babylon.max.js 2.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. }());
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. }());
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. }());
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.Forward = function () {
  834. return new Vector3(0, 0, 1.0);
  835. };
  836. Vector3.Right = function () {
  837. return new Vector3(1.0, 0, 0);
  838. };
  839. Vector3.Left = function () {
  840. return new Vector3(-1.0, 0, 0);
  841. };
  842. Vector3.TransformCoordinates = function (vector, transformation) {
  843. var result = Vector3.Zero();
  844. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  845. return result;
  846. };
  847. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  848. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  849. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  850. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  851. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  852. result.x = x / w;
  853. result.y = y / w;
  854. result.z = z / w;
  855. };
  856. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  857. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  858. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  859. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  860. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  861. result.x = rx / rw;
  862. result.y = ry / rw;
  863. result.z = rz / rw;
  864. };
  865. Vector3.TransformNormal = function (vector, transformation) {
  866. var result = Vector3.Zero();
  867. Vector3.TransformNormalToRef(vector, transformation, result);
  868. return result;
  869. };
  870. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  871. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  872. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  873. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  874. result.x = x;
  875. result.y = y;
  876. result.z = z;
  877. };
  878. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  879. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  880. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  881. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  882. };
  883. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  884. var squared = amount * amount;
  885. var cubed = amount * squared;
  886. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  887. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  888. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  889. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  890. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  891. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  892. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  893. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  894. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Clamp = function (value, min, max) {
  898. var x = value.x;
  899. x = (x > max.x) ? max.x : x;
  900. x = (x < min.x) ? min.x : x;
  901. var y = value.y;
  902. y = (y > max.y) ? max.y : y;
  903. y = (y < min.y) ? min.y : y;
  904. var z = value.z;
  905. z = (z > max.z) ? max.z : z;
  906. z = (z < min.z) ? min.z : z;
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  910. var squared = amount * amount;
  911. var cubed = amount * squared;
  912. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  913. var part2 = (-2.0 * cubed) + (3.0 * squared);
  914. var part3 = (cubed - (2.0 * squared)) + amount;
  915. var part4 = cubed - squared;
  916. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  917. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  918. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  919. return new Vector3(x, y, z);
  920. };
  921. Vector3.Lerp = function (start, end, amount) {
  922. var x = start.x + ((end.x - start.x) * amount);
  923. var y = start.y + ((end.y - start.y) * amount);
  924. var z = start.z + ((end.z - start.z) * amount);
  925. return new Vector3(x, y, z);
  926. };
  927. Vector3.Dot = function (left, right) {
  928. return (left.x * right.x + left.y * right.y + left.z * right.z);
  929. };
  930. Vector3.Cross = function (left, right) {
  931. var result = Vector3.Zero();
  932. Vector3.CrossToRef(left, right, result);
  933. return result;
  934. };
  935. Vector3.CrossToRef = function (left, right, result) {
  936. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  937. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  938. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  939. result.copyFrom(Tmp.Vector3[0]);
  940. };
  941. Vector3.Normalize = function (vector) {
  942. var result = Vector3.Zero();
  943. Vector3.NormalizeToRef(vector, result);
  944. return result;
  945. };
  946. Vector3.NormalizeToRef = function (vector, result) {
  947. result.copyFrom(vector);
  948. result.normalize();
  949. };
  950. Vector3.Project = function (vector, world, transform, viewport) {
  951. var cw = viewport.width;
  952. var ch = viewport.height;
  953. var cx = viewport.x;
  954. var cy = viewport.y;
  955. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  956. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  957. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  958. world.multiplyToRef(transform, matrix);
  959. matrix.multiplyToRef(viewportMatrix, matrix);
  960. return Vector3.TransformCoordinates(vector, matrix);
  961. };
  962. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  963. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  964. world.multiplyToRef(transform, matrix);
  965. matrix.invert();
  966. source.x = source.x / viewportWidth * 2 - 1;
  967. source.y = -(source.y / viewportHeight * 2 - 1);
  968. var vector = Vector3.TransformCoordinates(source, matrix);
  969. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  970. if (MathTools.WithinEpsilon(num, 1.0)) {
  971. vector = vector.scale(1.0 / num);
  972. }
  973. return vector;
  974. };
  975. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  976. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  977. world.multiplyToRef(view, matrix);
  978. matrix.multiplyToRef(projection, matrix);
  979. matrix.invert();
  980. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  981. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  982. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  983. if (MathTools.WithinEpsilon(num, 1.0)) {
  984. vector = vector.scale(1.0 / num);
  985. }
  986. return vector;
  987. };
  988. Vector3.Minimize = function (left, right) {
  989. var min = left.clone();
  990. min.MinimizeInPlace(right);
  991. return min;
  992. };
  993. Vector3.Maximize = function (left, right) {
  994. var max = left.clone();
  995. max.MaximizeInPlace(right);
  996. return max;
  997. };
  998. Vector3.Distance = function (value1, value2) {
  999. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1000. };
  1001. Vector3.DistanceSquared = function (value1, value2) {
  1002. var x = value1.x - value2.x;
  1003. var y = value1.y - value2.y;
  1004. var z = value1.z - value2.z;
  1005. return (x * x) + (y * y) + (z * z);
  1006. };
  1007. Vector3.Center = function (value1, value2) {
  1008. var center = value1.add(value2);
  1009. center.scaleInPlace(0.5);
  1010. return center;
  1011. };
  1012. /**
  1013. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1014. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1015. * to something in order to rotate it from its local system to the given target system.
  1016. */
  1017. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1018. var rotation = Vector3.Zero();
  1019. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1020. return rotation;
  1021. };
  1022. /**
  1023. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1024. */
  1025. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1026. var u = axis1.normalize();
  1027. var w = axis3.normalize();
  1028. // world axis
  1029. var X = Axis.X;
  1030. var Y = Axis.Y;
  1031. // equation unknowns and vars
  1032. var yaw = 0.0;
  1033. var pitch = 0.0;
  1034. var roll = 0.0;
  1035. var x = 0.0;
  1036. var y = 0.0;
  1037. var z = 0.0;
  1038. var t = 0.0;
  1039. var sign = -1.0;
  1040. var nbRevert = 0;
  1041. var cross = Tmp.Vector3[0];
  1042. var dot = 0.0;
  1043. // step 1 : rotation around w
  1044. // Rv3(u) = u1, and u1 belongs to plane xOz
  1045. // Rv3(w) = w1 = w invariant
  1046. var u1 = Tmp.Vector3[1];
  1047. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1048. z = 1.0;
  1049. }
  1050. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1051. x = 1.0;
  1052. }
  1053. else {
  1054. t = w.z / w.x;
  1055. x = -t * Math.sqrt(1 / (1 + t * t));
  1056. z = Math.sqrt(1 / (1 + t * t));
  1057. }
  1058. u1.x = x;
  1059. u1.y = y;
  1060. u1.z = z;
  1061. u1.normalize();
  1062. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1063. cross.normalize();
  1064. if (Vector3.Dot(w, cross) < 0) {
  1065. sign = 1.0;
  1066. }
  1067. dot = Vector3.Dot(u, u1);
  1068. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1069. roll = Math.acos(dot) * sign;
  1070. if (Vector3.Dot(u1, X) < 0) {
  1071. roll = Math.PI + roll;
  1072. u1 = u1.scaleInPlace(-1);
  1073. nbRevert++;
  1074. }
  1075. // step 2 : rotate around u1
  1076. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1077. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1078. var w2 = Tmp.Vector3[2];
  1079. var v2 = Tmp.Vector3[3];
  1080. x = 0.0;
  1081. y = 0.0;
  1082. z = 0.0;
  1083. sign = -1.0;
  1084. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1085. x = 1.0;
  1086. }
  1087. else {
  1088. t = u1.z / u1.x;
  1089. x = -t * Math.sqrt(1 / (1 + t * t));
  1090. z = Math.sqrt(1 / (1 + t * t));
  1091. }
  1092. w2.x = x;
  1093. w2.y = y;
  1094. w2.z = z;
  1095. w2.normalize();
  1096. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1097. v2.normalize();
  1098. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1099. cross.normalize();
  1100. if (Vector3.Dot(u1, cross) < 0) {
  1101. sign = 1.0;
  1102. }
  1103. dot = Vector3.Dot(w, w2);
  1104. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1105. pitch = Math.acos(dot) * sign;
  1106. if (Vector3.Dot(v2, Y) < 0) {
  1107. pitch = Math.PI + pitch;
  1108. nbRevert++;
  1109. }
  1110. // step 3 : rotate around v2
  1111. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1112. sign = -1.0;
  1113. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1114. cross.normalize();
  1115. if (Vector3.Dot(cross, Y) < 0) {
  1116. sign = 1.0;
  1117. }
  1118. dot = Vector3.Dot(u1, X);
  1119. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1120. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1121. if (dot < 0 && nbRevert < 2) {
  1122. yaw = Math.PI + yaw;
  1123. }
  1124. ref.x = pitch;
  1125. ref.y = yaw;
  1126. ref.z = roll;
  1127. };
  1128. return Vector3;
  1129. }());
  1130. BABYLON.Vector3 = Vector3;
  1131. //Vector4 class created for EulerAngle class conversion to Quaternion
  1132. var Vector4 = (function () {
  1133. function Vector4(x, y, z, w) {
  1134. this.x = x;
  1135. this.y = y;
  1136. this.z = z;
  1137. this.w = w;
  1138. }
  1139. Vector4.prototype.toString = function () {
  1140. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1141. };
  1142. Vector4.prototype.getClassName = function () {
  1143. return "Vector4";
  1144. };
  1145. Vector4.prototype.getHashCode = function () {
  1146. var hash = this.x || 0;
  1147. hash = (hash * 397) ^ (this.y || 0);
  1148. hash = (hash * 397) ^ (this.z || 0);
  1149. hash = (hash * 397) ^ (this.w || 0);
  1150. return hash;
  1151. };
  1152. // Operators
  1153. Vector4.prototype.asArray = function () {
  1154. var result = [];
  1155. this.toArray(result, 0);
  1156. return result;
  1157. };
  1158. Vector4.prototype.toArray = function (array, index) {
  1159. if (index === undefined) {
  1160. index = 0;
  1161. }
  1162. array[index] = this.x;
  1163. array[index + 1] = this.y;
  1164. array[index + 2] = this.z;
  1165. array[index + 3] = this.w;
  1166. return this;
  1167. };
  1168. Vector4.prototype.addInPlace = function (otherVector) {
  1169. this.x += otherVector.x;
  1170. this.y += otherVector.y;
  1171. this.z += otherVector.z;
  1172. this.w += otherVector.w;
  1173. return this;
  1174. };
  1175. Vector4.prototype.add = function (otherVector) {
  1176. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1177. };
  1178. Vector4.prototype.addToRef = function (otherVector, result) {
  1179. result.x = this.x + otherVector.x;
  1180. result.y = this.y + otherVector.y;
  1181. result.z = this.z + otherVector.z;
  1182. result.w = this.w + otherVector.w;
  1183. return this;
  1184. };
  1185. Vector4.prototype.subtractInPlace = function (otherVector) {
  1186. this.x -= otherVector.x;
  1187. this.y -= otherVector.y;
  1188. this.z -= otherVector.z;
  1189. this.w -= otherVector.w;
  1190. return this;
  1191. };
  1192. Vector4.prototype.subtract = function (otherVector) {
  1193. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1194. };
  1195. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1196. result.x = this.x - otherVector.x;
  1197. result.y = this.y - otherVector.y;
  1198. result.z = this.z - otherVector.z;
  1199. result.w = this.w - otherVector.w;
  1200. return this;
  1201. };
  1202. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1203. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1204. };
  1205. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1206. result.x = this.x - x;
  1207. result.y = this.y - y;
  1208. result.z = this.z - z;
  1209. result.w = this.w - w;
  1210. return this;
  1211. };
  1212. Vector4.prototype.negate = function () {
  1213. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1214. };
  1215. Vector4.prototype.scaleInPlace = function (scale) {
  1216. this.x *= scale;
  1217. this.y *= scale;
  1218. this.z *= scale;
  1219. this.w *= scale;
  1220. return this;
  1221. };
  1222. Vector4.prototype.scale = function (scale) {
  1223. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1224. };
  1225. Vector4.prototype.scaleToRef = function (scale, result) {
  1226. result.x = this.x * scale;
  1227. result.y = this.y * scale;
  1228. result.z = this.z * scale;
  1229. result.w = this.w * scale;
  1230. };
  1231. Vector4.prototype.equals = function (otherVector) {
  1232. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1233. };
  1234. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1235. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1236. return otherVector
  1237. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1238. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1239. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1240. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1241. };
  1242. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1243. return this.x === x && this.y === y && this.z === z && this.w === w;
  1244. };
  1245. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1246. this.x *= otherVector.x;
  1247. this.y *= otherVector.y;
  1248. this.z *= otherVector.z;
  1249. this.w *= otherVector.w;
  1250. return this;
  1251. };
  1252. Vector4.prototype.multiply = function (otherVector) {
  1253. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1254. };
  1255. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1256. result.x = this.x * otherVector.x;
  1257. result.y = this.y * otherVector.y;
  1258. result.z = this.z * otherVector.z;
  1259. result.w = this.w * otherVector.w;
  1260. return this;
  1261. };
  1262. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1263. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1264. };
  1265. Vector4.prototype.divide = function (otherVector) {
  1266. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1267. };
  1268. Vector4.prototype.divideToRef = function (otherVector, result) {
  1269. result.x = this.x / otherVector.x;
  1270. result.y = this.y / otherVector.y;
  1271. result.z = this.z / otherVector.z;
  1272. result.w = this.w / otherVector.w;
  1273. return this;
  1274. };
  1275. Vector4.prototype.MinimizeInPlace = function (other) {
  1276. if (other.x < this.x)
  1277. this.x = other.x;
  1278. if (other.y < this.y)
  1279. this.y = other.y;
  1280. if (other.z < this.z)
  1281. this.z = other.z;
  1282. if (other.w < this.w)
  1283. this.w = other.w;
  1284. return this;
  1285. };
  1286. Vector4.prototype.MaximizeInPlace = function (other) {
  1287. if (other.x > this.x)
  1288. this.x = other.x;
  1289. if (other.y > this.y)
  1290. this.y = other.y;
  1291. if (other.z > this.z)
  1292. this.z = other.z;
  1293. if (other.w > this.w)
  1294. this.w = other.w;
  1295. return this;
  1296. };
  1297. // Properties
  1298. Vector4.prototype.length = function () {
  1299. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1300. };
  1301. Vector4.prototype.lengthSquared = function () {
  1302. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1303. };
  1304. // Methods
  1305. Vector4.prototype.normalize = function () {
  1306. var len = this.length();
  1307. if (len === 0)
  1308. return this;
  1309. var num = 1.0 / len;
  1310. this.x *= num;
  1311. this.y *= num;
  1312. this.z *= num;
  1313. this.w *= num;
  1314. return this;
  1315. };
  1316. Vector4.prototype.toVector3 = function () {
  1317. return new Vector3(this.x, this.y, this.z);
  1318. };
  1319. Vector4.prototype.clone = function () {
  1320. return new Vector4(this.x, this.y, this.z, this.w);
  1321. };
  1322. Vector4.prototype.copyFrom = function (source) {
  1323. this.x = source.x;
  1324. this.y = source.y;
  1325. this.z = source.z;
  1326. this.w = source.w;
  1327. return this;
  1328. };
  1329. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1330. this.x = x;
  1331. this.y = y;
  1332. this.z = z;
  1333. this.w = w;
  1334. return this;
  1335. };
  1336. // Statics
  1337. Vector4.FromArray = function (array, offset) {
  1338. if (!offset) {
  1339. offset = 0;
  1340. }
  1341. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1342. };
  1343. Vector4.FromArrayToRef = function (array, offset, result) {
  1344. result.x = array[offset];
  1345. result.y = array[offset + 1];
  1346. result.z = array[offset + 2];
  1347. result.w = array[offset + 3];
  1348. };
  1349. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1350. result.x = array[offset];
  1351. result.y = array[offset + 1];
  1352. result.z = array[offset + 2];
  1353. result.w = array[offset + 3];
  1354. };
  1355. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1356. result.x = x;
  1357. result.y = y;
  1358. result.z = z;
  1359. result.w = w;
  1360. };
  1361. Vector4.Zero = function () {
  1362. return new Vector4(0, 0, 0, 0);
  1363. };
  1364. Vector4.Normalize = function (vector) {
  1365. var result = Vector4.Zero();
  1366. Vector4.NormalizeToRef(vector, result);
  1367. return result;
  1368. };
  1369. Vector4.NormalizeToRef = function (vector, result) {
  1370. result.copyFrom(vector);
  1371. result.normalize();
  1372. };
  1373. Vector4.Minimize = function (left, right) {
  1374. var min = left.clone();
  1375. min.MinimizeInPlace(right);
  1376. return min;
  1377. };
  1378. Vector4.Maximize = function (left, right) {
  1379. var max = left.clone();
  1380. max.MaximizeInPlace(right);
  1381. return max;
  1382. };
  1383. Vector4.Distance = function (value1, value2) {
  1384. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1385. };
  1386. Vector4.DistanceSquared = function (value1, value2) {
  1387. var x = value1.x - value2.x;
  1388. var y = value1.y - value2.y;
  1389. var z = value1.z - value2.z;
  1390. var w = value1.w - value2.w;
  1391. return (x * x) + (y * y) + (z * z) + (w * w);
  1392. };
  1393. Vector4.Center = function (value1, value2) {
  1394. var center = value1.add(value2);
  1395. center.scaleInPlace(0.5);
  1396. return center;
  1397. };
  1398. return Vector4;
  1399. }());
  1400. BABYLON.Vector4 = Vector4;
  1401. var Size = (function () {
  1402. function Size(width, height) {
  1403. this.width = width;
  1404. this.height = height;
  1405. }
  1406. Size.prototype.toString = function () {
  1407. return "{W: " + this.width + ", H: " + this.height + "}";
  1408. };
  1409. Size.prototype.getClassName = function () {
  1410. return "Size";
  1411. };
  1412. Size.prototype.getHashCode = function () {
  1413. var hash = this.width || 0;
  1414. hash = (hash * 397) ^ (this.height || 0);
  1415. return hash;
  1416. };
  1417. Size.prototype.copyFrom = function (src) {
  1418. this.width = src.width;
  1419. this.height = src.height;
  1420. };
  1421. Size.prototype.copyFromFloats = function (width, height) {
  1422. this.width = width;
  1423. this.height = height;
  1424. };
  1425. Size.prototype.multiplyByFloats = function (w, h) {
  1426. return new Size(this.width * w, this.height * h);
  1427. };
  1428. Size.prototype.clone = function () {
  1429. return new Size(this.width, this.height);
  1430. };
  1431. Size.prototype.equals = function (other) {
  1432. if (!other) {
  1433. return false;
  1434. }
  1435. return (this.width === other.width) && (this.height === other.height);
  1436. };
  1437. Object.defineProperty(Size.prototype, "surface", {
  1438. get: function () {
  1439. return this.width * this.height;
  1440. },
  1441. enumerable: true,
  1442. configurable: true
  1443. });
  1444. Size.Zero = function () {
  1445. return new Size(0, 0);
  1446. };
  1447. Size.prototype.add = function (otherSize) {
  1448. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1449. return r;
  1450. };
  1451. Size.prototype.substract = function (otherSize) {
  1452. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1453. return r;
  1454. };
  1455. Size.Lerp = function (start, end, amount) {
  1456. var w = start.width + ((end.width - start.width) * amount);
  1457. var h = start.height + ((end.height - start.height) * amount);
  1458. return new Size(w, h);
  1459. };
  1460. return Size;
  1461. }());
  1462. BABYLON.Size = Size;
  1463. var Quaternion = (function () {
  1464. function Quaternion(x, y, z, w) {
  1465. if (x === void 0) { x = 0; }
  1466. if (y === void 0) { y = 0; }
  1467. if (z === void 0) { z = 0; }
  1468. if (w === void 0) { w = 1; }
  1469. this.x = x;
  1470. this.y = y;
  1471. this.z = z;
  1472. this.w = w;
  1473. }
  1474. Quaternion.prototype.toString = function () {
  1475. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1476. };
  1477. Quaternion.prototype.getClassName = function () {
  1478. return "Quaternion";
  1479. };
  1480. Quaternion.prototype.getHashCode = function () {
  1481. var hash = this.x || 0;
  1482. hash = (hash * 397) ^ (this.y || 0);
  1483. hash = (hash * 397) ^ (this.z || 0);
  1484. hash = (hash * 397) ^ (this.w || 0);
  1485. return hash;
  1486. };
  1487. Quaternion.prototype.asArray = function () {
  1488. return [this.x, this.y, this.z, this.w];
  1489. };
  1490. Quaternion.prototype.equals = function (otherQuaternion) {
  1491. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1492. };
  1493. Quaternion.prototype.clone = function () {
  1494. return new Quaternion(this.x, this.y, this.z, this.w);
  1495. };
  1496. Quaternion.prototype.copyFrom = function (other) {
  1497. this.x = other.x;
  1498. this.y = other.y;
  1499. this.z = other.z;
  1500. this.w = other.w;
  1501. return this;
  1502. };
  1503. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1504. this.x = x;
  1505. this.y = y;
  1506. this.z = z;
  1507. this.w = w;
  1508. return this;
  1509. };
  1510. Quaternion.prototype.add = function (other) {
  1511. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1512. };
  1513. Quaternion.prototype.subtract = function (other) {
  1514. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1515. };
  1516. Quaternion.prototype.scale = function (value) {
  1517. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1518. };
  1519. Quaternion.prototype.multiply = function (q1) {
  1520. var result = new Quaternion(0, 0, 0, 1.0);
  1521. this.multiplyToRef(q1, result);
  1522. return result;
  1523. };
  1524. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1525. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1526. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1527. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1528. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1529. result.copyFromFloats(x, y, z, w);
  1530. return this;
  1531. };
  1532. Quaternion.prototype.multiplyInPlace = function (q1) {
  1533. this.multiplyToRef(q1, this);
  1534. return this;
  1535. };
  1536. Quaternion.prototype.conjugateToRef = function (ref) {
  1537. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1538. return this;
  1539. };
  1540. Quaternion.prototype.conjugateInPlace = function () {
  1541. this.x *= -1;
  1542. this.y *= -1;
  1543. this.z *= -1;
  1544. return this;
  1545. };
  1546. Quaternion.prototype.conjugate = function () {
  1547. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1548. return result;
  1549. };
  1550. Quaternion.prototype.length = function () {
  1551. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1552. };
  1553. Quaternion.prototype.normalize = function () {
  1554. var length = 1.0 / this.length();
  1555. this.x *= length;
  1556. this.y *= length;
  1557. this.z *= length;
  1558. this.w *= length;
  1559. return this;
  1560. };
  1561. Quaternion.prototype.toEulerAngles = function (order) {
  1562. if (order === void 0) { order = "YZX"; }
  1563. var result = Vector3.Zero();
  1564. this.toEulerAnglesToRef(result, order);
  1565. return result;
  1566. };
  1567. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1568. if (order === void 0) { order = "YZX"; }
  1569. var qx = this.x;
  1570. var qy = this.y;
  1571. var qz = this.z;
  1572. var qw = this.w;
  1573. var xsqr = qx * qx;
  1574. var t0 = -2.0 * (xsqr + qy * qy) + 1.0;
  1575. var t1 = 2.0 * (qz * qx + qw * qy);
  1576. var t2 = -2.0 * (qz * qy - qw * qx);
  1577. var t3 = 2.0 * (qx * qy + qw * qz);
  1578. var t4 = -2.0 * (qz * qz + xsqr) + 1.0;
  1579. t2 = t2 > 1.0 ? 1.0 : t2;
  1580. t2 = t2 < -1.0 ? -1.0 : t2;
  1581. result.x = Math.asin(t2);
  1582. result.z = Math.atan2(t3, t4);
  1583. result.y = Math.atan2(t1, t0);
  1584. return this;
  1585. };
  1586. ;
  1587. Quaternion.prototype.toRotationMatrix = function (result) {
  1588. var xx = this.x * this.x;
  1589. var yy = this.y * this.y;
  1590. var zz = this.z * this.z;
  1591. var xy = this.x * this.y;
  1592. var zw = this.z * this.w;
  1593. var zx = this.z * this.x;
  1594. var yw = this.y * this.w;
  1595. var yz = this.y * this.z;
  1596. var xw = this.x * this.w;
  1597. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1598. result.m[1] = 2.0 * (xy + zw);
  1599. result.m[2] = 2.0 * (zx - yw);
  1600. result.m[3] = 0;
  1601. result.m[4] = 2.0 * (xy - zw);
  1602. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1603. result.m[6] = 2.0 * (yz + xw);
  1604. result.m[7] = 0;
  1605. result.m[8] = 2.0 * (zx + yw);
  1606. result.m[9] = 2.0 * (yz - xw);
  1607. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1608. result.m[11] = 0;
  1609. result.m[12] = 0;
  1610. result.m[13] = 0;
  1611. result.m[14] = 0;
  1612. result.m[15] = 1.0;
  1613. return this;
  1614. };
  1615. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1616. Quaternion.FromRotationMatrixToRef(matrix, this);
  1617. return this;
  1618. };
  1619. // Statics
  1620. Quaternion.FromRotationMatrix = function (matrix) {
  1621. var result = new Quaternion();
  1622. Quaternion.FromRotationMatrixToRef(matrix, result);
  1623. return result;
  1624. };
  1625. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1626. var data = matrix.m;
  1627. var m11 = data[0], m12 = data[4], m13 = data[8];
  1628. var m21 = data[1], m22 = data[5], m23 = data[9];
  1629. var m31 = data[2], m32 = data[6], m33 = data[10];
  1630. var trace = m11 + m22 + m33;
  1631. var s;
  1632. if (trace > 0) {
  1633. s = 0.5 / Math.sqrt(trace + 1.0);
  1634. result.w = 0.25 / s;
  1635. result.x = (m32 - m23) * s;
  1636. result.y = (m13 - m31) * s;
  1637. result.z = (m21 - m12) * s;
  1638. }
  1639. else if (m11 > m22 && m11 > m33) {
  1640. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1641. result.w = (m32 - m23) / s;
  1642. result.x = 0.25 * s;
  1643. result.y = (m12 + m21) / s;
  1644. result.z = (m13 + m31) / s;
  1645. }
  1646. else if (m22 > m33) {
  1647. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1648. result.w = (m13 - m31) / s;
  1649. result.x = (m12 + m21) / s;
  1650. result.y = 0.25 * s;
  1651. result.z = (m23 + m32) / s;
  1652. }
  1653. else {
  1654. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1655. result.w = (m21 - m12) / s;
  1656. result.x = (m13 + m31) / s;
  1657. result.y = (m23 + m32) / s;
  1658. result.z = 0.25 * s;
  1659. }
  1660. };
  1661. Quaternion.Inverse = function (q) {
  1662. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1663. };
  1664. Quaternion.Identity = function () {
  1665. return new Quaternion(0, 0, 0, 1);
  1666. };
  1667. Quaternion.RotationAxis = function (axis, angle) {
  1668. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1669. };
  1670. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1671. var sin = Math.sin(angle / 2);
  1672. axis.normalize();
  1673. result.w = Math.cos(angle / 2);
  1674. result.x = axis.x * sin;
  1675. result.y = axis.y * sin;
  1676. result.z = axis.z * sin;
  1677. return result;
  1678. };
  1679. Quaternion.FromArray = function (array, offset) {
  1680. if (!offset) {
  1681. offset = 0;
  1682. }
  1683. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1684. };
  1685. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1686. var q = new Quaternion();
  1687. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1688. return q;
  1689. };
  1690. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1691. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1692. var halfRoll = roll * 0.5;
  1693. var halfPitch = pitch * 0.5;
  1694. var halfYaw = yaw * 0.5;
  1695. var sinRoll = Math.sin(halfRoll);
  1696. var cosRoll = Math.cos(halfRoll);
  1697. var sinPitch = Math.sin(halfPitch);
  1698. var cosPitch = Math.cos(halfPitch);
  1699. var sinYaw = Math.sin(halfYaw);
  1700. var cosYaw = Math.cos(halfYaw);
  1701. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1702. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1703. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1704. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1705. };
  1706. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1707. var result = new Quaternion();
  1708. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1709. return result;
  1710. };
  1711. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1712. // Produces a quaternion from Euler angles in the z-x-z orientation
  1713. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1714. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1715. var halfBeta = beta * 0.5;
  1716. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1717. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1718. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1719. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1720. };
  1721. Quaternion.Slerp = function (left, right, amount) {
  1722. var num2;
  1723. var num3;
  1724. var num = amount;
  1725. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1726. var flag = false;
  1727. if (num4 < 0) {
  1728. flag = true;
  1729. num4 = -num4;
  1730. }
  1731. if (num4 > 0.999999) {
  1732. num3 = 1 - num;
  1733. num2 = flag ? -num : num;
  1734. }
  1735. else {
  1736. var num5 = Math.acos(num4);
  1737. var num6 = (1.0 / Math.sin(num5));
  1738. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1739. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1740. }
  1741. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1742. };
  1743. return Quaternion;
  1744. }());
  1745. BABYLON.Quaternion = Quaternion;
  1746. var Matrix = (function () {
  1747. function Matrix() {
  1748. this.m = new Float32Array(16);
  1749. }
  1750. // Properties
  1751. Matrix.prototype.isIdentity = function () {
  1752. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1753. return false;
  1754. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1755. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1756. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1757. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1758. return false;
  1759. return true;
  1760. };
  1761. Matrix.prototype.determinant = function () {
  1762. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1763. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1764. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1765. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1766. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1767. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1768. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1769. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1770. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1771. };
  1772. // Methods
  1773. Matrix.prototype.toArray = function () {
  1774. return this.m;
  1775. };
  1776. Matrix.prototype.asArray = function () {
  1777. return this.toArray();
  1778. };
  1779. Matrix.prototype.invert = function () {
  1780. this.invertToRef(this);
  1781. return this;
  1782. };
  1783. Matrix.prototype.reset = function () {
  1784. for (var index = 0; index < 16; index++) {
  1785. this.m[index] = 0;
  1786. }
  1787. return this;
  1788. };
  1789. Matrix.prototype.add = function (other) {
  1790. var result = new Matrix();
  1791. this.addToRef(other, result);
  1792. return result;
  1793. };
  1794. Matrix.prototype.addToRef = function (other, result) {
  1795. for (var index = 0; index < 16; index++) {
  1796. result.m[index] = this.m[index] + other.m[index];
  1797. }
  1798. return this;
  1799. };
  1800. Matrix.prototype.addToSelf = function (other) {
  1801. for (var index = 0; index < 16; index++) {
  1802. this.m[index] += other.m[index];
  1803. }
  1804. return this;
  1805. };
  1806. Matrix.prototype.invertToRef = function (other) {
  1807. var l1 = this.m[0];
  1808. var l2 = this.m[1];
  1809. var l3 = this.m[2];
  1810. var l4 = this.m[3];
  1811. var l5 = this.m[4];
  1812. var l6 = this.m[5];
  1813. var l7 = this.m[6];
  1814. var l8 = this.m[7];
  1815. var l9 = this.m[8];
  1816. var l10 = this.m[9];
  1817. var l11 = this.m[10];
  1818. var l12 = this.m[11];
  1819. var l13 = this.m[12];
  1820. var l14 = this.m[13];
  1821. var l15 = this.m[14];
  1822. var l16 = this.m[15];
  1823. var l17 = (l11 * l16) - (l12 * l15);
  1824. var l18 = (l10 * l16) - (l12 * l14);
  1825. var l19 = (l10 * l15) - (l11 * l14);
  1826. var l20 = (l9 * l16) - (l12 * l13);
  1827. var l21 = (l9 * l15) - (l11 * l13);
  1828. var l22 = (l9 * l14) - (l10 * l13);
  1829. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1830. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1831. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1832. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1833. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1834. var l28 = (l7 * l16) - (l8 * l15);
  1835. var l29 = (l6 * l16) - (l8 * l14);
  1836. var l30 = (l6 * l15) - (l7 * l14);
  1837. var l31 = (l5 * l16) - (l8 * l13);
  1838. var l32 = (l5 * l15) - (l7 * l13);
  1839. var l33 = (l5 * l14) - (l6 * l13);
  1840. var l34 = (l7 * l12) - (l8 * l11);
  1841. var l35 = (l6 * l12) - (l8 * l10);
  1842. var l36 = (l6 * l11) - (l7 * l10);
  1843. var l37 = (l5 * l12) - (l8 * l9);
  1844. var l38 = (l5 * l11) - (l7 * l9);
  1845. var l39 = (l5 * l10) - (l6 * l9);
  1846. other.m[0] = l23 * l27;
  1847. other.m[4] = l24 * l27;
  1848. other.m[8] = l25 * l27;
  1849. other.m[12] = l26 * l27;
  1850. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1851. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1852. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1853. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1854. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1855. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1856. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1857. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1858. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1859. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1860. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1861. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1862. return this;
  1863. };
  1864. Matrix.prototype.setTranslation = function (vector3) {
  1865. this.m[12] = vector3.x;
  1866. this.m[13] = vector3.y;
  1867. this.m[14] = vector3.z;
  1868. return this;
  1869. };
  1870. Matrix.prototype.getTranslation = function () {
  1871. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1872. };
  1873. Matrix.prototype.multiply = function (other) {
  1874. var result = new Matrix();
  1875. this.multiplyToRef(other, result);
  1876. return result;
  1877. };
  1878. Matrix.prototype.copyFrom = function (other) {
  1879. for (var index = 0; index < 16; index++) {
  1880. this.m[index] = other.m[index];
  1881. }
  1882. return this;
  1883. };
  1884. Matrix.prototype.copyToArray = function (array, offset) {
  1885. if (offset === void 0) { offset = 0; }
  1886. for (var index = 0; index < 16; index++) {
  1887. array[offset + index] = this.m[index];
  1888. }
  1889. return this;
  1890. };
  1891. Matrix.prototype.multiplyToRef = function (other, result) {
  1892. this.multiplyToArray(other, result.m, 0);
  1893. return this;
  1894. };
  1895. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1896. var tm0 = this.m[0];
  1897. var tm1 = this.m[1];
  1898. var tm2 = this.m[2];
  1899. var tm3 = this.m[3];
  1900. var tm4 = this.m[4];
  1901. var tm5 = this.m[5];
  1902. var tm6 = this.m[6];
  1903. var tm7 = this.m[7];
  1904. var tm8 = this.m[8];
  1905. var tm9 = this.m[9];
  1906. var tm10 = this.m[10];
  1907. var tm11 = this.m[11];
  1908. var tm12 = this.m[12];
  1909. var tm13 = this.m[13];
  1910. var tm14 = this.m[14];
  1911. var tm15 = this.m[15];
  1912. var om0 = other.m[0];
  1913. var om1 = other.m[1];
  1914. var om2 = other.m[2];
  1915. var om3 = other.m[3];
  1916. var om4 = other.m[4];
  1917. var om5 = other.m[5];
  1918. var om6 = other.m[6];
  1919. var om7 = other.m[7];
  1920. var om8 = other.m[8];
  1921. var om9 = other.m[9];
  1922. var om10 = other.m[10];
  1923. var om11 = other.m[11];
  1924. var om12 = other.m[12];
  1925. var om13 = other.m[13];
  1926. var om14 = other.m[14];
  1927. var om15 = other.m[15];
  1928. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1929. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1930. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1931. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1932. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1933. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1934. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1935. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1936. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1937. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1938. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1939. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1940. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1941. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1942. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1943. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1944. return this;
  1945. };
  1946. Matrix.prototype.equals = function (value) {
  1947. return value &&
  1948. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1949. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1950. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1951. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1952. };
  1953. Matrix.prototype.clone = function () {
  1954. 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]);
  1955. };
  1956. Matrix.prototype.getClassName = function () {
  1957. return "Matrix";
  1958. };
  1959. Matrix.prototype.getHashCode = function () {
  1960. var hash = this.m[0] || 0;
  1961. for (var i = 1; i < 16; i++) {
  1962. hash = (hash * 397) ^ (this.m[i] || 0);
  1963. }
  1964. return hash;
  1965. };
  1966. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1967. translation.x = this.m[12];
  1968. translation.y = this.m[13];
  1969. translation.z = this.m[14];
  1970. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1971. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1972. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1973. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1974. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1975. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1976. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1977. rotation.x = 0;
  1978. rotation.y = 0;
  1979. rotation.z = 0;
  1980. rotation.w = 1;
  1981. return false;
  1982. }
  1983. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, Tmp.Matrix[0]);
  1984. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  1985. return true;
  1986. };
  1987. // Statics
  1988. Matrix.FromArray = function (array, offset) {
  1989. var result = new Matrix();
  1990. if (!offset) {
  1991. offset = 0;
  1992. }
  1993. Matrix.FromArrayToRef(array, offset, result);
  1994. return result;
  1995. };
  1996. Matrix.FromArrayToRef = function (array, offset, result) {
  1997. for (var index = 0; index < 16; index++) {
  1998. result.m[index] = array[index + offset];
  1999. }
  2000. };
  2001. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2002. for (var index = 0; index < 16; index++) {
  2003. result.m[index] = array[index + offset] * scale;
  2004. }
  2005. };
  2006. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2007. result.m[0] = initialM11;
  2008. result.m[1] = initialM12;
  2009. result.m[2] = initialM13;
  2010. result.m[3] = initialM14;
  2011. result.m[4] = initialM21;
  2012. result.m[5] = initialM22;
  2013. result.m[6] = initialM23;
  2014. result.m[7] = initialM24;
  2015. result.m[8] = initialM31;
  2016. result.m[9] = initialM32;
  2017. result.m[10] = initialM33;
  2018. result.m[11] = initialM34;
  2019. result.m[12] = initialM41;
  2020. result.m[13] = initialM42;
  2021. result.m[14] = initialM43;
  2022. result.m[15] = initialM44;
  2023. };
  2024. Matrix.prototype.getRow = function (index) {
  2025. if (index < 0 || index > 3) {
  2026. return null;
  2027. }
  2028. var i = index * 4;
  2029. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2030. };
  2031. Matrix.prototype.setRow = function (index, row) {
  2032. if (index < 0 || index > 3) {
  2033. return this;
  2034. }
  2035. var i = index * 4;
  2036. this.m[i + 0] = row.x;
  2037. this.m[i + 1] = row.y;
  2038. this.m[i + 2] = row.z;
  2039. this.m[i + 3] = row.w;
  2040. return this;
  2041. };
  2042. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2043. var result = new Matrix();
  2044. result.m[0] = initialM11;
  2045. result.m[1] = initialM12;
  2046. result.m[2] = initialM13;
  2047. result.m[3] = initialM14;
  2048. result.m[4] = initialM21;
  2049. result.m[5] = initialM22;
  2050. result.m[6] = initialM23;
  2051. result.m[7] = initialM24;
  2052. result.m[8] = initialM31;
  2053. result.m[9] = initialM32;
  2054. result.m[10] = initialM33;
  2055. result.m[11] = initialM34;
  2056. result.m[12] = initialM41;
  2057. result.m[13] = initialM42;
  2058. result.m[14] = initialM43;
  2059. result.m[15] = initialM44;
  2060. return result;
  2061. };
  2062. Matrix.Compose = function (scale, rotation, translation) {
  2063. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2064. var rotationMatrix = Matrix.Identity();
  2065. rotation.toRotationMatrix(rotationMatrix);
  2066. result = result.multiply(rotationMatrix);
  2067. result.setTranslation(translation);
  2068. return result;
  2069. };
  2070. Matrix.Identity = function () {
  2071. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2072. };
  2073. Matrix.IdentityToRef = function (result) {
  2074. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2075. };
  2076. Matrix.Zero = function () {
  2077. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2078. };
  2079. Matrix.RotationX = function (angle) {
  2080. var result = new Matrix();
  2081. Matrix.RotationXToRef(angle, result);
  2082. return result;
  2083. };
  2084. Matrix.Invert = function (source) {
  2085. var result = new Matrix();
  2086. source.invertToRef(result);
  2087. return result;
  2088. };
  2089. Matrix.RotationXToRef = function (angle, result) {
  2090. var s = Math.sin(angle);
  2091. var c = Math.cos(angle);
  2092. result.m[0] = 1.0;
  2093. result.m[15] = 1.0;
  2094. result.m[5] = c;
  2095. result.m[10] = c;
  2096. result.m[9] = -s;
  2097. result.m[6] = s;
  2098. result.m[1] = 0;
  2099. result.m[2] = 0;
  2100. result.m[3] = 0;
  2101. result.m[4] = 0;
  2102. result.m[7] = 0;
  2103. result.m[8] = 0;
  2104. result.m[11] = 0;
  2105. result.m[12] = 0;
  2106. result.m[13] = 0;
  2107. result.m[14] = 0;
  2108. };
  2109. Matrix.RotationY = function (angle) {
  2110. var result = new Matrix();
  2111. Matrix.RotationYToRef(angle, result);
  2112. return result;
  2113. };
  2114. Matrix.RotationYToRef = function (angle, result) {
  2115. var s = Math.sin(angle);
  2116. var c = Math.cos(angle);
  2117. result.m[5] = 1.0;
  2118. result.m[15] = 1.0;
  2119. result.m[0] = c;
  2120. result.m[2] = -s;
  2121. result.m[8] = s;
  2122. result.m[10] = c;
  2123. result.m[1] = 0;
  2124. result.m[3] = 0;
  2125. result.m[4] = 0;
  2126. result.m[6] = 0;
  2127. result.m[7] = 0;
  2128. result.m[9] = 0;
  2129. result.m[11] = 0;
  2130. result.m[12] = 0;
  2131. result.m[13] = 0;
  2132. result.m[14] = 0;
  2133. };
  2134. Matrix.RotationZ = function (angle) {
  2135. var result = new Matrix();
  2136. Matrix.RotationZToRef(angle, result);
  2137. return result;
  2138. };
  2139. Matrix.RotationZToRef = function (angle, result) {
  2140. var s = Math.sin(angle);
  2141. var c = Math.cos(angle);
  2142. result.m[10] = 1.0;
  2143. result.m[15] = 1.0;
  2144. result.m[0] = c;
  2145. result.m[1] = s;
  2146. result.m[4] = -s;
  2147. result.m[5] = c;
  2148. result.m[2] = 0;
  2149. result.m[3] = 0;
  2150. result.m[6] = 0;
  2151. result.m[7] = 0;
  2152. result.m[8] = 0;
  2153. result.m[9] = 0;
  2154. result.m[11] = 0;
  2155. result.m[12] = 0;
  2156. result.m[13] = 0;
  2157. result.m[14] = 0;
  2158. };
  2159. Matrix.RotationAxis = function (axis, angle) {
  2160. var result = Matrix.Zero();
  2161. Matrix.RotationAxisToRef(axis, angle, result);
  2162. return result;
  2163. };
  2164. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2165. var s = Math.sin(-angle);
  2166. var c = Math.cos(-angle);
  2167. var c1 = 1 - c;
  2168. axis.normalize();
  2169. result.m[0] = (axis.x * axis.x) * c1 + c;
  2170. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2171. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2172. result.m[3] = 0.0;
  2173. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2174. result.m[5] = (axis.y * axis.y) * c1 + c;
  2175. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2176. result.m[7] = 0.0;
  2177. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2178. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2179. result.m[10] = (axis.z * axis.z) * c1 + c;
  2180. result.m[11] = 0.0;
  2181. result.m[15] = 1.0;
  2182. };
  2183. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2184. var result = new Matrix();
  2185. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2186. return result;
  2187. };
  2188. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2189. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2190. this._tempQuaternion.toRotationMatrix(result);
  2191. };
  2192. Matrix.Scaling = function (x, y, z) {
  2193. var result = Matrix.Zero();
  2194. Matrix.ScalingToRef(x, y, z, result);
  2195. return result;
  2196. };
  2197. Matrix.ScalingToRef = function (x, y, z, result) {
  2198. result.m[0] = x;
  2199. result.m[1] = 0;
  2200. result.m[2] = 0;
  2201. result.m[3] = 0;
  2202. result.m[4] = 0;
  2203. result.m[5] = y;
  2204. result.m[6] = 0;
  2205. result.m[7] = 0;
  2206. result.m[8] = 0;
  2207. result.m[9] = 0;
  2208. result.m[10] = z;
  2209. result.m[11] = 0;
  2210. result.m[12] = 0;
  2211. result.m[13] = 0;
  2212. result.m[14] = 0;
  2213. result.m[15] = 1.0;
  2214. };
  2215. Matrix.Translation = function (x, y, z) {
  2216. var result = Matrix.Identity();
  2217. Matrix.TranslationToRef(x, y, z, result);
  2218. return result;
  2219. };
  2220. Matrix.TranslationToRef = function (x, y, z, result) {
  2221. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2222. };
  2223. Matrix.Lerp = function (startValue, endValue, gradient) {
  2224. var result = Matrix.Zero();
  2225. for (var index = 0; index < 16; index++) {
  2226. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2227. }
  2228. return result;
  2229. };
  2230. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2231. var startScale = new Vector3(0, 0, 0);
  2232. var startRotation = new Quaternion();
  2233. var startTranslation = new Vector3(0, 0, 0);
  2234. startValue.decompose(startScale, startRotation, startTranslation);
  2235. var endScale = new Vector3(0, 0, 0);
  2236. var endRotation = new Quaternion();
  2237. var endTranslation = new Vector3(0, 0, 0);
  2238. endValue.decompose(endScale, endRotation, endTranslation);
  2239. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2240. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2241. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2242. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2243. };
  2244. Matrix.LookAtLH = function (eye, target, up) {
  2245. var result = Matrix.Zero();
  2246. Matrix.LookAtLHToRef(eye, target, up, result);
  2247. return result;
  2248. };
  2249. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2250. // Z axis
  2251. target.subtractToRef(eye, this._zAxis);
  2252. this._zAxis.normalize();
  2253. // X axis
  2254. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2255. if (this._xAxis.lengthSquared() === 0) {
  2256. this._xAxis.x = 1.0;
  2257. }
  2258. else {
  2259. this._xAxis.normalize();
  2260. }
  2261. // Y axis
  2262. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2263. this._yAxis.normalize();
  2264. // Eye angles
  2265. var ex = -Vector3.Dot(this._xAxis, eye);
  2266. var ey = -Vector3.Dot(this._yAxis, eye);
  2267. var ez = -Vector3.Dot(this._zAxis, eye);
  2268. 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);
  2269. };
  2270. Matrix.LookAtRH = function (eye, target, up) {
  2271. var result = Matrix.Zero();
  2272. Matrix.LookAtRHToRef(eye, target, up, result);
  2273. return result;
  2274. };
  2275. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2276. // Z axis
  2277. eye.subtractToRef(target, this._zAxis);
  2278. this._zAxis.normalize();
  2279. // X axis
  2280. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2281. if (this._xAxis.lengthSquared() === 0) {
  2282. this._xAxis.x = 1.0;
  2283. }
  2284. else {
  2285. this._xAxis.normalize();
  2286. }
  2287. // Y axis
  2288. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2289. this._yAxis.normalize();
  2290. // Eye angles
  2291. var ex = -Vector3.Dot(this._xAxis, eye);
  2292. var ey = -Vector3.Dot(this._yAxis, eye);
  2293. var ez = -Vector3.Dot(this._zAxis, eye);
  2294. 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);
  2295. };
  2296. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2297. var matrix = Matrix.Zero();
  2298. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2299. return matrix;
  2300. };
  2301. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2302. var hw = 2.0 / width;
  2303. var hh = 2.0 / height;
  2304. var id = 1.0 / (zfar - znear);
  2305. var nid = znear / (znear - zfar);
  2306. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2307. };
  2308. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2309. var matrix = Matrix.Zero();
  2310. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2311. return matrix;
  2312. };
  2313. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2314. result.m[0] = 2.0 / (right - left);
  2315. result.m[1] = result.m[2] = result.m[3] = 0;
  2316. result.m[5] = 2.0 / (top - bottom);
  2317. result.m[4] = result.m[6] = result.m[7] = 0;
  2318. result.m[10] = 1.0 / (zfar - znear);
  2319. result.m[8] = result.m[9] = result.m[11] = 0;
  2320. result.m[12] = (left + right) / (left - right);
  2321. result.m[13] = (top + bottom) / (bottom - top);
  2322. result.m[14] = -znear / (zfar - znear);
  2323. result.m[15] = 1.0;
  2324. };
  2325. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2326. var matrix = Matrix.Zero();
  2327. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2328. return matrix;
  2329. };
  2330. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2331. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2332. result.m[10] *= -1.0;
  2333. };
  2334. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2335. var matrix = Matrix.Zero();
  2336. matrix.m[0] = (2.0 * znear) / width;
  2337. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2338. matrix.m[5] = (2.0 * znear) / height;
  2339. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2340. matrix.m[10] = -zfar / (znear - zfar);
  2341. matrix.m[8] = matrix.m[9] = 0.0;
  2342. matrix.m[11] = 1.0;
  2343. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2344. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2345. return matrix;
  2346. };
  2347. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2348. var matrix = Matrix.Zero();
  2349. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2350. return matrix;
  2351. };
  2352. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2353. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2354. var tan = 1.0 / (Math.tan(fov * 0.5));
  2355. if (isVerticalFovFixed) {
  2356. result.m[0] = tan / aspect;
  2357. }
  2358. else {
  2359. result.m[0] = tan;
  2360. }
  2361. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2362. if (isVerticalFovFixed) {
  2363. result.m[5] = tan;
  2364. }
  2365. else {
  2366. result.m[5] = tan * aspect;
  2367. }
  2368. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2369. result.m[8] = result.m[9] = 0.0;
  2370. result.m[10] = zfar / (zfar - znear);
  2371. result.m[11] = 1.0;
  2372. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2373. result.m[14] = -(znear * zfar) / (zfar - znear);
  2374. };
  2375. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2376. var matrix = Matrix.Zero();
  2377. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2378. return matrix;
  2379. };
  2380. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2381. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2382. var tan = 1.0 / (Math.tan(fov * 0.5));
  2383. if (isVerticalFovFixed) {
  2384. result.m[0] = tan / aspect;
  2385. }
  2386. else {
  2387. result.m[0] = tan;
  2388. }
  2389. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2390. if (isVerticalFovFixed) {
  2391. result.m[5] = tan;
  2392. }
  2393. else {
  2394. result.m[5] = tan * aspect;
  2395. }
  2396. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2397. result.m[8] = result.m[9] = 0.0;
  2398. result.m[10] = zfar / (znear - zfar);
  2399. result.m[11] = -1.0;
  2400. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2401. result.m[14] = (znear * zfar) / (znear - zfar);
  2402. };
  2403. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2404. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2405. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2406. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2407. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2408. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2409. var xScale = 2.0 / (leftTan + rightTan);
  2410. var yScale = 2.0 / (upTan + downTan);
  2411. result.m[0] = xScale;
  2412. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2413. result.m[5] = yScale;
  2414. result.m[6] = result.m[7] = 0.0;
  2415. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2416. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2417. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2418. result.m[10] = -zfar / (znear - zfar);
  2419. result.m[11] = 1.0;
  2420. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2421. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2422. result.m[14] = (znear * zfar) / (znear - zfar);
  2423. };
  2424. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2425. var cw = viewport.width;
  2426. var ch = viewport.height;
  2427. var cx = viewport.x;
  2428. var cy = viewport.y;
  2429. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2430. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2431. };
  2432. Matrix.GetAsMatrix2x2 = function (matrix) {
  2433. return new Float32Array([
  2434. matrix.m[0], matrix.m[1],
  2435. matrix.m[4], matrix.m[5]
  2436. ]);
  2437. };
  2438. Matrix.GetAsMatrix3x3 = function (matrix) {
  2439. return new Float32Array([
  2440. matrix.m[0], matrix.m[1], matrix.m[2],
  2441. matrix.m[4], matrix.m[5], matrix.m[6],
  2442. matrix.m[8], matrix.m[9], matrix.m[10]
  2443. ]);
  2444. };
  2445. Matrix.Transpose = function (matrix) {
  2446. var result = new Matrix();
  2447. result.m[0] = matrix.m[0];
  2448. result.m[1] = matrix.m[4];
  2449. result.m[2] = matrix.m[8];
  2450. result.m[3] = matrix.m[12];
  2451. result.m[4] = matrix.m[1];
  2452. result.m[5] = matrix.m[5];
  2453. result.m[6] = matrix.m[9];
  2454. result.m[7] = matrix.m[13];
  2455. result.m[8] = matrix.m[2];
  2456. result.m[9] = matrix.m[6];
  2457. result.m[10] = matrix.m[10];
  2458. result.m[11] = matrix.m[14];
  2459. result.m[12] = matrix.m[3];
  2460. result.m[13] = matrix.m[7];
  2461. result.m[14] = matrix.m[11];
  2462. result.m[15] = matrix.m[15];
  2463. return result;
  2464. };
  2465. Matrix.Reflection = function (plane) {
  2466. var matrix = new Matrix();
  2467. Matrix.ReflectionToRef(plane, matrix);
  2468. return matrix;
  2469. };
  2470. Matrix.ReflectionToRef = function (plane, result) {
  2471. plane.normalize();
  2472. var x = plane.normal.x;
  2473. var y = plane.normal.y;
  2474. var z = plane.normal.z;
  2475. var temp = -2 * x;
  2476. var temp2 = -2 * y;
  2477. var temp3 = -2 * z;
  2478. result.m[0] = (temp * x) + 1;
  2479. result.m[1] = temp2 * x;
  2480. result.m[2] = temp3 * x;
  2481. result.m[3] = 0.0;
  2482. result.m[4] = temp * y;
  2483. result.m[5] = (temp2 * y) + 1;
  2484. result.m[6] = temp3 * y;
  2485. result.m[7] = 0.0;
  2486. result.m[8] = temp * z;
  2487. result.m[9] = temp2 * z;
  2488. result.m[10] = (temp3 * z) + 1;
  2489. result.m[11] = 0.0;
  2490. result.m[12] = temp * plane.d;
  2491. result.m[13] = temp2 * plane.d;
  2492. result.m[14] = temp3 * plane.d;
  2493. result.m[15] = 1.0;
  2494. };
  2495. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2496. mat.m[0] = xaxis.x;
  2497. mat.m[1] = xaxis.y;
  2498. mat.m[2] = xaxis.z;
  2499. mat.m[3] = 0;
  2500. mat.m[4] = yaxis.x;
  2501. mat.m[5] = yaxis.y;
  2502. mat.m[6] = yaxis.z;
  2503. mat.m[7] = 0;
  2504. mat.m[8] = zaxis.x;
  2505. mat.m[9] = zaxis.y;
  2506. mat.m[10] = zaxis.z;
  2507. mat.m[11] = 0;
  2508. mat.m[12] = 0;
  2509. mat.m[13] = 0;
  2510. mat.m[14] = 0;
  2511. mat.m[15] = 1;
  2512. };
  2513. Matrix._tempQuaternion = new Quaternion();
  2514. Matrix._xAxis = Vector3.Zero();
  2515. Matrix._yAxis = Vector3.Zero();
  2516. Matrix._zAxis = Vector3.Zero();
  2517. return Matrix;
  2518. }());
  2519. BABYLON.Matrix = Matrix;
  2520. var Plane = (function () {
  2521. function Plane(a, b, c, d) {
  2522. this.normal = new Vector3(a, b, c);
  2523. this.d = d;
  2524. }
  2525. Plane.prototype.asArray = function () {
  2526. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2527. };
  2528. // Methods
  2529. Plane.prototype.clone = function () {
  2530. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2531. };
  2532. Plane.prototype.getClassName = function () {
  2533. return "Plane";
  2534. };
  2535. Plane.prototype.getHashCode = function () {
  2536. var hash = this.normal.getHashCode();
  2537. hash = (hash * 397) ^ (this.d || 0);
  2538. return hash;
  2539. };
  2540. Plane.prototype.normalize = function () {
  2541. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2542. var magnitude = 0;
  2543. if (norm !== 0) {
  2544. magnitude = 1.0 / norm;
  2545. }
  2546. this.normal.x *= magnitude;
  2547. this.normal.y *= magnitude;
  2548. this.normal.z *= magnitude;
  2549. this.d *= magnitude;
  2550. return this;
  2551. };
  2552. Plane.prototype.transform = function (transformation) {
  2553. var transposedMatrix = Matrix.Transpose(transformation);
  2554. var x = this.normal.x;
  2555. var y = this.normal.y;
  2556. var z = this.normal.z;
  2557. var d = this.d;
  2558. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2559. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2560. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2561. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2562. return new Plane(normalX, normalY, normalZ, finalD);
  2563. };
  2564. Plane.prototype.dotCoordinate = function (point) {
  2565. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2566. };
  2567. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2568. var x1 = point2.x - point1.x;
  2569. var y1 = point2.y - point1.y;
  2570. var z1 = point2.z - point1.z;
  2571. var x2 = point3.x - point1.x;
  2572. var y2 = point3.y - point1.y;
  2573. var z2 = point3.z - point1.z;
  2574. var yz = (y1 * z2) - (z1 * y2);
  2575. var xz = (z1 * x2) - (x1 * z2);
  2576. var xy = (x1 * y2) - (y1 * x2);
  2577. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2578. var invPyth;
  2579. if (pyth !== 0) {
  2580. invPyth = 1.0 / pyth;
  2581. }
  2582. else {
  2583. invPyth = 0;
  2584. }
  2585. this.normal.x = yz * invPyth;
  2586. this.normal.y = xz * invPyth;
  2587. this.normal.z = xy * invPyth;
  2588. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2589. return this;
  2590. };
  2591. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2592. var dot = Vector3.Dot(this.normal, direction);
  2593. return (dot <= epsilon);
  2594. };
  2595. Plane.prototype.signedDistanceTo = function (point) {
  2596. return Vector3.Dot(point, this.normal) + this.d;
  2597. };
  2598. // Statics
  2599. Plane.FromArray = function (array) {
  2600. return new Plane(array[0], array[1], array[2], array[3]);
  2601. };
  2602. Plane.FromPoints = function (point1, point2, point3) {
  2603. var result = new Plane(0, 0, 0, 0);
  2604. result.copyFromPoints(point1, point2, point3);
  2605. return result;
  2606. };
  2607. Plane.FromPositionAndNormal = function (origin, normal) {
  2608. var result = new Plane(0, 0, 0, 0);
  2609. normal.normalize();
  2610. result.normal = normal;
  2611. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2612. return result;
  2613. };
  2614. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2615. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2616. return Vector3.Dot(point, normal) + d;
  2617. };
  2618. return Plane;
  2619. }());
  2620. BABYLON.Plane = Plane;
  2621. var Viewport = (function () {
  2622. function Viewport(x, y, width, height) {
  2623. this.x = x;
  2624. this.y = y;
  2625. this.width = width;
  2626. this.height = height;
  2627. }
  2628. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2629. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2630. };
  2631. return Viewport;
  2632. }());
  2633. BABYLON.Viewport = Viewport;
  2634. var Frustum = (function () {
  2635. function Frustum() {
  2636. }
  2637. Frustum.GetPlanes = function (transform) {
  2638. var frustumPlanes = [];
  2639. for (var index = 0; index < 6; index++) {
  2640. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2641. }
  2642. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2643. return frustumPlanes;
  2644. };
  2645. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2646. // Near
  2647. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2648. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2649. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2650. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2651. frustumPlanes[0].normalize();
  2652. // Far
  2653. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2654. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2655. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2656. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2657. frustumPlanes[1].normalize();
  2658. // Left
  2659. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2660. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2661. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2662. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2663. frustumPlanes[2].normalize();
  2664. // Right
  2665. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2666. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2667. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2668. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2669. frustumPlanes[3].normalize();
  2670. // Top
  2671. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2672. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2673. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2674. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2675. frustumPlanes[4].normalize();
  2676. // Bottom
  2677. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2678. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2679. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2680. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2681. frustumPlanes[5].normalize();
  2682. };
  2683. return Frustum;
  2684. }());
  2685. BABYLON.Frustum = Frustum;
  2686. (function (Space) {
  2687. Space[Space["LOCAL"] = 0] = "LOCAL";
  2688. Space[Space["WORLD"] = 1] = "WORLD";
  2689. })(BABYLON.Space || (BABYLON.Space = {}));
  2690. var Space = BABYLON.Space;
  2691. var Axis = (function () {
  2692. function Axis() {
  2693. }
  2694. Axis.X = new Vector3(1, 0, 0);
  2695. Axis.Y = new Vector3(0, 1, 0);
  2696. Axis.Z = new Vector3(0, 0, 1);
  2697. return Axis;
  2698. }());
  2699. BABYLON.Axis = Axis;
  2700. ;
  2701. var BezierCurve = (function () {
  2702. function BezierCurve() {
  2703. }
  2704. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2705. // Extract X (which is equal to time here)
  2706. var f0 = 1 - 3 * x2 + 3 * x1;
  2707. var f1 = 3 * x2 - 6 * x1;
  2708. var f2 = 3 * x1;
  2709. var refinedT = t;
  2710. for (var i = 0; i < 5; i++) {
  2711. var refinedT2 = refinedT * refinedT;
  2712. var refinedT3 = refinedT2 * refinedT;
  2713. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2714. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2715. refinedT -= (x - t) * slope;
  2716. refinedT = Math.min(1, Math.max(0, refinedT));
  2717. }
  2718. // Resolve cubic bezier for the given x
  2719. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2720. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2721. Math.pow(refinedT, 3);
  2722. };
  2723. return BezierCurve;
  2724. }());
  2725. BABYLON.BezierCurve = BezierCurve;
  2726. (function (Orientation) {
  2727. Orientation[Orientation["CW"] = 0] = "CW";
  2728. Orientation[Orientation["CCW"] = 1] = "CCW";
  2729. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2730. var Orientation = BABYLON.Orientation;
  2731. var Angle = (function () {
  2732. function Angle(radians) {
  2733. var _this = this;
  2734. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2735. this.radians = function () { return _this._radians; };
  2736. this._radians = radians;
  2737. if (this._radians < 0)
  2738. this._radians += (2 * Math.PI);
  2739. }
  2740. Angle.BetweenTwoPoints = function (a, b) {
  2741. var delta = b.subtract(a);
  2742. var theta = Math.atan2(delta.y, delta.x);
  2743. return new Angle(theta);
  2744. };
  2745. Angle.FromRadians = function (radians) {
  2746. return new Angle(radians);
  2747. };
  2748. Angle.FromDegrees = function (degrees) {
  2749. return new Angle(degrees * Math.PI / 180);
  2750. };
  2751. return Angle;
  2752. }());
  2753. BABYLON.Angle = Angle;
  2754. var Arc2 = (function () {
  2755. function Arc2(startPoint, midPoint, endPoint) {
  2756. this.startPoint = startPoint;
  2757. this.midPoint = midPoint;
  2758. this.endPoint = endPoint;
  2759. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2760. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2761. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2762. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2763. 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);
  2764. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2765. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2766. var a1 = this.startAngle.degrees();
  2767. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2768. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2769. // angles correction
  2770. if (a2 - a1 > +180.0)
  2771. a2 -= 360.0;
  2772. if (a2 - a1 < -180.0)
  2773. a2 += 360.0;
  2774. if (a3 - a2 > +180.0)
  2775. a3 -= 360.0;
  2776. if (a3 - a2 < -180.0)
  2777. a3 += 360.0;
  2778. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2779. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2780. }
  2781. return Arc2;
  2782. }());
  2783. BABYLON.Arc2 = Arc2;
  2784. var Path2 = (function () {
  2785. function Path2(x, y) {
  2786. this._points = new Array();
  2787. this._length = 0;
  2788. this.closed = false;
  2789. this._points.push(new Vector2(x, y));
  2790. }
  2791. Path2.prototype.addLineTo = function (x, y) {
  2792. if (closed) {
  2793. //Tools.Error("cannot add lines to closed paths");
  2794. return this;
  2795. }
  2796. var newPoint = new Vector2(x, y);
  2797. var previousPoint = this._points[this._points.length - 1];
  2798. this._points.push(newPoint);
  2799. this._length += newPoint.subtract(previousPoint).length();
  2800. return this;
  2801. };
  2802. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2803. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2804. if (closed) {
  2805. //Tools.Error("cannot add arcs to closed paths");
  2806. return this;
  2807. }
  2808. var startPoint = this._points[this._points.length - 1];
  2809. var midPoint = new Vector2(midX, midY);
  2810. var endPoint = new Vector2(endX, endY);
  2811. var arc = new Arc2(startPoint, midPoint, endPoint);
  2812. var increment = arc.angle.radians() / numberOfSegments;
  2813. if (arc.orientation === Orientation.CW)
  2814. increment *= -1;
  2815. var currentAngle = arc.startAngle.radians() + increment;
  2816. for (var i = 0; i < numberOfSegments; i++) {
  2817. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2818. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2819. this.addLineTo(x, y);
  2820. currentAngle += increment;
  2821. }
  2822. return this;
  2823. };
  2824. Path2.prototype.close = function () {
  2825. this.closed = true;
  2826. return this;
  2827. };
  2828. Path2.prototype.length = function () {
  2829. var result = this._length;
  2830. if (!this.closed) {
  2831. var lastPoint = this._points[this._points.length - 1];
  2832. var firstPoint = this._points[0];
  2833. result += (firstPoint.subtract(lastPoint).length());
  2834. }
  2835. return result;
  2836. };
  2837. Path2.prototype.getPoints = function () {
  2838. return this._points;
  2839. };
  2840. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2841. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2842. //Tools.Error("normalized length position should be between 0 and 1.");
  2843. return Vector2.Zero();
  2844. }
  2845. var lengthPosition = normalizedLengthPosition * this.length();
  2846. var previousOffset = 0;
  2847. for (var i = 0; i < this._points.length; i++) {
  2848. var j = (i + 1) % this._points.length;
  2849. var a = this._points[i];
  2850. var b = this._points[j];
  2851. var bToA = b.subtract(a);
  2852. var nextOffset = (bToA.length() + previousOffset);
  2853. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2854. var dir = bToA.normalize();
  2855. var localOffset = lengthPosition - previousOffset;
  2856. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2857. }
  2858. previousOffset = nextOffset;
  2859. }
  2860. //Tools.Error("internal error");
  2861. return Vector2.Zero();
  2862. };
  2863. Path2.StartingAt = function (x, y) {
  2864. return new Path2(x, y);
  2865. };
  2866. return Path2;
  2867. }());
  2868. BABYLON.Path2 = Path2;
  2869. var Path3D = (function () {
  2870. /**
  2871. * new Path3D(path, normal, raw)
  2872. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2873. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2874. * path : an array of Vector3, the curve axis of the Path3D
  2875. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2876. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2877. */
  2878. function Path3D(path, firstNormal, raw) {
  2879. this.path = path;
  2880. this._curve = new Array();
  2881. this._distances = new Array();
  2882. this._tangents = new Array();
  2883. this._normals = new Array();
  2884. this._binormals = new Array();
  2885. for (var p = 0; p < path.length; p++) {
  2886. this._curve[p] = path[p].clone(); // hard copy
  2887. }
  2888. this._raw = raw || false;
  2889. this._compute(firstNormal);
  2890. }
  2891. /**
  2892. * Returns the Path3D array of successive Vector3 designing its curve.
  2893. */
  2894. Path3D.prototype.getCurve = function () {
  2895. return this._curve;
  2896. };
  2897. /**
  2898. * Returns an array populated with tangent vectors on each Path3D curve point.
  2899. */
  2900. Path3D.prototype.getTangents = function () {
  2901. return this._tangents;
  2902. };
  2903. /**
  2904. * Returns an array populated with normal vectors on each Path3D curve point.
  2905. */
  2906. Path3D.prototype.getNormals = function () {
  2907. return this._normals;
  2908. };
  2909. /**
  2910. * Returns an array populated with binormal vectors on each Path3D curve point.
  2911. */
  2912. Path3D.prototype.getBinormals = function () {
  2913. return this._binormals;
  2914. };
  2915. /**
  2916. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2917. */
  2918. Path3D.prototype.getDistances = function () {
  2919. return this._distances;
  2920. };
  2921. /**
  2922. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2923. * Returns the same object updated.
  2924. */
  2925. Path3D.prototype.update = function (path, firstNormal) {
  2926. for (var p = 0; p < path.length; p++) {
  2927. this._curve[p].x = path[p].x;
  2928. this._curve[p].y = path[p].y;
  2929. this._curve[p].z = path[p].z;
  2930. }
  2931. this._compute(firstNormal);
  2932. return this;
  2933. };
  2934. // private function compute() : computes tangents, normals and binormals
  2935. Path3D.prototype._compute = function (firstNormal) {
  2936. var l = this._curve.length;
  2937. // first and last tangents
  2938. this._tangents[0] = this._getFirstNonNullVector(0);
  2939. if (!this._raw) {
  2940. this._tangents[0].normalize();
  2941. }
  2942. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2943. if (!this._raw) {
  2944. this._tangents[l - 1].normalize();
  2945. }
  2946. // normals and binormals at first point : arbitrary vector with _normalVector()
  2947. var tg0 = this._tangents[0];
  2948. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2949. this._normals[0] = pp0;
  2950. if (!this._raw) {
  2951. this._normals[0].normalize();
  2952. }
  2953. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2954. if (!this._raw) {
  2955. this._binormals[0].normalize();
  2956. }
  2957. this._distances[0] = 0.0;
  2958. // normals and binormals : next points
  2959. var prev; // previous vector (segment)
  2960. var cur; // current vector (segment)
  2961. var curTang; // current tangent
  2962. // previous normal
  2963. var prevBinor; // previous binormal
  2964. for (var i = 1; i < l; i++) {
  2965. // tangents
  2966. prev = this._getLastNonNullVector(i);
  2967. if (i < l - 1) {
  2968. cur = this._getFirstNonNullVector(i);
  2969. this._tangents[i] = prev.add(cur);
  2970. this._tangents[i].normalize();
  2971. }
  2972. this._distances[i] = this._distances[i - 1] + prev.length();
  2973. // normals and binormals
  2974. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2975. curTang = this._tangents[i];
  2976. prevBinor = this._binormals[i - 1];
  2977. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2978. if (!this._raw) {
  2979. this._normals[i].normalize();
  2980. }
  2981. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2982. if (!this._raw) {
  2983. this._binormals[i].normalize();
  2984. }
  2985. }
  2986. };
  2987. // private function getFirstNonNullVector(index)
  2988. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2989. Path3D.prototype._getFirstNonNullVector = function (index) {
  2990. var i = 1;
  2991. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2992. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2993. i++;
  2994. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2995. }
  2996. return nNVector;
  2997. };
  2998. // private function getLastNonNullVector(index)
  2999. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3000. Path3D.prototype._getLastNonNullVector = function (index) {
  3001. var i = 1;
  3002. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3003. while (nLVector.length() === 0 && index > i + 1) {
  3004. i++;
  3005. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3006. }
  3007. return nLVector;
  3008. };
  3009. // private function normalVector(v0, vt, va) :
  3010. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3011. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3012. Path3D.prototype._normalVector = function (v0, vt, va) {
  3013. var normal0;
  3014. var tgl = vt.length();
  3015. if (tgl === 0.0) {
  3016. tgl = 1.0;
  3017. }
  3018. if (va === undefined || va === null) {
  3019. var point;
  3020. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3021. point = new Vector3(0.0, -1.0, 0.0);
  3022. }
  3023. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3024. point = new Vector3(1.0, 0.0, 0.0);
  3025. }
  3026. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3027. point = new Vector3(0.0, 0.0, 1.0);
  3028. }
  3029. normal0 = Vector3.Cross(vt, point);
  3030. }
  3031. else {
  3032. normal0 = Vector3.Cross(vt, va);
  3033. Vector3.CrossToRef(normal0, vt, normal0);
  3034. }
  3035. normal0.normalize();
  3036. return normal0;
  3037. };
  3038. return Path3D;
  3039. }());
  3040. BABYLON.Path3D = Path3D;
  3041. var Curve3 = (function () {
  3042. /**
  3043. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3044. * A Curve3 is designed from a series of successive Vector3.
  3045. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3046. */
  3047. function Curve3(points) {
  3048. this._length = 0.0;
  3049. this._points = points;
  3050. this._length = this._computeLength(points);
  3051. }
  3052. /**
  3053. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3054. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3055. * @param v1 (Vector3) the control point
  3056. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3057. * @param nbPoints (integer) the wanted number of points in the curve
  3058. */
  3059. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3060. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3061. var bez = new Array();
  3062. var equation = function (t, val0, val1, val2) {
  3063. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3064. return res;
  3065. };
  3066. for (var i = 0; i <= nbPoints; i++) {
  3067. 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)));
  3068. }
  3069. return new Curve3(bez);
  3070. };
  3071. /**
  3072. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3073. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3074. * @param v1 (Vector3) the first control point
  3075. * @param v2 (Vector3) the second control point
  3076. * @param v3 (Vector3) the end point of the Cubic Bezier
  3077. * @param nbPoints (integer) the wanted number of points in the curve
  3078. */
  3079. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3080. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3081. var bez = new Array();
  3082. var equation = function (t, val0, val1, val2, val3) {
  3083. 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;
  3084. return res;
  3085. };
  3086. for (var i = 0; i <= nbPoints; i++) {
  3087. 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)));
  3088. }
  3089. return new Curve3(bez);
  3090. };
  3091. /**
  3092. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3093. * @param p1 (Vector3) the origin point of the Hermite Spline
  3094. * @param t1 (Vector3) the tangent vector at the origin point
  3095. * @param p2 (Vector3) the end point of the Hermite Spline
  3096. * @param t2 (Vector3) the tangent vector at the end point
  3097. * @param nbPoints (integer) the wanted number of points in the curve
  3098. */
  3099. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3100. var hermite = new Array();
  3101. var step = 1.0 / nbPoints;
  3102. for (var i = 0; i <= nbPoints; i++) {
  3103. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3104. }
  3105. return new Curve3(hermite);
  3106. };
  3107. /**
  3108. * Returns the Curve3 stored array of successive Vector3
  3109. */
  3110. Curve3.prototype.getPoints = function () {
  3111. return this._points;
  3112. };
  3113. /**
  3114. * Returns the computed length (float) of the curve.
  3115. */
  3116. Curve3.prototype.length = function () {
  3117. return this._length;
  3118. };
  3119. /**
  3120. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3121. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3122. * curveA and curveB keep unchanged.
  3123. */
  3124. Curve3.prototype.continue = function (curve) {
  3125. var lastPoint = this._points[this._points.length - 1];
  3126. var continuedPoints = this._points.slice();
  3127. var curvePoints = curve.getPoints();
  3128. for (var i = 1; i < curvePoints.length; i++) {
  3129. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3130. }
  3131. var continuedCurve = new Curve3(continuedPoints);
  3132. return continuedCurve;
  3133. };
  3134. Curve3.prototype._computeLength = function (path) {
  3135. var l = 0;
  3136. for (var i = 1; i < path.length; i++) {
  3137. l += (path[i].subtract(path[i - 1])).length();
  3138. }
  3139. return l;
  3140. };
  3141. return Curve3;
  3142. }());
  3143. BABYLON.Curve3 = Curve3;
  3144. // SphericalHarmonics
  3145. var SphericalHarmonics = (function () {
  3146. function SphericalHarmonics() {
  3147. this.L00 = Vector3.Zero();
  3148. this.L1_1 = Vector3.Zero();
  3149. this.L10 = Vector3.Zero();
  3150. this.L11 = Vector3.Zero();
  3151. this.L2_2 = Vector3.Zero();
  3152. this.L2_1 = Vector3.Zero();
  3153. this.L20 = Vector3.Zero();
  3154. this.L21 = Vector3.Zero();
  3155. this.L22 = Vector3.Zero();
  3156. }
  3157. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3158. var colorVector = new Vector3(color.r, color.g, color.b);
  3159. var c = colorVector.scale(deltaSolidAngle);
  3160. this.L00 = this.L00.add(c.scale(0.282095));
  3161. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3162. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3163. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3164. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3165. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3166. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3167. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3168. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3169. };
  3170. SphericalHarmonics.prototype.scale = function (scale) {
  3171. this.L00 = this.L00.scale(scale);
  3172. this.L1_1 = this.L1_1.scale(scale);
  3173. this.L10 = this.L10.scale(scale);
  3174. this.L11 = this.L11.scale(scale);
  3175. this.L2_2 = this.L2_2.scale(scale);
  3176. this.L2_1 = this.L2_1.scale(scale);
  3177. this.L20 = this.L20.scale(scale);
  3178. this.L21 = this.L21.scale(scale);
  3179. this.L22 = this.L22.scale(scale);
  3180. };
  3181. return SphericalHarmonics;
  3182. }());
  3183. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3184. // SphericalPolynomial
  3185. var SphericalPolynomial = (function () {
  3186. function SphericalPolynomial() {
  3187. this.x = Vector3.Zero();
  3188. this.y = Vector3.Zero();
  3189. this.z = Vector3.Zero();
  3190. this.xx = Vector3.Zero();
  3191. this.yy = Vector3.Zero();
  3192. this.zz = Vector3.Zero();
  3193. this.xy = Vector3.Zero();
  3194. this.yz = Vector3.Zero();
  3195. this.zx = Vector3.Zero();
  3196. }
  3197. SphericalPolynomial.prototype.addAmbient = function (color) {
  3198. var colorVector = new Vector3(color.r, color.g, color.b);
  3199. this.xx = this.xx.add(colorVector);
  3200. this.yy = this.yy.add(colorVector);
  3201. this.zz = this.zz.add(colorVector);
  3202. };
  3203. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3204. var result = new SphericalPolynomial();
  3205. result.x = harmonics.L11.scale(1.02333);
  3206. result.y = harmonics.L1_1.scale(1.02333);
  3207. result.z = harmonics.L10.scale(1.02333);
  3208. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3209. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3210. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3211. result.yz = harmonics.L2_1.scale(0.858086);
  3212. result.zx = harmonics.L21.scale(0.858086);
  3213. result.xy = harmonics.L2_2.scale(0.858086);
  3214. return result;
  3215. };
  3216. return SphericalPolynomial;
  3217. }());
  3218. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3219. // Vertex formats
  3220. var PositionNormalVertex = (function () {
  3221. function PositionNormalVertex(position, normal) {
  3222. if (position === void 0) { position = Vector3.Zero(); }
  3223. if (normal === void 0) { normal = Vector3.Up(); }
  3224. this.position = position;
  3225. this.normal = normal;
  3226. }
  3227. PositionNormalVertex.prototype.clone = function () {
  3228. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3229. };
  3230. return PositionNormalVertex;
  3231. }());
  3232. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3233. var PositionNormalTextureVertex = (function () {
  3234. function PositionNormalTextureVertex(position, normal, uv) {
  3235. if (position === void 0) { position = Vector3.Zero(); }
  3236. if (normal === void 0) { normal = Vector3.Up(); }
  3237. if (uv === void 0) { uv = Vector2.Zero(); }
  3238. this.position = position;
  3239. this.normal = normal;
  3240. this.uv = uv;
  3241. }
  3242. PositionNormalTextureVertex.prototype.clone = function () {
  3243. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3244. };
  3245. return PositionNormalTextureVertex;
  3246. }());
  3247. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3248. // Temporary pre-allocated objects for engine internal use
  3249. // usage in any internal function :
  3250. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3251. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3252. var Tmp = (function () {
  3253. function Tmp() {
  3254. }
  3255. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3256. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3257. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3258. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3259. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3260. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3261. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3262. Matrix.Zero(), Matrix.Zero(),
  3263. Matrix.Zero(), Matrix.Zero(),
  3264. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3265. return Tmp;
  3266. }());
  3267. BABYLON.Tmp = Tmp;
  3268. })(BABYLON || (BABYLON = {}));
  3269. var BABYLON;
  3270. (function (BABYLON) {
  3271. function generateSerializableMember(type, sourceName) {
  3272. return function (target, propertyKey) {
  3273. if (!target.__serializableMembers) {
  3274. target.__serializableMembers = {};
  3275. }
  3276. if (!target.__serializableMembers[propertyKey]) {
  3277. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3278. }
  3279. };
  3280. }
  3281. function serialize(sourceName) {
  3282. return generateSerializableMember(0, sourceName); // value member
  3283. }
  3284. BABYLON.serialize = serialize;
  3285. function serializeAsTexture(sourceName) {
  3286. return generateSerializableMember(1, sourceName); // texture member
  3287. }
  3288. BABYLON.serializeAsTexture = serializeAsTexture;
  3289. function serializeAsColor3(sourceName) {
  3290. return generateSerializableMember(2, sourceName); // color3 member
  3291. }
  3292. BABYLON.serializeAsColor3 = serializeAsColor3;
  3293. function serializeAsFresnelParameters(sourceName) {
  3294. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3295. }
  3296. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3297. function serializeAsVector2(sourceName) {
  3298. return generateSerializableMember(4, sourceName); // vector2 member
  3299. }
  3300. BABYLON.serializeAsVector2 = serializeAsVector2;
  3301. function serializeAsVector3(sourceName) {
  3302. return generateSerializableMember(5, sourceName); // vector3 member
  3303. }
  3304. BABYLON.serializeAsVector3 = serializeAsVector3;
  3305. function serializeAsMeshReference(sourceName) {
  3306. return generateSerializableMember(6, sourceName); // mesh reference member
  3307. }
  3308. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3309. function serializeAsColorCurves(sourceName) {
  3310. return generateSerializableMember(7, sourceName); // color curves
  3311. }
  3312. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3313. var SerializationHelper = (function () {
  3314. function SerializationHelper() {
  3315. }
  3316. SerializationHelper.Serialize = function (entity, serializationObject) {
  3317. if (!serializationObject) {
  3318. serializationObject = {};
  3319. }
  3320. // Tags
  3321. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3322. // Properties
  3323. for (var property in entity.__serializableMembers) {
  3324. var propertyDescriptor = entity.__serializableMembers[property];
  3325. var targetPropertyName = propertyDescriptor.sourceName || property;
  3326. var propertyType = propertyDescriptor.type;
  3327. var sourceProperty = entity[property];
  3328. if (sourceProperty !== undefined && sourceProperty !== null) {
  3329. switch (propertyType) {
  3330. case 0:
  3331. serializationObject[targetPropertyName] = sourceProperty;
  3332. break;
  3333. case 1:
  3334. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3335. break;
  3336. case 2:
  3337. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3338. break;
  3339. case 3:
  3340. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3341. break;
  3342. case 4:
  3343. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3344. break;
  3345. case 5:
  3346. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3347. break;
  3348. case 6:
  3349. serializationObject[targetPropertyName] = sourceProperty.id;
  3350. break;
  3351. case 7:
  3352. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3353. break;
  3354. }
  3355. }
  3356. }
  3357. return serializationObject;
  3358. };
  3359. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3360. var destination = creationFunction();
  3361. // Tags
  3362. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3363. // Properties
  3364. for (var property in destination.__serializableMembers) {
  3365. var propertyDescriptor = destination.__serializableMembers[property];
  3366. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3367. var propertyType = propertyDescriptor.type;
  3368. if (sourceProperty !== undefined && sourceProperty !== null) {
  3369. switch (propertyType) {
  3370. case 0:
  3371. destination[property] = sourceProperty;
  3372. break;
  3373. case 1:
  3374. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3375. break;
  3376. case 2:
  3377. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3378. break;
  3379. case 3:
  3380. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3381. break;
  3382. case 4:
  3383. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3384. break;
  3385. case 5:
  3386. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3387. break;
  3388. case 6:
  3389. destination[property] = scene.getLastMeshByID(sourceProperty);
  3390. break;
  3391. case 7:
  3392. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3393. break;
  3394. }
  3395. }
  3396. }
  3397. return destination;
  3398. };
  3399. SerializationHelper.Clone = function (creationFunction, source) {
  3400. var destination = creationFunction();
  3401. // Tags
  3402. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3403. // Properties
  3404. for (var property in destination.__serializableMembers) {
  3405. var propertyDescriptor = destination.__serializableMembers[property];
  3406. var sourceProperty = source[property];
  3407. var propertyType = propertyDescriptor.type;
  3408. if (sourceProperty !== undefined && sourceProperty !== null) {
  3409. switch (propertyType) {
  3410. case 0: // Value
  3411. case 6:
  3412. destination[property] = sourceProperty;
  3413. break;
  3414. case 1: // Texture
  3415. case 2: // Color3
  3416. case 3: // FresnelParameters
  3417. case 4: // Vector2
  3418. case 5: // Vector3
  3419. case 7:
  3420. destination[property] = sourceProperty.clone();
  3421. break;
  3422. }
  3423. }
  3424. }
  3425. return destination;
  3426. };
  3427. return SerializationHelper;
  3428. }());
  3429. BABYLON.SerializationHelper = SerializationHelper;
  3430. })(BABYLON || (BABYLON = {}));
  3431. var BABYLON;
  3432. (function (BABYLON) {
  3433. /**
  3434. * A class serves as a medium between the observable and its observers
  3435. */
  3436. var EventState = (function () {
  3437. /**
  3438. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3439. */
  3440. function EventState(mask, skipNextObservers) {
  3441. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3442. this.initalize(mask, skipNextObservers);
  3443. }
  3444. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3445. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3446. this.mask = mask;
  3447. this.skipNextObservers = skipNextObservers;
  3448. return this;
  3449. };
  3450. return EventState;
  3451. }());
  3452. BABYLON.EventState = EventState;
  3453. /**
  3454. * Represent an Observer registered to a given Observable object.
  3455. */
  3456. var Observer = (function () {
  3457. function Observer(callback, mask) {
  3458. this.callback = callback;
  3459. this.mask = mask;
  3460. }
  3461. return Observer;
  3462. }());
  3463. BABYLON.Observer = Observer;
  3464. /**
  3465. * The Observable class is a simple implementation of the Observable pattern.
  3466. * 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.
  3467. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3468. * 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).
  3469. * 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.
  3470. */
  3471. var Observable = (function () {
  3472. function Observable() {
  3473. this._observers = new Array();
  3474. this._eventState = new EventState(0);
  3475. }
  3476. /**
  3477. * Create a new Observer with the specified callback
  3478. * @param callback the callback that will be executed for that Observer
  3479. * @param mask the mask used to filter observers
  3480. * @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.
  3481. */
  3482. Observable.prototype.add = function (callback, mask, insertFirst) {
  3483. if (mask === void 0) { mask = -1; }
  3484. if (insertFirst === void 0) { insertFirst = false; }
  3485. if (!callback) {
  3486. return null;
  3487. }
  3488. var observer = new Observer(callback, mask);
  3489. if (insertFirst) {
  3490. this._observers.unshift(observer);
  3491. }
  3492. else {
  3493. this._observers.push(observer);
  3494. }
  3495. return observer;
  3496. };
  3497. /**
  3498. * Remove an Observer from the Observable object
  3499. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3500. */
  3501. Observable.prototype.remove = function (observer) {
  3502. var index = this._observers.indexOf(observer);
  3503. if (index !== -1) {
  3504. this._observers.splice(index, 1);
  3505. return true;
  3506. }
  3507. return false;
  3508. };
  3509. /**
  3510. * Remove a callback from the Observable object
  3511. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3512. */
  3513. Observable.prototype.removeCallback = function (callback) {
  3514. for (var index = 0; index < this._observers.length; index++) {
  3515. if (this._observers[index].callback === callback) {
  3516. this._observers.splice(index, 1);
  3517. return true;
  3518. }
  3519. }
  3520. return false;
  3521. };
  3522. /**
  3523. * Notify all Observers by calling their respective callback with the given data
  3524. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3525. * @param eventData
  3526. * @param mask
  3527. */
  3528. Observable.prototype.notifyObservers = function (eventData, mask) {
  3529. if (mask === void 0) { mask = -1; }
  3530. var state = this._eventState;
  3531. state.mask = mask;
  3532. state.skipNextObservers = false;
  3533. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3534. var obs = _a[_i];
  3535. if (obs.mask & mask) {
  3536. obs.callback(eventData, state);
  3537. }
  3538. if (state.skipNextObservers) {
  3539. return false;
  3540. }
  3541. }
  3542. return true;
  3543. };
  3544. /**
  3545. * return true is the Observable has at least one Observer registered
  3546. */
  3547. Observable.prototype.hasObservers = function () {
  3548. return this._observers.length > 0;
  3549. };
  3550. /**
  3551. * Clear the list of observers
  3552. */
  3553. Observable.prototype.clear = function () {
  3554. this._observers = new Array();
  3555. };
  3556. /**
  3557. * Clone the current observable
  3558. */
  3559. Observable.prototype.clone = function () {
  3560. var result = new Observable();
  3561. result._observers = this._observers.slice(0);
  3562. return result;
  3563. };
  3564. return Observable;
  3565. }());
  3566. BABYLON.Observable = Observable;
  3567. })(BABYLON || (BABYLON = {}));
  3568. var BABYLON;
  3569. (function (BABYLON) {
  3570. var Database = (function () {
  3571. function Database(urlToScene, callbackManifestChecked) {
  3572. // Handling various flavors of prefixed version of IndexedDB
  3573. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3574. this.callbackManifestChecked = callbackManifestChecked;
  3575. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3576. this.db = null;
  3577. this.enableSceneOffline = false;
  3578. this.enableTexturesOffline = false;
  3579. this.manifestVersionFound = 0;
  3580. this.mustUpdateRessources = false;
  3581. this.hasReachedQuota = false;
  3582. if (!Database.IDBStorageEnabled) {
  3583. this.callbackManifestChecked(true);
  3584. }
  3585. else {
  3586. this.checkManifestFile();
  3587. }
  3588. }
  3589. Database.prototype.checkManifestFile = function () {
  3590. var _this = this;
  3591. function noManifestFile() {
  3592. that.enableSceneOffline = false;
  3593. that.enableTexturesOffline = false;
  3594. that.callbackManifestChecked(false);
  3595. }
  3596. var that = this;
  3597. var timeStampUsed = false;
  3598. var manifestURL = this.currentSceneUrl + ".manifest";
  3599. var xhr = new XMLHttpRequest();
  3600. if (navigator.onLine) {
  3601. // Adding a timestamp to by-pass browsers' cache
  3602. timeStampUsed = true;
  3603. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3604. }
  3605. xhr.open("GET", manifestURL, true);
  3606. xhr.addEventListener("load", function () {
  3607. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3608. try {
  3609. var manifestFile = JSON.parse(xhr.response);
  3610. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3611. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3612. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3613. _this.manifestVersionFound = manifestFile.version;
  3614. }
  3615. if (_this.callbackManifestChecked) {
  3616. _this.callbackManifestChecked(true);
  3617. }
  3618. }
  3619. catch (ex) {
  3620. noManifestFile();
  3621. }
  3622. }
  3623. else {
  3624. noManifestFile();
  3625. }
  3626. }, false);
  3627. xhr.addEventListener("error", function (event) {
  3628. if (timeStampUsed) {
  3629. timeStampUsed = false;
  3630. // Let's retry without the timeStamp
  3631. // It could fail when coupled with HTML5 Offline API
  3632. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3633. xhr.open("GET", retryManifestURL, true);
  3634. xhr.send();
  3635. }
  3636. else {
  3637. noManifestFile();
  3638. }
  3639. }, false);
  3640. try {
  3641. xhr.send();
  3642. }
  3643. catch (ex) {
  3644. BABYLON.Tools.Error("Error on XHR send request.");
  3645. that.callbackManifestChecked(false);
  3646. }
  3647. };
  3648. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3649. var _this = this;
  3650. function handleError() {
  3651. that.isSupported = false;
  3652. if (errorCallback)
  3653. errorCallback();
  3654. }
  3655. var that = this;
  3656. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3657. // Your browser doesn't support IndexedDB
  3658. this.isSupported = false;
  3659. if (errorCallback)
  3660. errorCallback();
  3661. }
  3662. else {
  3663. // If the DB hasn't been opened or created yet
  3664. if (!this.db) {
  3665. this.hasReachedQuota = false;
  3666. this.isSupported = true;
  3667. var request = this.idbFactory.open("babylonjs", 1);
  3668. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3669. request.onerror = function (event) {
  3670. handleError();
  3671. };
  3672. // executes when a version change transaction cannot complete due to other active transactions
  3673. request.onblocked = function (event) {
  3674. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3675. handleError();
  3676. };
  3677. // DB has been opened successfully
  3678. request.onsuccess = function (event) {
  3679. _this.db = request.result;
  3680. successCallback();
  3681. };
  3682. // Initialization of the DB. Creating Scenes & Textures stores
  3683. request.onupgradeneeded = function (event) {
  3684. _this.db = (event.target).result;
  3685. try {
  3686. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3687. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3688. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3689. }
  3690. catch (ex) {
  3691. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3692. handleError();
  3693. }
  3694. };
  3695. }
  3696. else {
  3697. if (successCallback)
  3698. successCallback();
  3699. }
  3700. }
  3701. };
  3702. Database.prototype.loadImageFromDB = function (url, image) {
  3703. var _this = this;
  3704. var completeURL = Database.ReturnFullUrlLocation(url);
  3705. var saveAndLoadImage = function () {
  3706. if (!_this.hasReachedQuota && _this.db !== null) {
  3707. // the texture is not yet in the DB, let's try to save it
  3708. _this._saveImageIntoDBAsync(completeURL, image);
  3709. }
  3710. else {
  3711. image.src = url;
  3712. }
  3713. };
  3714. if (!this.mustUpdateRessources) {
  3715. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3716. }
  3717. else {
  3718. saveAndLoadImage();
  3719. }
  3720. };
  3721. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3722. if (this.isSupported && this.db !== null) {
  3723. var texture;
  3724. var transaction = this.db.transaction(["textures"]);
  3725. transaction.onabort = function (event) {
  3726. image.src = url;
  3727. };
  3728. transaction.oncomplete = function (event) {
  3729. var blobTextureURL;
  3730. if (texture) {
  3731. var URL = window.URL || window.webkitURL;
  3732. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3733. image.onerror = function () {
  3734. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3735. image.src = url;
  3736. };
  3737. image.src = blobTextureURL;
  3738. }
  3739. else {
  3740. notInDBCallback();
  3741. }
  3742. };
  3743. var getRequest = transaction.objectStore("textures").get(url);
  3744. getRequest.onsuccess = function (event) {
  3745. texture = (event.target).result;
  3746. };
  3747. getRequest.onerror = function (event) {
  3748. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3749. image.src = url;
  3750. };
  3751. }
  3752. else {
  3753. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3754. image.src = url;
  3755. }
  3756. };
  3757. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3758. var _this = this;
  3759. if (this.isSupported) {
  3760. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3761. var generateBlobUrl = function () {
  3762. var blobTextureURL;
  3763. if (blob) {
  3764. var URL = window.URL || window.webkitURL;
  3765. try {
  3766. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3767. }
  3768. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3769. catch (ex) {
  3770. blobTextureURL = URL.createObjectURL(blob);
  3771. }
  3772. }
  3773. image.src = blobTextureURL;
  3774. };
  3775. if (Database.IsUASupportingBlobStorage) {
  3776. var xhr = new XMLHttpRequest(), blob;
  3777. xhr.open("GET", url, true);
  3778. xhr.responseType = "blob";
  3779. xhr.addEventListener("load", function () {
  3780. if (xhr.status === 200) {
  3781. // Blob as response (XHR2)
  3782. blob = xhr.response;
  3783. var transaction = _this.db.transaction(["textures"], "readwrite");
  3784. // the transaction could abort because of a QuotaExceededError error
  3785. transaction.onabort = function (event) {
  3786. try {
  3787. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3788. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3789. _this.hasReachedQuota = true;
  3790. }
  3791. }
  3792. catch (ex) { }
  3793. generateBlobUrl();
  3794. };
  3795. transaction.oncomplete = function (event) {
  3796. generateBlobUrl();
  3797. };
  3798. var newTexture = { textureUrl: url, data: blob };
  3799. try {
  3800. // Put the blob into the dabase
  3801. var addRequest = transaction.objectStore("textures").put(newTexture);
  3802. addRequest.onsuccess = function (event) {
  3803. };
  3804. addRequest.onerror = function (event) {
  3805. generateBlobUrl();
  3806. };
  3807. }
  3808. catch (ex) {
  3809. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3810. if (ex.code === 25) {
  3811. Database.IsUASupportingBlobStorage = false;
  3812. }
  3813. image.src = url;
  3814. }
  3815. }
  3816. else {
  3817. image.src = url;
  3818. }
  3819. }, false);
  3820. xhr.addEventListener("error", function (event) {
  3821. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3822. image.src = url;
  3823. }, false);
  3824. xhr.send();
  3825. }
  3826. else {
  3827. image.src = url;
  3828. }
  3829. }
  3830. else {
  3831. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3832. image.src = url;
  3833. }
  3834. };
  3835. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3836. var _this = this;
  3837. var updateVersion = function (event) {
  3838. // the version is not yet in the DB or we need to update it
  3839. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3840. };
  3841. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3842. };
  3843. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3844. var _this = this;
  3845. if (this.isSupported) {
  3846. var version;
  3847. try {
  3848. var transaction = this.db.transaction(["versions"]);
  3849. transaction.oncomplete = function (event) {
  3850. if (version) {
  3851. // If the version in the JSON file is > than the version in DB
  3852. if (_this.manifestVersionFound > version.data) {
  3853. _this.mustUpdateRessources = true;
  3854. updateInDBCallback();
  3855. }
  3856. else {
  3857. callback(version.data);
  3858. }
  3859. }
  3860. else {
  3861. _this.mustUpdateRessources = true;
  3862. updateInDBCallback();
  3863. }
  3864. };
  3865. transaction.onabort = function (event) {
  3866. callback(-1);
  3867. };
  3868. var getRequest = transaction.objectStore("versions").get(url);
  3869. getRequest.onsuccess = function (event) {
  3870. version = (event.target).result;
  3871. };
  3872. getRequest.onerror = function (event) {
  3873. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3874. callback(-1);
  3875. };
  3876. }
  3877. catch (ex) {
  3878. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3879. callback(-1);
  3880. }
  3881. }
  3882. else {
  3883. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3884. callback(-1);
  3885. }
  3886. };
  3887. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3888. var _this = this;
  3889. if (this.isSupported && !this.hasReachedQuota) {
  3890. try {
  3891. // Open a transaction to the database
  3892. var transaction = this.db.transaction(["versions"], "readwrite");
  3893. // the transaction could abort because of a QuotaExceededError error
  3894. transaction.onabort = function (event) {
  3895. try {
  3896. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3897. _this.hasReachedQuota = true;
  3898. }
  3899. }
  3900. catch (ex) { }
  3901. callback(-1);
  3902. };
  3903. transaction.oncomplete = function (event) {
  3904. callback(_this.manifestVersionFound);
  3905. };
  3906. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3907. // Put the scene into the database
  3908. var addRequest = transaction.objectStore("versions").put(newVersion);
  3909. addRequest.onsuccess = function (event) {
  3910. };
  3911. addRequest.onerror = function (event) {
  3912. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3913. };
  3914. }
  3915. catch (ex) {
  3916. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3917. callback(-1);
  3918. }
  3919. }
  3920. else {
  3921. callback(-1);
  3922. }
  3923. };
  3924. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3925. var _this = this;
  3926. var completeUrl = Database.ReturnFullUrlLocation(url);
  3927. var saveAndLoadFile = function (event) {
  3928. // the scene is not yet in the DB, let's try to save it
  3929. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3930. };
  3931. this._checkVersionFromDB(completeUrl, function (version) {
  3932. if (version !== -1) {
  3933. if (!_this.mustUpdateRessources) {
  3934. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3935. }
  3936. else {
  3937. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3938. }
  3939. }
  3940. else {
  3941. errorCallback();
  3942. }
  3943. });
  3944. };
  3945. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3946. if (this.isSupported) {
  3947. var targetStore;
  3948. if (url.indexOf(".babylon") !== -1) {
  3949. targetStore = "scenes";
  3950. }
  3951. else {
  3952. targetStore = "textures";
  3953. }
  3954. var file;
  3955. var transaction = this.db.transaction([targetStore]);
  3956. transaction.oncomplete = function (event) {
  3957. if (file) {
  3958. callback(file.data);
  3959. }
  3960. else {
  3961. notInDBCallback();
  3962. }
  3963. };
  3964. transaction.onabort = function (event) {
  3965. notInDBCallback();
  3966. };
  3967. var getRequest = transaction.objectStore(targetStore).get(url);
  3968. getRequest.onsuccess = function (event) {
  3969. file = (event.target).result;
  3970. };
  3971. getRequest.onerror = function (event) {
  3972. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3973. notInDBCallback();
  3974. };
  3975. }
  3976. else {
  3977. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3978. callback();
  3979. }
  3980. };
  3981. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3982. var _this = this;
  3983. if (this.isSupported) {
  3984. var targetStore;
  3985. if (url.indexOf(".babylon") !== -1) {
  3986. targetStore = "scenes";
  3987. }
  3988. else {
  3989. targetStore = "textures";
  3990. }
  3991. // Create XHR
  3992. var xhr = new XMLHttpRequest(), fileData;
  3993. xhr.open("GET", url, true);
  3994. if (useArrayBuffer) {
  3995. xhr.responseType = "arraybuffer";
  3996. }
  3997. xhr.onprogress = progressCallback;
  3998. xhr.addEventListener("load", function () {
  3999. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4000. // Blob as response (XHR2)
  4001. //fileData = xhr.responseText;
  4002. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4003. if (!_this.hasReachedQuota) {
  4004. // Open a transaction to the database
  4005. var transaction = _this.db.transaction([targetStore], "readwrite");
  4006. // the transaction could abort because of a QuotaExceededError error
  4007. transaction.onabort = function (event) {
  4008. try {
  4009. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4010. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4011. _this.hasReachedQuota = true;
  4012. }
  4013. }
  4014. catch (ex) { }
  4015. callback(fileData);
  4016. };
  4017. transaction.oncomplete = function (event) {
  4018. callback(fileData);
  4019. };
  4020. var newFile;
  4021. if (targetStore === "scenes") {
  4022. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4023. }
  4024. else {
  4025. newFile = { textureUrl: url, data: fileData };
  4026. }
  4027. try {
  4028. // Put the scene into the database
  4029. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4030. addRequest.onsuccess = function (event) {
  4031. };
  4032. addRequest.onerror = function (event) {
  4033. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4034. };
  4035. }
  4036. catch (ex) {
  4037. callback(fileData);
  4038. }
  4039. }
  4040. else {
  4041. callback(fileData);
  4042. }
  4043. }
  4044. else {
  4045. callback();
  4046. }
  4047. }, false);
  4048. xhr.addEventListener("error", function (event) {
  4049. BABYLON.Tools.Error("error on XHR request.");
  4050. callback();
  4051. }, false);
  4052. xhr.send();
  4053. }
  4054. else {
  4055. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4056. callback();
  4057. }
  4058. };
  4059. Database.IsUASupportingBlobStorage = true;
  4060. Database.IDBStorageEnabled = true;
  4061. Database.parseURL = function (url) {
  4062. var a = document.createElement('a');
  4063. a.href = url;
  4064. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4065. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4066. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4067. return absLocation;
  4068. };
  4069. Database.ReturnFullUrlLocation = function (url) {
  4070. if (url.indexOf("http:/") === -1) {
  4071. return (Database.parseURL(window.location.href) + url);
  4072. }
  4073. else {
  4074. return url;
  4075. }
  4076. };
  4077. return Database;
  4078. }());
  4079. BABYLON.Database = Database;
  4080. })(BABYLON || (BABYLON = {}));
  4081. var BABYLON;
  4082. (function (BABYLON) {
  4083. var Internals;
  4084. (function (Internals) {
  4085. /*
  4086. * Based on jsTGALoader - Javascript loader for TGA file
  4087. * By Vincent Thibault
  4088. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4089. */
  4090. var TGATools = (function () {
  4091. function TGATools() {
  4092. }
  4093. TGATools.GetTGAHeader = function (data) {
  4094. var offset = 0;
  4095. var header = {
  4096. id_length: data[offset++],
  4097. colormap_type: data[offset++],
  4098. image_type: data[offset++],
  4099. colormap_index: data[offset++] | data[offset++] << 8,
  4100. colormap_length: data[offset++] | data[offset++] << 8,
  4101. colormap_size: data[offset++],
  4102. origin: [
  4103. data[offset++] | data[offset++] << 8,
  4104. data[offset++] | data[offset++] << 8
  4105. ],
  4106. width: data[offset++] | data[offset++] << 8,
  4107. height: data[offset++] | data[offset++] << 8,
  4108. pixel_size: data[offset++],
  4109. flags: data[offset++]
  4110. };
  4111. return header;
  4112. };
  4113. TGATools.UploadContent = function (gl, data) {
  4114. // Not enough data to contain header ?
  4115. if (data.length < 19) {
  4116. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4117. return;
  4118. }
  4119. // Read Header
  4120. var offset = 18;
  4121. var header = TGATools.GetTGAHeader(data);
  4122. // Assume it's a valid Targa file.
  4123. if (header.id_length + offset > data.length) {
  4124. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4125. return;
  4126. }
  4127. // Skip not needed data
  4128. offset += header.id_length;
  4129. var use_rle = false;
  4130. var use_pal = false;
  4131. var use_rgb = false;
  4132. var use_grey = false;
  4133. // Get some informations.
  4134. switch (header.image_type) {
  4135. case TGATools._TYPE_RLE_INDEXED:
  4136. use_rle = true;
  4137. case TGATools._TYPE_INDEXED:
  4138. use_pal = true;
  4139. break;
  4140. case TGATools._TYPE_RLE_RGB:
  4141. use_rle = true;
  4142. case TGATools._TYPE_RGB:
  4143. use_rgb = true;
  4144. break;
  4145. case TGATools._TYPE_RLE_GREY:
  4146. use_rle = true;
  4147. case TGATools._TYPE_GREY:
  4148. use_grey = true;
  4149. break;
  4150. }
  4151. var pixel_data;
  4152. var numAlphaBits = header.flags & 0xf;
  4153. var pixel_size = header.pixel_size >> 3;
  4154. var pixel_total = header.width * header.height * pixel_size;
  4155. // Read palettes
  4156. var palettes;
  4157. if (use_pal) {
  4158. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4159. }
  4160. // Read LRE
  4161. if (use_rle) {
  4162. pixel_data = new Uint8Array(pixel_total);
  4163. var c, count, i;
  4164. var localOffset = 0;
  4165. var pixels = new Uint8Array(pixel_size);
  4166. while (offset < pixel_total && localOffset < pixel_total) {
  4167. c = data[offset++];
  4168. count = (c & 0x7f) + 1;
  4169. // RLE pixels
  4170. if (c & 0x80) {
  4171. // Bind pixel tmp array
  4172. for (i = 0; i < pixel_size; ++i) {
  4173. pixels[i] = data[offset++];
  4174. }
  4175. // Copy pixel array
  4176. for (i = 0; i < count; ++i) {
  4177. pixel_data.set(pixels, localOffset + i * pixel_size);
  4178. }
  4179. localOffset += pixel_size * count;
  4180. }
  4181. else {
  4182. count *= pixel_size;
  4183. for (i = 0; i < count; ++i) {
  4184. pixel_data[localOffset + i] = data[offset++];
  4185. }
  4186. localOffset += count;
  4187. }
  4188. }
  4189. }
  4190. else {
  4191. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4192. }
  4193. // Load to texture
  4194. var x_start, y_start, x_step, y_step, y_end, x_end;
  4195. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4196. default:
  4197. case TGATools._ORIGIN_UL:
  4198. x_start = 0;
  4199. x_step = 1;
  4200. x_end = header.width;
  4201. y_start = 0;
  4202. y_step = 1;
  4203. y_end = header.height;
  4204. break;
  4205. case TGATools._ORIGIN_BL:
  4206. x_start = 0;
  4207. x_step = 1;
  4208. x_end = header.width;
  4209. y_start = header.height - 1;
  4210. y_step = -1;
  4211. y_end = -1;
  4212. break;
  4213. case TGATools._ORIGIN_UR:
  4214. x_start = header.width - 1;
  4215. x_step = -1;
  4216. x_end = -1;
  4217. y_start = 0;
  4218. y_step = 1;
  4219. y_end = header.height;
  4220. break;
  4221. case TGATools._ORIGIN_BR:
  4222. x_start = header.width - 1;
  4223. x_step = -1;
  4224. x_end = -1;
  4225. y_start = header.height - 1;
  4226. y_step = -1;
  4227. y_end = -1;
  4228. break;
  4229. }
  4230. // Load the specify method
  4231. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4232. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4233. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4234. };
  4235. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4236. var image = pixel_data, colormap = palettes;
  4237. var width = header.width, height = header.height;
  4238. var color, i = 0, x, y;
  4239. var imageData = new Uint8Array(width * height * 4);
  4240. for (y = y_start; y !== y_end; y += y_step) {
  4241. for (x = x_start; x !== x_end; x += x_step, i++) {
  4242. color = image[i];
  4243. imageData[(x + width * y) * 4 + 3] = 255;
  4244. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4245. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4246. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4247. }
  4248. }
  4249. return imageData;
  4250. };
  4251. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4252. var image = pixel_data;
  4253. var width = header.width, height = header.height;
  4254. var color, i = 0, x, y;
  4255. var imageData = new Uint8Array(width * height * 4);
  4256. for (y = y_start; y !== y_end; y += y_step) {
  4257. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4258. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4259. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4260. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4261. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4262. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4263. }
  4264. }
  4265. return imageData;
  4266. };
  4267. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4268. var image = pixel_data;
  4269. var width = header.width, height = header.height;
  4270. var i = 0, x, y;
  4271. var imageData = new Uint8Array(width * height * 4);
  4272. for (y = y_start; y !== y_end; y += y_step) {
  4273. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4274. imageData[(x + width * y) * 4 + 3] = 255;
  4275. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4276. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4277. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4278. }
  4279. }
  4280. return imageData;
  4281. };
  4282. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4283. var image = pixel_data;
  4284. var width = header.width, height = header.height;
  4285. var i = 0, x, y;
  4286. var imageData = new Uint8Array(width * height * 4);
  4287. for (y = y_start; y !== y_end; y += y_step) {
  4288. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4289. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4290. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4291. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4292. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4293. }
  4294. }
  4295. return imageData;
  4296. };
  4297. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4298. var image = pixel_data;
  4299. var width = header.width, height = header.height;
  4300. var color, i = 0, x, y;
  4301. var imageData = new Uint8Array(width * height * 4);
  4302. for (y = y_start; y !== y_end; y += y_step) {
  4303. for (x = x_start; x !== x_end; x += x_step, i++) {
  4304. color = image[i];
  4305. imageData[(x + width * y) * 4 + 0] = color;
  4306. imageData[(x + width * y) * 4 + 1] = color;
  4307. imageData[(x + width * y) * 4 + 2] = color;
  4308. imageData[(x + width * y) * 4 + 3] = 255;
  4309. }
  4310. }
  4311. return imageData;
  4312. };
  4313. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4314. var image = pixel_data;
  4315. var width = header.width, height = header.height;
  4316. var i = 0, x, y;
  4317. var imageData = new Uint8Array(width * height * 4);
  4318. for (y = y_start; y !== y_end; y += y_step) {
  4319. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4320. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4321. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4322. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4323. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4324. }
  4325. }
  4326. return imageData;
  4327. };
  4328. TGATools._TYPE_NO_DATA = 0;
  4329. TGATools._TYPE_INDEXED = 1;
  4330. TGATools._TYPE_RGB = 2;
  4331. TGATools._TYPE_GREY = 3;
  4332. TGATools._TYPE_RLE_INDEXED = 9;
  4333. TGATools._TYPE_RLE_RGB = 10;
  4334. TGATools._TYPE_RLE_GREY = 11;
  4335. TGATools._ORIGIN_MASK = 0x30;
  4336. TGATools._ORIGIN_SHIFT = 0x04;
  4337. TGATools._ORIGIN_BL = 0x00;
  4338. TGATools._ORIGIN_BR = 0x01;
  4339. TGATools._ORIGIN_UL = 0x02;
  4340. TGATools._ORIGIN_UR = 0x03;
  4341. return TGATools;
  4342. }());
  4343. Internals.TGATools = TGATools;
  4344. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4345. })(BABYLON || (BABYLON = {}));
  4346. var BABYLON;
  4347. (function (BABYLON) {
  4348. var SmartArray = (function () {
  4349. function SmartArray(capacity) {
  4350. this.length = 0;
  4351. this._duplicateId = 0;
  4352. this.data = new Array(capacity);
  4353. this._id = SmartArray._GlobalId++;
  4354. }
  4355. SmartArray.prototype.push = function (value) {
  4356. this.data[this.length++] = value;
  4357. if (this.length > this.data.length) {
  4358. this.data.length *= 2;
  4359. }
  4360. if (!value.__smartArrayFlags) {
  4361. value.__smartArrayFlags = {};
  4362. }
  4363. value.__smartArrayFlags[this._id] = this._duplicateId;
  4364. };
  4365. SmartArray.prototype.pushNoDuplicate = function (value) {
  4366. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4367. return false;
  4368. }
  4369. this.push(value);
  4370. return true;
  4371. };
  4372. SmartArray.prototype.sort = function (compareFn) {
  4373. this.data.sort(compareFn);
  4374. };
  4375. SmartArray.prototype.reset = function () {
  4376. this.length = 0;
  4377. this._duplicateId++;
  4378. };
  4379. SmartArray.prototype.concat = function (array) {
  4380. if (array.length === 0) {
  4381. return;
  4382. }
  4383. if (this.length + array.length > this.data.length) {
  4384. this.data.length = (this.length + array.length) * 2;
  4385. }
  4386. for (var index = 0; index < array.length; index++) {
  4387. this.data[this.length++] = (array.data || array)[index];
  4388. }
  4389. };
  4390. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4391. if (array.length === 0) {
  4392. return;
  4393. }
  4394. if (this.length + array.length > this.data.length) {
  4395. this.data.length = (this.length + array.length) * 2;
  4396. }
  4397. for (var index = 0; index < array.length; index++) {
  4398. var item = (array.data || array)[index];
  4399. this.pushNoDuplicate(item);
  4400. }
  4401. };
  4402. SmartArray.prototype.indexOf = function (value) {
  4403. var position = this.data.indexOf(value);
  4404. if (position >= this.length) {
  4405. return -1;
  4406. }
  4407. return position;
  4408. };
  4409. // Statics
  4410. SmartArray._GlobalId = 0;
  4411. return SmartArray;
  4412. }());
  4413. BABYLON.SmartArray = SmartArray;
  4414. })(BABYLON || (BABYLON = {}));
  4415. var BABYLON;
  4416. (function (BABYLON) {
  4417. /**
  4418. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4419. * The underlying implementation relies on an associative array to ensure the best performances.
  4420. * The value can be anything including 'null' but except 'undefined'
  4421. */
  4422. var StringDictionary = (function () {
  4423. function StringDictionary() {
  4424. this._count = 0;
  4425. this._data = {};
  4426. }
  4427. /**
  4428. * This will clear this dictionary and copy the content from the 'source' one.
  4429. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4430. * @param source the dictionary to take the content from and copy to this dictionary
  4431. */
  4432. StringDictionary.prototype.copyFrom = function (source) {
  4433. var _this = this;
  4434. this.clear();
  4435. source.forEach(function (t, v) { return _this.add(t, v); });
  4436. };
  4437. /**
  4438. * Get a value based from its key
  4439. * @param key the given key to get the matching value from
  4440. * @return the value if found, otherwise undefined is returned
  4441. */
  4442. StringDictionary.prototype.get = function (key) {
  4443. var val = this._data[key];
  4444. if (val !== undefined) {
  4445. return val;
  4446. }
  4447. return undefined;
  4448. };
  4449. /**
  4450. * Get a value from its key or add it if it doesn't exist.
  4451. * This method will ensure you that a given key/data will be present in the dictionary.
  4452. * @param key the given key to get the matching value from
  4453. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4454. * The factory will only be invoked if there's no data for the given key.
  4455. * @return the value corresponding to the key.
  4456. */
  4457. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4458. var val = this.get(key);
  4459. if (val !== undefined) {
  4460. return val;
  4461. }
  4462. val = factory(key);
  4463. if (val) {
  4464. this.add(key, val);
  4465. }
  4466. return val;
  4467. };
  4468. /**
  4469. * Get a value from its key if present in the dictionary otherwise add it
  4470. * @param key the key to get the value from
  4471. * @param val if there's no such key/value pair in the dictionary add it with this value
  4472. * @return the value corresponding to the key
  4473. */
  4474. StringDictionary.prototype.getOrAdd = function (key, val) {
  4475. var curVal = this.get(key);
  4476. if (curVal !== undefined) {
  4477. return curVal;
  4478. }
  4479. this.add(key, val);
  4480. return val;
  4481. };
  4482. /**
  4483. * Check if there's a given key in the dictionary
  4484. * @param key the key to check for
  4485. * @return true if the key is present, false otherwise
  4486. */
  4487. StringDictionary.prototype.contains = function (key) {
  4488. return this._data[key] !== undefined;
  4489. };
  4490. /**
  4491. * Add a new key and its corresponding value
  4492. * @param key the key to add
  4493. * @param value the value corresponding to the key
  4494. * @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
  4495. */
  4496. StringDictionary.prototype.add = function (key, value) {
  4497. if (this._data[key] !== undefined) {
  4498. return false;
  4499. }
  4500. this._data[key] = value;
  4501. ++this._count;
  4502. return true;
  4503. };
  4504. StringDictionary.prototype.set = function (key, value) {
  4505. if (this._data[key] === undefined) {
  4506. return false;
  4507. }
  4508. this._data[key] = value;
  4509. return true;
  4510. };
  4511. /**
  4512. * Get the element of the given key and remove it from the dictionary
  4513. * @param key
  4514. */
  4515. StringDictionary.prototype.getAndRemove = function (key) {
  4516. var val = this.get(key);
  4517. if (val !== undefined) {
  4518. delete this._data[key];
  4519. --this._count;
  4520. return val;
  4521. }
  4522. return null;
  4523. };
  4524. /**
  4525. * Remove a key/value from the dictionary.
  4526. * @param key the key to remove
  4527. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4528. */
  4529. StringDictionary.prototype.remove = function (key) {
  4530. if (this.contains(key)) {
  4531. delete this._data[key];
  4532. --this._count;
  4533. return true;
  4534. }
  4535. return false;
  4536. };
  4537. /**
  4538. * Clear the whole content of the dictionary
  4539. */
  4540. StringDictionary.prototype.clear = function () {
  4541. this._data = {};
  4542. this._count = 0;
  4543. };
  4544. Object.defineProperty(StringDictionary.prototype, "count", {
  4545. get: function () {
  4546. return this._count;
  4547. },
  4548. enumerable: true,
  4549. configurable: true
  4550. });
  4551. /**
  4552. * Execute a callback on each key/val of the dictionary.
  4553. * Note that you can remove any element in this dictionary in the callback implementation
  4554. * @param callback the callback to execute on a given key/value pair
  4555. */
  4556. StringDictionary.prototype.forEach = function (callback) {
  4557. for (var cur in this._data) {
  4558. var val = this._data[cur];
  4559. callback(cur, val);
  4560. }
  4561. };
  4562. /**
  4563. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4564. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4565. * Note that you can remove any element in this dictionary in the callback implementation
  4566. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4567. */
  4568. StringDictionary.prototype.first = function (callback) {
  4569. for (var cur in this._data) {
  4570. var val = this._data[cur];
  4571. var res = callback(cur, val);
  4572. if (res) {
  4573. return res;
  4574. }
  4575. }
  4576. return null;
  4577. };
  4578. return StringDictionary;
  4579. }());
  4580. BABYLON.StringDictionary = StringDictionary;
  4581. })(BABYLON || (BABYLON = {}));
  4582. var BABYLON;
  4583. (function (BABYLON) {
  4584. // Screenshots
  4585. var screenshotCanvas;
  4586. var cloneValue = function (source, destinationObject) {
  4587. if (!source)
  4588. return null;
  4589. if (source instanceof BABYLON.Mesh) {
  4590. return null;
  4591. }
  4592. if (source instanceof BABYLON.SubMesh) {
  4593. return source.clone(destinationObject);
  4594. }
  4595. else if (source.clone) {
  4596. return source.clone();
  4597. }
  4598. return null;
  4599. };
  4600. var Tools = (function () {
  4601. function Tools() {
  4602. }
  4603. Tools.Instantiate = function (className) {
  4604. var arr = className.split(".");
  4605. var fn = (window || this);
  4606. for (var i = 0, len = arr.length; i < len; i++) {
  4607. fn = fn[arr[i]];
  4608. }
  4609. if (typeof fn !== "function") {
  4610. return null;
  4611. }
  4612. return fn;
  4613. };
  4614. Tools.SetImmediate = function (action) {
  4615. if (window.setImmediate) {
  4616. window.setImmediate(action);
  4617. }
  4618. else {
  4619. setTimeout(action, 1);
  4620. }
  4621. };
  4622. Tools.IsExponentOfTwo = function (value) {
  4623. var count = 1;
  4624. do {
  4625. count *= 2;
  4626. } while (count < value);
  4627. return count === value;
  4628. };
  4629. Tools.GetExponentOfTwo = function (value, max) {
  4630. var count = 1;
  4631. do {
  4632. count *= 2;
  4633. } while (count < value);
  4634. if (count > max)
  4635. count = max;
  4636. return count;
  4637. };
  4638. Tools.GetFilename = function (path) {
  4639. var index = path.lastIndexOf("/");
  4640. if (index < 0)
  4641. return path;
  4642. return path.substring(index + 1);
  4643. };
  4644. Tools.GetDOMTextContent = function (element) {
  4645. var result = "";
  4646. var child = element.firstChild;
  4647. while (child) {
  4648. if (child.nodeType === 3) {
  4649. result += child.textContent;
  4650. }
  4651. child = child.nextSibling;
  4652. }
  4653. return result;
  4654. };
  4655. Tools.ToDegrees = function (angle) {
  4656. return angle * 180 / Math.PI;
  4657. };
  4658. Tools.ToRadians = function (angle) {
  4659. return angle * Math.PI / 180;
  4660. };
  4661. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4662. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4663. var output = "";
  4664. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4665. var i = 0;
  4666. var bytes = new Uint8Array(buffer);
  4667. while (i < bytes.length) {
  4668. chr1 = bytes[i++];
  4669. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4670. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4671. enc1 = chr1 >> 2;
  4672. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4673. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4674. enc4 = chr3 & 63;
  4675. if (isNaN(chr2)) {
  4676. enc3 = enc4 = 64;
  4677. }
  4678. else if (isNaN(chr3)) {
  4679. enc4 = 64;
  4680. }
  4681. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4682. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4683. }
  4684. return "data:image/png;base64," + output;
  4685. };
  4686. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4687. if (bias === void 0) { bias = null; }
  4688. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4689. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4690. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4691. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4692. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4693. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4694. }
  4695. if (bias) {
  4696. minimum.x -= minimum.x * bias.x + bias.y;
  4697. minimum.y -= minimum.y * bias.x + bias.y;
  4698. minimum.z -= minimum.z * bias.x + bias.y;
  4699. maximum.x += maximum.x * bias.x + bias.y;
  4700. maximum.y += maximum.y * bias.x + bias.y;
  4701. maximum.z += maximum.z * bias.x + bias.y;
  4702. }
  4703. return {
  4704. minimum: minimum,
  4705. maximum: maximum
  4706. };
  4707. };
  4708. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4709. if (bias === void 0) { bias = null; }
  4710. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4711. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4712. if (!stride) {
  4713. stride = 3;
  4714. }
  4715. for (var index = start; index < start + count; index++) {
  4716. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4717. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4718. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4719. }
  4720. if (bias) {
  4721. minimum.x -= minimum.x * bias.x + bias.y;
  4722. minimum.y -= minimum.y * bias.x + bias.y;
  4723. minimum.z -= minimum.z * bias.x + bias.y;
  4724. maximum.x += maximum.x * bias.x + bias.y;
  4725. maximum.y += maximum.y * bias.x + bias.y;
  4726. maximum.z += maximum.z * bias.x + bias.y;
  4727. }
  4728. return {
  4729. minimum: minimum,
  4730. maximum: maximum
  4731. };
  4732. };
  4733. Tools.Vector2ArrayFeeder = function (array) {
  4734. return function (index) {
  4735. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4736. var length = isFloatArray ? array.length / 2 : array.length;
  4737. if (index >= length) {
  4738. return null;
  4739. }
  4740. if (isFloatArray) {
  4741. var fa = array;
  4742. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4743. }
  4744. var a = array;
  4745. return a[index];
  4746. };
  4747. };
  4748. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4749. if (bias === void 0) { bias = null; }
  4750. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4751. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4752. var i = 0;
  4753. var cur = feeder(i++);
  4754. while (cur) {
  4755. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4756. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4757. cur = feeder(i++);
  4758. }
  4759. if (bias) {
  4760. minimum.x -= minimum.x * bias.x + bias.y;
  4761. minimum.y -= minimum.y * bias.x + bias.y;
  4762. maximum.x += maximum.x * bias.x + bias.y;
  4763. maximum.y += maximum.y * bias.x + bias.y;
  4764. }
  4765. return {
  4766. minimum: minimum,
  4767. maximum: maximum
  4768. };
  4769. };
  4770. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4771. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4772. return undefined;
  4773. return Array.isArray(obj) ? obj : [obj];
  4774. };
  4775. // Misc.
  4776. Tools.GetPointerPrefix = function () {
  4777. var eventPrefix = "pointer";
  4778. // Check if pointer events are supported
  4779. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4780. eventPrefix = "mouse";
  4781. }
  4782. return eventPrefix;
  4783. };
  4784. /**
  4785. * @param func - the function to be called
  4786. * @param requester - the object that will request the next frame. Falls back to window.
  4787. */
  4788. Tools.QueueNewFrame = function (func, requester) {
  4789. if (requester === void 0) { requester = window; }
  4790. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4791. /*if(requester.isPresenting) {
  4792. return;
  4793. } else*/ if (requester.requestAnimationFrame)
  4794. requester.requestAnimationFrame(func);
  4795. else if (requester.msRequestAnimationFrame)
  4796. requester.msRequestAnimationFrame(func);
  4797. else if (requester.webkitRequestAnimationFrame)
  4798. requester.webkitRequestAnimationFrame(func);
  4799. else if (requester.mozRequestAnimationFrame)
  4800. requester.mozRequestAnimationFrame(func);
  4801. else if (requester.oRequestAnimationFrame)
  4802. requester.oRequestAnimationFrame(func);
  4803. else {
  4804. window.setTimeout(func, 16);
  4805. }
  4806. };
  4807. Tools.RequestFullscreen = function (element) {
  4808. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4809. if (!requestFunction)
  4810. return;
  4811. requestFunction.call(element);
  4812. };
  4813. Tools.ExitFullscreen = function () {
  4814. if (document.exitFullscreen) {
  4815. document.exitFullscreen();
  4816. }
  4817. else if (document.mozCancelFullScreen) {
  4818. document.mozCancelFullScreen();
  4819. }
  4820. else if (document.webkitCancelFullScreen) {
  4821. document.webkitCancelFullScreen();
  4822. }
  4823. else if (document.msCancelFullScreen) {
  4824. document.msCancelFullScreen();
  4825. }
  4826. };
  4827. Tools.SetCorsBehavior = function (url, img) {
  4828. if (Tools.CorsBehavior) {
  4829. switch (typeof (Tools.CorsBehavior)) {
  4830. case "function":
  4831. var result = Tools.CorsBehavior(url);
  4832. if (result) {
  4833. return result;
  4834. }
  4835. break;
  4836. case "string":
  4837. default:
  4838. img.crossOrigin = Tools.CorsBehavior;
  4839. break;
  4840. }
  4841. }
  4842. };
  4843. // External files
  4844. Tools.CleanUrl = function (url) {
  4845. url = url.replace(/#/mg, "%23");
  4846. return url;
  4847. };
  4848. Tools.LoadImage = function (url, onload, onerror, database) {
  4849. if (url instanceof ArrayBuffer) {
  4850. url = Tools.EncodeArrayBufferTobase64(url);
  4851. }
  4852. url = Tools.CleanUrl(url);
  4853. var img = new Image();
  4854. if (url.substr(0, 5) !== "data:") {
  4855. Tools.SetCorsBehavior(url, img);
  4856. }
  4857. img.onload = function () {
  4858. onload(img);
  4859. };
  4860. img.onerror = function (err) {
  4861. Tools.Error("Error while trying to load texture: " + url);
  4862. if (Tools.UseFallbackTexture) {
  4863. img.src = "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";
  4864. onload(img);
  4865. }
  4866. else {
  4867. onerror();
  4868. }
  4869. };
  4870. var noIndexedDB = function () {
  4871. img.src = url;
  4872. };
  4873. var loadFromIndexedDB = function () {
  4874. database.loadImageFromDB(url, img);
  4875. };
  4876. //ANY database to do!
  4877. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4878. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4879. }
  4880. else {
  4881. if (url.indexOf("file:") === -1) {
  4882. noIndexedDB();
  4883. }
  4884. else {
  4885. try {
  4886. var textureName = url.substring(5).toLowerCase();
  4887. var blobURL;
  4888. try {
  4889. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4890. }
  4891. catch (ex) {
  4892. // Chrome doesn't support oneTimeOnly parameter
  4893. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4894. }
  4895. img.src = blobURL;
  4896. }
  4897. catch (e) {
  4898. img.src = null;
  4899. }
  4900. }
  4901. }
  4902. return img;
  4903. };
  4904. //ANY
  4905. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4906. url = Tools.CleanUrl(url);
  4907. var noIndexedDB = function () {
  4908. var request = new XMLHttpRequest();
  4909. var loadUrl = Tools.BaseUrl + url;
  4910. request.open('GET', loadUrl, true);
  4911. if (useArrayBuffer) {
  4912. request.responseType = "arraybuffer";
  4913. }
  4914. request.onprogress = progressCallBack;
  4915. request.onreadystatechange = function () {
  4916. if (request.readyState === 4) {
  4917. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4918. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4919. callback(!useArrayBuffer ? request.responseText : request.response);
  4920. }
  4921. else {
  4922. if (onError) {
  4923. onError();
  4924. }
  4925. else {
  4926. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4927. }
  4928. }
  4929. }
  4930. };
  4931. request.send(null);
  4932. };
  4933. var loadFromIndexedDB = function () {
  4934. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4935. };
  4936. if (url.indexOf("file:") !== -1) {
  4937. var fileName = url.substring(5).toLowerCase();
  4938. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4939. }
  4940. else {
  4941. // Caching all files
  4942. if (database && database.enableSceneOffline) {
  4943. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4944. }
  4945. else {
  4946. noIndexedDB();
  4947. }
  4948. }
  4949. };
  4950. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4951. var reader = new FileReader();
  4952. reader.onload = function (e) {
  4953. //target doesn't have result from ts 1.3
  4954. callback(e.target['result']);
  4955. };
  4956. reader.onprogress = progressCallback;
  4957. reader.readAsDataURL(fileToLoad);
  4958. };
  4959. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4960. var reader = new FileReader();
  4961. reader.onerror = function (e) {
  4962. Tools.Log("Error while reading file: " + fileToLoad.name);
  4963. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4964. };
  4965. reader.onload = function (e) {
  4966. //target doesn't have result from ts 1.3
  4967. callback(e.target['result']);
  4968. };
  4969. reader.onprogress = progressCallBack;
  4970. if (!useArrayBuffer) {
  4971. // Asynchronous read
  4972. reader.readAsText(fileToLoad);
  4973. }
  4974. else {
  4975. reader.readAsArrayBuffer(fileToLoad);
  4976. }
  4977. };
  4978. //returns a downloadable url to a file content.
  4979. Tools.FileAsURL = function (content) {
  4980. var fileBlob = new Blob([content]);
  4981. var url = window.URL || window.webkitURL;
  4982. var link = url.createObjectURL(fileBlob);
  4983. return link;
  4984. };
  4985. // Misc.
  4986. Tools.Format = function (value, decimals) {
  4987. if (decimals === void 0) { decimals = 2; }
  4988. return value.toFixed(decimals);
  4989. };
  4990. Tools.CheckExtends = function (v, min, max) {
  4991. if (v.x < min.x)
  4992. min.x = v.x;
  4993. if (v.y < min.y)
  4994. min.y = v.y;
  4995. if (v.z < min.z)
  4996. min.z = v.z;
  4997. if (v.x > max.x)
  4998. max.x = v.x;
  4999. if (v.y > max.y)
  5000. max.y = v.y;
  5001. if (v.z > max.z)
  5002. max.z = v.z;
  5003. };
  5004. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5005. for (var prop in source) {
  5006. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5007. continue;
  5008. }
  5009. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5010. continue;
  5011. }
  5012. var sourceValue = source[prop];
  5013. var typeOfSourceValue = typeof sourceValue;
  5014. if (typeOfSourceValue === "function") {
  5015. continue;
  5016. }
  5017. if (typeOfSourceValue === "object") {
  5018. if (sourceValue instanceof Array) {
  5019. destination[prop] = [];
  5020. if (sourceValue.length > 0) {
  5021. if (typeof sourceValue[0] == "object") {
  5022. for (var index = 0; index < sourceValue.length; index++) {
  5023. var clonedValue = cloneValue(sourceValue[index], destination);
  5024. if (destination[prop].indexOf(clonedValue) === -1) {
  5025. destination[prop].push(clonedValue);
  5026. }
  5027. }
  5028. }
  5029. else {
  5030. destination[prop] = sourceValue.slice(0);
  5031. }
  5032. }
  5033. }
  5034. else {
  5035. destination[prop] = cloneValue(sourceValue, destination);
  5036. }
  5037. }
  5038. else {
  5039. destination[prop] = sourceValue;
  5040. }
  5041. }
  5042. };
  5043. Tools.IsEmpty = function (obj) {
  5044. for (var i in obj) {
  5045. return false;
  5046. }
  5047. return true;
  5048. };
  5049. Tools.RegisterTopRootEvents = function (events) {
  5050. for (var index = 0; index < events.length; index++) {
  5051. var event = events[index];
  5052. window.addEventListener(event.name, event.handler, false);
  5053. try {
  5054. if (window.parent) {
  5055. window.parent.addEventListener(event.name, event.handler, false);
  5056. }
  5057. }
  5058. catch (e) {
  5059. }
  5060. }
  5061. };
  5062. Tools.UnregisterTopRootEvents = function (events) {
  5063. for (var index = 0; index < events.length; index++) {
  5064. var event = events[index];
  5065. window.removeEventListener(event.name, event.handler);
  5066. try {
  5067. if (window.parent) {
  5068. window.parent.removeEventListener(event.name, event.handler);
  5069. }
  5070. }
  5071. catch (e) {
  5072. }
  5073. }
  5074. };
  5075. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5076. if (mimeType === void 0) { mimeType = "image/png"; }
  5077. // Read the contents of the framebuffer
  5078. var numberOfChannelsByLine = width * 4;
  5079. var halfHeight = height / 2;
  5080. //Reading datas from WebGL
  5081. var data = engine.readPixels(0, 0, width, height);
  5082. //To flip image on Y axis.
  5083. for (var i = 0; i < halfHeight; i++) {
  5084. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5085. var currentCell = j + i * numberOfChannelsByLine;
  5086. var targetLine = height - i - 1;
  5087. var targetCell = j + targetLine * numberOfChannelsByLine;
  5088. var temp = data[currentCell];
  5089. data[currentCell] = data[targetCell];
  5090. data[targetCell] = temp;
  5091. }
  5092. }
  5093. // Create a 2D canvas to store the result
  5094. if (!screenshotCanvas) {
  5095. screenshotCanvas = document.createElement('canvas');
  5096. }
  5097. screenshotCanvas.width = width;
  5098. screenshotCanvas.height = height;
  5099. var context = screenshotCanvas.getContext('2d');
  5100. // Copy the pixels to a 2D canvas
  5101. var imageData = context.createImageData(width, height);
  5102. var castData = (imageData.data);
  5103. castData.set(data);
  5104. context.putImageData(imageData, 0, 0);
  5105. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5106. };
  5107. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5108. if (mimeType === void 0) { mimeType = "image/png"; }
  5109. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5110. if (successCallback) {
  5111. successCallback(base64Image);
  5112. }
  5113. else {
  5114. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5115. if (("download" in document.createElement("a"))) {
  5116. var a = window.document.createElement("a");
  5117. a.href = base64Image;
  5118. var date = new Date();
  5119. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5120. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5121. window.document.body.appendChild(a);
  5122. a.addEventListener("click", function () {
  5123. a.parentElement.removeChild(a);
  5124. });
  5125. a.click();
  5126. }
  5127. else {
  5128. var newWindow = window.open("");
  5129. var img = newWindow.document.createElement("img");
  5130. img.src = base64Image;
  5131. newWindow.document.body.appendChild(img);
  5132. }
  5133. }
  5134. };
  5135. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5136. if (mimeType === void 0) { mimeType = "image/png"; }
  5137. var width;
  5138. var height;
  5139. // If a precision value is specified
  5140. if (size.precision) {
  5141. width = Math.round(engine.getRenderWidth() * size.precision);
  5142. height = Math.round(width / engine.getAspectRatio(camera));
  5143. }
  5144. else if (size.width && size.height) {
  5145. width = size.width;
  5146. height = size.height;
  5147. }
  5148. else if (size.width && !size.height) {
  5149. width = size.width;
  5150. height = Math.round(width / engine.getAspectRatio(camera));
  5151. }
  5152. else if (size.height && !size.width) {
  5153. height = size.height;
  5154. width = Math.round(height * engine.getAspectRatio(camera));
  5155. }
  5156. else if (!isNaN(size)) {
  5157. height = size;
  5158. width = size;
  5159. }
  5160. else {
  5161. Tools.Error("Invalid 'size' parameter !");
  5162. return;
  5163. }
  5164. if (!screenshotCanvas) {
  5165. screenshotCanvas = document.createElement('canvas');
  5166. }
  5167. screenshotCanvas.width = width;
  5168. screenshotCanvas.height = height;
  5169. var renderContext = screenshotCanvas.getContext("2d");
  5170. renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
  5171. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5172. };
  5173. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5174. if (mimeType === void 0) { mimeType = "image/png"; }
  5175. var width;
  5176. var height;
  5177. //If a precision value is specified
  5178. if (size.precision) {
  5179. width = Math.round(engine.getRenderWidth() * size.precision);
  5180. height = Math.round(width / engine.getAspectRatio(camera));
  5181. size = { width: width, height: height };
  5182. }
  5183. else if (size.width && size.height) {
  5184. width = size.width;
  5185. height = size.height;
  5186. }
  5187. else if (size.width && !size.height) {
  5188. width = size.width;
  5189. height = Math.round(width / engine.getAspectRatio(camera));
  5190. size = { width: width, height: height };
  5191. }
  5192. else if (size.height && !size.width) {
  5193. height = size.height;
  5194. width = Math.round(height * engine.getAspectRatio(camera));
  5195. size = { width: width, height: height };
  5196. }
  5197. else if (!isNaN(size)) {
  5198. height = size;
  5199. width = size;
  5200. }
  5201. else {
  5202. Tools.Error("Invalid 'size' parameter !");
  5203. return;
  5204. }
  5205. var scene = camera.getScene();
  5206. var previousCamera = null;
  5207. if (scene.activeCamera !== camera) {
  5208. previousCamera = scene.activeCamera;
  5209. scene.activeCamera = camera;
  5210. }
  5211. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5212. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5213. texture.renderList = scene.meshes;
  5214. texture.onAfterRenderObservable.add(function () {
  5215. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5216. });
  5217. scene.incrementRenderId();
  5218. scene.resetCachedMaterial();
  5219. texture.render(true);
  5220. texture.dispose();
  5221. if (previousCamera) {
  5222. scene.activeCamera = previousCamera;
  5223. }
  5224. camera.getProjectionMatrix(true); // Force cache refresh;
  5225. };
  5226. // XHR response validator for local file scenario
  5227. Tools.ValidateXHRData = function (xhr, dataType) {
  5228. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5229. if (dataType === void 0) { dataType = 7; }
  5230. try {
  5231. if (dataType & 1) {
  5232. if (xhr.responseText && xhr.responseText.length > 0) {
  5233. return true;
  5234. }
  5235. else if (dataType === 1) {
  5236. return false;
  5237. }
  5238. }
  5239. if (dataType & 2) {
  5240. // Check header width and height since there is no "TGA" magic number
  5241. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5242. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5243. return true;
  5244. }
  5245. else if (dataType === 2) {
  5246. return false;
  5247. }
  5248. }
  5249. if (dataType & 4) {
  5250. // Check for the "DDS" magic number
  5251. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5252. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5253. return true;
  5254. }
  5255. else {
  5256. return false;
  5257. }
  5258. }
  5259. }
  5260. catch (e) {
  5261. }
  5262. return false;
  5263. };
  5264. /**
  5265. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5266. * Be aware Math.random() could cause collisions, but:
  5267. * "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"
  5268. */
  5269. Tools.RandomId = function () {
  5270. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5271. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5272. return v.toString(16);
  5273. });
  5274. };
  5275. Object.defineProperty(Tools, "NoneLogLevel", {
  5276. get: function () {
  5277. return Tools._NoneLogLevel;
  5278. },
  5279. enumerable: true,
  5280. configurable: true
  5281. });
  5282. Object.defineProperty(Tools, "MessageLogLevel", {
  5283. get: function () {
  5284. return Tools._MessageLogLevel;
  5285. },
  5286. enumerable: true,
  5287. configurable: true
  5288. });
  5289. Object.defineProperty(Tools, "WarningLogLevel", {
  5290. get: function () {
  5291. return Tools._WarningLogLevel;
  5292. },
  5293. enumerable: true,
  5294. configurable: true
  5295. });
  5296. Object.defineProperty(Tools, "ErrorLogLevel", {
  5297. get: function () {
  5298. return Tools._ErrorLogLevel;
  5299. },
  5300. enumerable: true,
  5301. configurable: true
  5302. });
  5303. Object.defineProperty(Tools, "AllLogLevel", {
  5304. get: function () {
  5305. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5306. },
  5307. enumerable: true,
  5308. configurable: true
  5309. });
  5310. Tools._AddLogEntry = function (entry) {
  5311. Tools._LogCache = entry + Tools._LogCache;
  5312. if (Tools.OnNewCacheEntry) {
  5313. Tools.OnNewCacheEntry(entry);
  5314. }
  5315. };
  5316. Tools._FormatMessage = function (message) {
  5317. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5318. var date = new Date();
  5319. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5320. };
  5321. Tools._LogDisabled = function (message) {
  5322. // nothing to do
  5323. };
  5324. Tools._LogEnabled = function (message) {
  5325. var formattedMessage = Tools._FormatMessage(message);
  5326. console.log("BJS - " + formattedMessage);
  5327. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5328. Tools._AddLogEntry(entry);
  5329. };
  5330. Tools._WarnDisabled = function (message) {
  5331. // nothing to do
  5332. };
  5333. Tools._WarnEnabled = function (message) {
  5334. var formattedMessage = Tools._FormatMessage(message);
  5335. console.warn("BJS - " + formattedMessage);
  5336. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5337. Tools._AddLogEntry(entry);
  5338. };
  5339. Tools._ErrorDisabled = function (message) {
  5340. // nothing to do
  5341. };
  5342. Tools._ErrorEnabled = function (message) {
  5343. Tools.errorsCount++;
  5344. var formattedMessage = Tools._FormatMessage(message);
  5345. console.error("BJS - " + formattedMessage);
  5346. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5347. Tools._AddLogEntry(entry);
  5348. };
  5349. Object.defineProperty(Tools, "LogCache", {
  5350. get: function () {
  5351. return Tools._LogCache;
  5352. },
  5353. enumerable: true,
  5354. configurable: true
  5355. });
  5356. Tools.ClearLogCache = function () {
  5357. Tools._LogCache = "";
  5358. Tools.errorsCount = 0;
  5359. };
  5360. Object.defineProperty(Tools, "LogLevels", {
  5361. set: function (level) {
  5362. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5363. Tools.Log = Tools._LogEnabled;
  5364. }
  5365. else {
  5366. Tools.Log = Tools._LogDisabled;
  5367. }
  5368. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5369. Tools.Warn = Tools._WarnEnabled;
  5370. }
  5371. else {
  5372. Tools.Warn = Tools._WarnDisabled;
  5373. }
  5374. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5375. Tools.Error = Tools._ErrorEnabled;
  5376. }
  5377. else {
  5378. Tools.Error = Tools._ErrorDisabled;
  5379. }
  5380. },
  5381. enumerable: true,
  5382. configurable: true
  5383. });
  5384. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5385. get: function () {
  5386. return Tools._PerformanceNoneLogLevel;
  5387. },
  5388. enumerable: true,
  5389. configurable: true
  5390. });
  5391. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5392. get: function () {
  5393. return Tools._PerformanceUserMarkLogLevel;
  5394. },
  5395. enumerable: true,
  5396. configurable: true
  5397. });
  5398. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5399. get: function () {
  5400. return Tools._PerformanceConsoleLogLevel;
  5401. },
  5402. enumerable: true,
  5403. configurable: true
  5404. });
  5405. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5406. set: function (level) {
  5407. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5408. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5409. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5410. return;
  5411. }
  5412. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5413. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5414. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5415. return;
  5416. }
  5417. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5418. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5419. },
  5420. enumerable: true,
  5421. configurable: true
  5422. });
  5423. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5424. };
  5425. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5426. };
  5427. Tools._StartUserMark = function (counterName, condition) {
  5428. if (condition === void 0) { condition = true; }
  5429. if (!condition || !Tools._performance.mark) {
  5430. return;
  5431. }
  5432. Tools._performance.mark(counterName + "-Begin");
  5433. };
  5434. Tools._EndUserMark = function (counterName, condition) {
  5435. if (condition === void 0) { condition = true; }
  5436. if (!condition || !Tools._performance.mark) {
  5437. return;
  5438. }
  5439. Tools._performance.mark(counterName + "-End");
  5440. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5441. };
  5442. Tools._StartPerformanceConsole = function (counterName, condition) {
  5443. if (condition === void 0) { condition = true; }
  5444. if (!condition) {
  5445. return;
  5446. }
  5447. Tools._StartUserMark(counterName, condition);
  5448. if (console.time) {
  5449. console.time(counterName);
  5450. }
  5451. };
  5452. Tools._EndPerformanceConsole = function (counterName, condition) {
  5453. if (condition === void 0) { condition = true; }
  5454. if (!condition) {
  5455. return;
  5456. }
  5457. Tools._EndUserMark(counterName, condition);
  5458. if (console.time) {
  5459. console.timeEnd(counterName);
  5460. }
  5461. };
  5462. Object.defineProperty(Tools, "Now", {
  5463. get: function () {
  5464. if (window.performance && window.performance.now) {
  5465. return window.performance.now();
  5466. }
  5467. return new Date().getTime();
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. /**
  5473. * This method will return the name of the class used to create the instance of the given object.
  5474. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5475. * @param object the object to get the class name from
  5476. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5477. */
  5478. Tools.getClassName = function (object, isType) {
  5479. if (isType === void 0) { isType = false; }
  5480. var name = null;
  5481. if (!isType && object.getClassName) {
  5482. name = object.getClassName();
  5483. }
  5484. else {
  5485. if (object instanceof Object) {
  5486. var classObj = isType ? object : Object.getPrototypeOf(object);
  5487. name = classObj.constructor["__bjsclassName__"];
  5488. }
  5489. if (!name) {
  5490. name = typeof object;
  5491. }
  5492. }
  5493. return name;
  5494. };
  5495. Tools.first = function (array, predicate) {
  5496. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5497. var el = array_1[_i];
  5498. if (predicate(el)) {
  5499. return el;
  5500. }
  5501. }
  5502. };
  5503. /**
  5504. * This method will return the name of the full name of the class, including its owning module (if any).
  5505. * 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).
  5506. * @param object the object to get the class name from
  5507. * @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.
  5508. */
  5509. Tools.getFullClassName = function (object, isType) {
  5510. if (isType === void 0) { isType = false; }
  5511. var className = null;
  5512. var moduleName = null;
  5513. if (!isType && object.getClassName) {
  5514. className = object.getClassName();
  5515. }
  5516. else {
  5517. if (object instanceof Object) {
  5518. var classObj = isType ? object : Object.getPrototypeOf(object);
  5519. className = classObj.constructor["__bjsclassName__"];
  5520. moduleName = classObj.constructor["__bjsmoduleName__"];
  5521. }
  5522. if (!className) {
  5523. className = typeof object;
  5524. }
  5525. }
  5526. if (!className) {
  5527. return null;
  5528. }
  5529. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5530. };
  5531. /**
  5532. * 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.
  5533. * @param array
  5534. */
  5535. Tools.arrayOrStringFeeder = function (array) {
  5536. return function (index) {
  5537. if (index >= array.length) {
  5538. return null;
  5539. }
  5540. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5541. if (val && val.getHashCode) {
  5542. val = val.getHashCode();
  5543. }
  5544. if (typeof val === "string") {
  5545. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5546. }
  5547. return val;
  5548. };
  5549. };
  5550. /**
  5551. * Compute the hashCode of a stream of number
  5552. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5553. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5554. * @return the hash code computed
  5555. */
  5556. Tools.hashCodeFromStream = function (feeder) {
  5557. // Based from here: http://stackoverflow.com/a/7616484/802124
  5558. var hash = 0;
  5559. var index = 0;
  5560. var chr = feeder(index++);
  5561. while (chr != null) {
  5562. hash = ((hash << 5) - hash) + chr;
  5563. hash |= 0; // Convert to 32bit integer
  5564. chr = feeder(index++);
  5565. }
  5566. return hash;
  5567. };
  5568. Tools.BaseUrl = "";
  5569. Tools.CorsBehavior = "anonymous";
  5570. Tools.UseFallbackTexture = true;
  5571. // Logs
  5572. Tools._NoneLogLevel = 0;
  5573. Tools._MessageLogLevel = 1;
  5574. Tools._WarningLogLevel = 2;
  5575. Tools._ErrorLogLevel = 4;
  5576. Tools._LogCache = "";
  5577. Tools.errorsCount = 0;
  5578. Tools.Log = Tools._LogEnabled;
  5579. Tools.Warn = Tools._WarnEnabled;
  5580. Tools.Error = Tools._ErrorEnabled;
  5581. // Performances
  5582. Tools._PerformanceNoneLogLevel = 0;
  5583. Tools._PerformanceUserMarkLogLevel = 1;
  5584. Tools._PerformanceConsoleLogLevel = 2;
  5585. Tools._performance = window.performance;
  5586. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5587. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5588. return Tools;
  5589. }());
  5590. BABYLON.Tools = Tools;
  5591. /**
  5592. * This class is used to track a performance counter which is number based.
  5593. * The user has access to many properties which give statistics of different nature
  5594. *
  5595. * The implementer can track two kinds of Performance Counter: time and count
  5596. * 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.
  5597. * 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.
  5598. */
  5599. var PerfCounter = (function () {
  5600. function PerfCounter() {
  5601. this._startMonitoringTime = 0;
  5602. this._min = 0;
  5603. this._max = 0;
  5604. this._average = 0;
  5605. this._lastSecAverage = 0;
  5606. this._current = 0;
  5607. this._totalValueCount = 0;
  5608. this._totalAccumulated = 0;
  5609. this._lastSecAccumulated = 0;
  5610. this._lastSecTime = 0;
  5611. this._lastSecValueCount = 0;
  5612. }
  5613. Object.defineProperty(PerfCounter.prototype, "min", {
  5614. /**
  5615. * Returns the smallest value ever
  5616. */
  5617. get: function () {
  5618. return this._min;
  5619. },
  5620. enumerable: true,
  5621. configurable: true
  5622. });
  5623. Object.defineProperty(PerfCounter.prototype, "max", {
  5624. /**
  5625. * Returns the biggest value ever
  5626. */
  5627. get: function () {
  5628. return this._max;
  5629. },
  5630. enumerable: true,
  5631. configurable: true
  5632. });
  5633. Object.defineProperty(PerfCounter.prototype, "average", {
  5634. /**
  5635. * Returns the average value since the performance counter is running
  5636. */
  5637. get: function () {
  5638. return this._average;
  5639. },
  5640. enumerable: true,
  5641. configurable: true
  5642. });
  5643. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5644. /**
  5645. * Returns the average value of the last second the counter was monitored
  5646. */
  5647. get: function () {
  5648. return this._lastSecAverage;
  5649. },
  5650. enumerable: true,
  5651. configurable: true
  5652. });
  5653. Object.defineProperty(PerfCounter.prototype, "current", {
  5654. /**
  5655. * Returns the current value
  5656. */
  5657. get: function () {
  5658. return this._current;
  5659. },
  5660. enumerable: true,
  5661. configurable: true
  5662. });
  5663. Object.defineProperty(PerfCounter.prototype, "total", {
  5664. get: function () {
  5665. return this._totalAccumulated;
  5666. },
  5667. enumerable: true,
  5668. configurable: true
  5669. });
  5670. /**
  5671. * Call this method to start monitoring a new frame.
  5672. * 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.
  5673. */
  5674. PerfCounter.prototype.fetchNewFrame = function () {
  5675. this._totalValueCount++;
  5676. this._current = 0;
  5677. this._lastSecValueCount++;
  5678. };
  5679. /**
  5680. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5681. * @param newCount the count value to add to the monitored count
  5682. * @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.
  5683. */
  5684. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5685. this._current += newCount;
  5686. if (fetchResult) {
  5687. this._fetchResult();
  5688. }
  5689. };
  5690. /**
  5691. * Start monitoring this performance counter
  5692. */
  5693. PerfCounter.prototype.beginMonitoring = function () {
  5694. this._startMonitoringTime = Tools.Now;
  5695. };
  5696. /**
  5697. * Compute the time lapsed since the previous beginMonitoring() call.
  5698. * @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
  5699. */
  5700. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5701. if (newFrame === void 0) { newFrame = true; }
  5702. if (newFrame) {
  5703. this.fetchNewFrame();
  5704. }
  5705. var currentTime = Tools.Now;
  5706. this._current = currentTime - this._startMonitoringTime;
  5707. if (newFrame) {
  5708. this._fetchResult();
  5709. }
  5710. };
  5711. PerfCounter.prototype._fetchResult = function () {
  5712. this._totalAccumulated += this._current;
  5713. this._lastSecAccumulated += this._current;
  5714. // Min/Max update
  5715. this._min = Math.min(this._min, this._current);
  5716. this._max = Math.max(this._max, this._current);
  5717. this._average = this._totalAccumulated / this._totalValueCount;
  5718. // Reset last sec?
  5719. var now = Tools.Now;
  5720. if ((now - this._lastSecTime) > 1000) {
  5721. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5722. this._lastSecTime = now;
  5723. this._lastSecAccumulated = 0;
  5724. this._lastSecValueCount = 0;
  5725. }
  5726. };
  5727. return PerfCounter;
  5728. }());
  5729. BABYLON.PerfCounter = PerfCounter;
  5730. /**
  5731. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5732. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5733. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5734. * @param name The name of the class, case should be preserved
  5735. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5736. */
  5737. function className(name, module) {
  5738. return function (target) {
  5739. target["__bjsclassName__"] = name;
  5740. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5741. };
  5742. }
  5743. BABYLON.className = className;
  5744. /**
  5745. * An implementation of a loop for asynchronous functions.
  5746. */
  5747. var AsyncLoop = (function () {
  5748. /**
  5749. * Constroctor.
  5750. * @param iterations the number of iterations.
  5751. * @param _fn the function to run each iteration
  5752. * @param _successCallback the callback that will be called upon succesful execution
  5753. * @param offset starting offset.
  5754. */
  5755. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5756. if (offset === void 0) { offset = 0; }
  5757. this.iterations = iterations;
  5758. this._fn = _fn;
  5759. this._successCallback = _successCallback;
  5760. this.index = offset - 1;
  5761. this._done = false;
  5762. }
  5763. /**
  5764. * Execute the next iteration. Must be called after the last iteration was finished.
  5765. */
  5766. AsyncLoop.prototype.executeNext = function () {
  5767. if (!this._done) {
  5768. if (this.index + 1 < this.iterations) {
  5769. ++this.index;
  5770. this._fn(this);
  5771. }
  5772. else {
  5773. this.breakLoop();
  5774. }
  5775. }
  5776. };
  5777. /**
  5778. * Break the loop and run the success callback.
  5779. */
  5780. AsyncLoop.prototype.breakLoop = function () {
  5781. this._done = true;
  5782. this._successCallback();
  5783. };
  5784. /**
  5785. * Helper function
  5786. */
  5787. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5788. if (offset === void 0) { offset = 0; }
  5789. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5790. loop.executeNext();
  5791. return loop;
  5792. };
  5793. /**
  5794. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5795. * @param iterations total number of iterations
  5796. * @param syncedIterations number of synchronous iterations in each async iteration.
  5797. * @param fn the function to call each iteration.
  5798. * @param callback a success call back that will be called when iterating stops.
  5799. * @param breakFunction a break condition (optional)
  5800. * @param timeout timeout settings for the setTimeout function. default - 0.
  5801. * @constructor
  5802. */
  5803. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5804. if (timeout === void 0) { timeout = 0; }
  5805. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5806. if (breakFunction && breakFunction())
  5807. loop.breakLoop();
  5808. else {
  5809. setTimeout(function () {
  5810. for (var i = 0; i < syncedIterations; ++i) {
  5811. var iteration = (loop.index * syncedIterations) + i;
  5812. if (iteration >= iterations)
  5813. break;
  5814. fn(iteration);
  5815. if (breakFunction && breakFunction()) {
  5816. loop.breakLoop();
  5817. break;
  5818. }
  5819. }
  5820. loop.executeNext();
  5821. }, timeout);
  5822. }
  5823. }, callback);
  5824. };
  5825. return AsyncLoop;
  5826. }());
  5827. BABYLON.AsyncLoop = AsyncLoop;
  5828. })(BABYLON || (BABYLON = {}));
  5829. var BABYLON;
  5830. (function (BABYLON) {
  5831. var Internals;
  5832. (function (Internals) {
  5833. var _AlphaState = (function () {
  5834. /**
  5835. * Initializes the state.
  5836. */
  5837. function _AlphaState() {
  5838. this._isAlphaBlendDirty = false;
  5839. this._isBlendFunctionParametersDirty = false;
  5840. this._alphaBlend = false;
  5841. this._blendFunctionParameters = new Array(4);
  5842. this.reset();
  5843. }
  5844. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5845. get: function () {
  5846. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5847. },
  5848. enumerable: true,
  5849. configurable: true
  5850. });
  5851. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5852. get: function () {
  5853. return this._alphaBlend;
  5854. },
  5855. set: function (value) {
  5856. if (this._alphaBlend === value) {
  5857. return;
  5858. }
  5859. this._alphaBlend = value;
  5860. this._isAlphaBlendDirty = true;
  5861. },
  5862. enumerable: true,
  5863. configurable: true
  5864. });
  5865. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5866. if (this._blendFunctionParameters[0] === value0 &&
  5867. this._blendFunctionParameters[1] === value1 &&
  5868. this._blendFunctionParameters[2] === value2 &&
  5869. this._blendFunctionParameters[3] === value3) {
  5870. return;
  5871. }
  5872. this._blendFunctionParameters[0] = value0;
  5873. this._blendFunctionParameters[1] = value1;
  5874. this._blendFunctionParameters[2] = value2;
  5875. this._blendFunctionParameters[3] = value3;
  5876. this._isBlendFunctionParametersDirty = true;
  5877. };
  5878. _AlphaState.prototype.reset = function () {
  5879. this._alphaBlend = false;
  5880. this._blendFunctionParameters[0] = null;
  5881. this._blendFunctionParameters[1] = null;
  5882. this._blendFunctionParameters[2] = null;
  5883. this._blendFunctionParameters[3] = null;
  5884. this._isAlphaBlendDirty = true;
  5885. this._isBlendFunctionParametersDirty = false;
  5886. };
  5887. _AlphaState.prototype.apply = function (gl) {
  5888. if (!this.isDirty) {
  5889. return;
  5890. }
  5891. // Alpha blend
  5892. if (this._isAlphaBlendDirty) {
  5893. if (this._alphaBlend) {
  5894. gl.enable(gl.BLEND);
  5895. }
  5896. else {
  5897. gl.disable(gl.BLEND);
  5898. }
  5899. this._isAlphaBlendDirty = false;
  5900. }
  5901. // Alpha function
  5902. if (this._isBlendFunctionParametersDirty) {
  5903. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5904. this._isBlendFunctionParametersDirty = false;
  5905. }
  5906. };
  5907. return _AlphaState;
  5908. }());
  5909. Internals._AlphaState = _AlphaState;
  5910. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5911. })(BABYLON || (BABYLON = {}));
  5912. var BABYLON;
  5913. (function (BABYLON) {
  5914. var Internals;
  5915. (function (Internals) {
  5916. var _DepthCullingState = (function () {
  5917. /**
  5918. * Initializes the state.
  5919. */
  5920. function _DepthCullingState() {
  5921. this._isDepthTestDirty = false;
  5922. this._isDepthMaskDirty = false;
  5923. this._isDepthFuncDirty = false;
  5924. this._isCullFaceDirty = false;
  5925. this._isCullDirty = false;
  5926. this._isZOffsetDirty = false;
  5927. this.reset();
  5928. }
  5929. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5930. get: function () {
  5931. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5932. },
  5933. enumerable: true,
  5934. configurable: true
  5935. });
  5936. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5937. get: function () {
  5938. return this._zOffset;
  5939. },
  5940. set: function (value) {
  5941. if (this._zOffset === value) {
  5942. return;
  5943. }
  5944. this._zOffset = value;
  5945. this._isZOffsetDirty = true;
  5946. },
  5947. enumerable: true,
  5948. configurable: true
  5949. });
  5950. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5951. get: function () {
  5952. return this._cullFace;
  5953. },
  5954. set: function (value) {
  5955. if (this._cullFace === value) {
  5956. return;
  5957. }
  5958. this._cullFace = value;
  5959. this._isCullFaceDirty = true;
  5960. },
  5961. enumerable: true,
  5962. configurable: true
  5963. });
  5964. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5965. get: function () {
  5966. return this._cull;
  5967. },
  5968. set: function (value) {
  5969. if (this._cull === value) {
  5970. return;
  5971. }
  5972. this._cull = value;
  5973. this._isCullDirty = true;
  5974. },
  5975. enumerable: true,
  5976. configurable: true
  5977. });
  5978. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5979. get: function () {
  5980. return this._depthFunc;
  5981. },
  5982. set: function (value) {
  5983. if (this._depthFunc === value) {
  5984. return;
  5985. }
  5986. this._depthFunc = value;
  5987. this._isDepthFuncDirty = true;
  5988. },
  5989. enumerable: true,
  5990. configurable: true
  5991. });
  5992. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5993. get: function () {
  5994. return this._depthMask;
  5995. },
  5996. set: function (value) {
  5997. if (this._depthMask === value) {
  5998. return;
  5999. }
  6000. this._depthMask = value;
  6001. this._isDepthMaskDirty = true;
  6002. },
  6003. enumerable: true,
  6004. configurable: true
  6005. });
  6006. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6007. get: function () {
  6008. return this._depthTest;
  6009. },
  6010. set: function (value) {
  6011. if (this._depthTest === value) {
  6012. return;
  6013. }
  6014. this._depthTest = value;
  6015. this._isDepthTestDirty = true;
  6016. },
  6017. enumerable: true,
  6018. configurable: true
  6019. });
  6020. _DepthCullingState.prototype.reset = function () {
  6021. this._depthMask = true;
  6022. this._depthTest = true;
  6023. this._depthFunc = null;
  6024. this._cullFace = null;
  6025. this._cull = null;
  6026. this._zOffset = 0;
  6027. this._isDepthTestDirty = true;
  6028. this._isDepthMaskDirty = true;
  6029. this._isDepthFuncDirty = false;
  6030. this._isCullFaceDirty = false;
  6031. this._isCullDirty = false;
  6032. this._isZOffsetDirty = false;
  6033. };
  6034. _DepthCullingState.prototype.apply = function (gl) {
  6035. if (!this.isDirty) {
  6036. return;
  6037. }
  6038. // Cull
  6039. if (this._isCullDirty) {
  6040. if (this.cull) {
  6041. gl.enable(gl.CULL_FACE);
  6042. }
  6043. else {
  6044. gl.disable(gl.CULL_FACE);
  6045. }
  6046. this._isCullDirty = false;
  6047. }
  6048. // Cull face
  6049. if (this._isCullFaceDirty) {
  6050. gl.cullFace(this.cullFace);
  6051. this._isCullFaceDirty = false;
  6052. }
  6053. // Depth mask
  6054. if (this._isDepthMaskDirty) {
  6055. gl.depthMask(this.depthMask);
  6056. this._isDepthMaskDirty = false;
  6057. }
  6058. // Depth test
  6059. if (this._isDepthTestDirty) {
  6060. if (this.depthTest) {
  6061. gl.enable(gl.DEPTH_TEST);
  6062. }
  6063. else {
  6064. gl.disable(gl.DEPTH_TEST);
  6065. }
  6066. this._isDepthTestDirty = false;
  6067. }
  6068. // Depth func
  6069. if (this._isDepthFuncDirty) {
  6070. gl.depthFunc(this.depthFunc);
  6071. this._isDepthFuncDirty = false;
  6072. }
  6073. // zOffset
  6074. if (this._isZOffsetDirty) {
  6075. if (this.zOffset) {
  6076. gl.enable(gl.POLYGON_OFFSET_FILL);
  6077. gl.polygonOffset(this.zOffset, 0);
  6078. }
  6079. else {
  6080. gl.disable(gl.POLYGON_OFFSET_FILL);
  6081. }
  6082. this._isZOffsetDirty = false;
  6083. }
  6084. };
  6085. return _DepthCullingState;
  6086. }());
  6087. Internals._DepthCullingState = _DepthCullingState;
  6088. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6089. })(BABYLON || (BABYLON = {}));
  6090. var BABYLON;
  6091. (function (BABYLON) {
  6092. var Internals;
  6093. (function (Internals) {
  6094. var _StencilState = (function () {
  6095. function _StencilState() {
  6096. this._isStencilTestDirty = false;
  6097. this._isStencilMaskDirty = false;
  6098. this._isStencilFuncDirty = false;
  6099. this._isStencilOpDirty = false;
  6100. this.reset();
  6101. }
  6102. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6103. get: function () {
  6104. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6105. },
  6106. enumerable: true,
  6107. configurable: true
  6108. });
  6109. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6110. get: function () {
  6111. return this._stencilFunc;
  6112. },
  6113. set: function (value) {
  6114. if (this._stencilFunc === value) {
  6115. return;
  6116. }
  6117. this._stencilFunc = value;
  6118. this._isStencilFuncDirty = true;
  6119. },
  6120. enumerable: true,
  6121. configurable: true
  6122. });
  6123. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6124. get: function () {
  6125. return this._stencilFuncRef;
  6126. },
  6127. set: function (value) {
  6128. if (this._stencilFuncRef === value) {
  6129. return;
  6130. }
  6131. this._stencilFuncRef = value;
  6132. this._isStencilFuncDirty = true;
  6133. },
  6134. enumerable: true,
  6135. configurable: true
  6136. });
  6137. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6138. get: function () {
  6139. return this._stencilFuncMask;
  6140. },
  6141. set: function (value) {
  6142. if (this._stencilFuncMask === value) {
  6143. return;
  6144. }
  6145. this._stencilFuncMask = value;
  6146. this._isStencilFuncDirty = true;
  6147. },
  6148. enumerable: true,
  6149. configurable: true
  6150. });
  6151. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6152. get: function () {
  6153. return this._stencilOpStencilFail;
  6154. },
  6155. set: function (value) {
  6156. if (this._stencilOpStencilFail === value) {
  6157. return;
  6158. }
  6159. this._stencilOpStencilFail = value;
  6160. this._isStencilOpDirty = true;
  6161. },
  6162. enumerable: true,
  6163. configurable: true
  6164. });
  6165. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6166. get: function () {
  6167. return this._stencilOpDepthFail;
  6168. },
  6169. set: function (value) {
  6170. if (this._stencilOpDepthFail === value) {
  6171. return;
  6172. }
  6173. this._stencilOpDepthFail = value;
  6174. this._isStencilOpDirty = true;
  6175. },
  6176. enumerable: true,
  6177. configurable: true
  6178. });
  6179. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6180. get: function () {
  6181. return this._stencilOpStencilDepthPass;
  6182. },
  6183. set: function (value) {
  6184. if (this._stencilOpStencilDepthPass === value) {
  6185. return;
  6186. }
  6187. this._stencilOpStencilDepthPass = value;
  6188. this._isStencilOpDirty = true;
  6189. },
  6190. enumerable: true,
  6191. configurable: true
  6192. });
  6193. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6194. get: function () {
  6195. return this._stencilMask;
  6196. },
  6197. set: function (value) {
  6198. if (this._stencilMask === value) {
  6199. return;
  6200. }
  6201. this._stencilMask = value;
  6202. this._isStencilMaskDirty = true;
  6203. },
  6204. enumerable: true,
  6205. configurable: true
  6206. });
  6207. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6208. get: function () {
  6209. return this._stencilTest;
  6210. },
  6211. set: function (value) {
  6212. if (this._stencilTest === value) {
  6213. return;
  6214. }
  6215. this._stencilTest = value;
  6216. this._isStencilTestDirty = true;
  6217. },
  6218. enumerable: true,
  6219. configurable: true
  6220. });
  6221. _StencilState.prototype.reset = function () {
  6222. this._stencilTest = false;
  6223. this._stencilMask = 0xFF;
  6224. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6225. this._stencilFuncRef = 1;
  6226. this._stencilFuncMask = 0xFF;
  6227. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6228. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6229. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6230. this._isStencilTestDirty = true;
  6231. this._isStencilMaskDirty = true;
  6232. this._isStencilFuncDirty = true;
  6233. this._isStencilOpDirty = true;
  6234. };
  6235. _StencilState.prototype.apply = function (gl) {
  6236. if (!this.isDirty) {
  6237. return;
  6238. }
  6239. // Stencil test
  6240. if (this._isStencilTestDirty) {
  6241. if (this.stencilTest) {
  6242. gl.enable(gl.STENCIL_TEST);
  6243. }
  6244. else {
  6245. gl.disable(gl.STENCIL_TEST);
  6246. }
  6247. this._isStencilTestDirty = false;
  6248. }
  6249. // Stencil mask
  6250. if (this._isStencilMaskDirty) {
  6251. gl.stencilMask(this.stencilMask);
  6252. this._isStencilMaskDirty = false;
  6253. }
  6254. // Stencil func
  6255. if (this._isStencilFuncDirty) {
  6256. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6257. this._isStencilFuncDirty = false;
  6258. }
  6259. // Stencil op
  6260. if (this._isStencilOpDirty) {
  6261. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6262. this._isStencilOpDirty = false;
  6263. }
  6264. };
  6265. return _StencilState;
  6266. }());
  6267. Internals._StencilState = _StencilState;
  6268. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6269. })(BABYLON || (BABYLON = {}));
  6270. var BABYLON;
  6271. (function (BABYLON) {
  6272. var compileShader = function (gl, source, type, defines) {
  6273. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6274. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6275. gl.compileShader(shader);
  6276. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6277. throw new Error(gl.getShaderInfoLog(shader));
  6278. }
  6279. return shader;
  6280. };
  6281. var HALF_FLOAT_OES = 0x8D61;
  6282. var getWebGLTextureType = function (gl, type) {
  6283. if (type === Engine.TEXTURETYPE_FLOAT) {
  6284. return gl.FLOAT;
  6285. }
  6286. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6287. // Add Half Float Constant.
  6288. return HALF_FLOAT_OES;
  6289. }
  6290. return gl.UNSIGNED_BYTE;
  6291. };
  6292. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6293. var magFilter = gl.NEAREST;
  6294. var minFilter = gl.NEAREST;
  6295. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6296. magFilter = gl.LINEAR;
  6297. if (generateMipMaps) {
  6298. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6299. }
  6300. else {
  6301. minFilter = gl.LINEAR;
  6302. }
  6303. }
  6304. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6305. magFilter = gl.LINEAR;
  6306. if (generateMipMaps) {
  6307. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6308. }
  6309. else {
  6310. minFilter = gl.LINEAR;
  6311. }
  6312. }
  6313. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6314. magFilter = gl.NEAREST;
  6315. if (generateMipMaps) {
  6316. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6317. }
  6318. else {
  6319. minFilter = gl.NEAREST;
  6320. }
  6321. }
  6322. return {
  6323. min: minFilter,
  6324. mag: magFilter
  6325. };
  6326. };
  6327. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6328. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6329. var engine = scene.getEngine();
  6330. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6331. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6332. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6333. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6334. texture._baseWidth = width;
  6335. texture._baseHeight = height;
  6336. texture._width = potWidth;
  6337. texture._height = potHeight;
  6338. texture.isReady = true;
  6339. processFunction(potWidth, potHeight);
  6340. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6341. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6342. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6343. if (!noMipmap && !isCompressed) {
  6344. gl.generateMipmap(gl.TEXTURE_2D);
  6345. }
  6346. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6347. engine.resetTextureCache();
  6348. scene._removePendingData(texture);
  6349. texture.onLoadedCallbacks.forEach(function (callback) {
  6350. callback();
  6351. });
  6352. texture.onLoadedCallbacks = [];
  6353. };
  6354. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6355. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6356. var img;
  6357. var onload = function () {
  6358. loadedImages[index] = img;
  6359. loadedImages._internalCount++;
  6360. scene._removePendingData(img);
  6361. if (loadedImages._internalCount === 6) {
  6362. onfinish(loadedImages);
  6363. }
  6364. };
  6365. var onerror = function () {
  6366. scene._removePendingData(img);
  6367. if (onErrorCallBack) {
  6368. onErrorCallBack();
  6369. }
  6370. };
  6371. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6372. scene._addPendingData(img);
  6373. };
  6374. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6375. if (onError === void 0) { onError = null; }
  6376. var loadedImages = [];
  6377. loadedImages._internalCount = 0;
  6378. for (var index = 0; index < 6; index++) {
  6379. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6380. }
  6381. };
  6382. var InstancingAttributeInfo = (function () {
  6383. function InstancingAttributeInfo() {
  6384. }
  6385. return InstancingAttributeInfo;
  6386. }());
  6387. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6388. var EngineCapabilities = (function () {
  6389. function EngineCapabilities() {
  6390. }
  6391. return EngineCapabilities;
  6392. }());
  6393. BABYLON.EngineCapabilities = EngineCapabilities;
  6394. /**
  6395. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6396. */
  6397. var Engine = (function () {
  6398. /**
  6399. * @constructor
  6400. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6401. * @param {boolean} [antialias] - enable antialias
  6402. * @param options - further options to be sent to the getContext function
  6403. */
  6404. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6405. var _this = this;
  6406. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6407. // Public members
  6408. this.isFullscreen = false;
  6409. this.isPointerLock = false;
  6410. this.cullBackFaces = true;
  6411. this.renderEvenInBackground = true;
  6412. // To enable/disable IDB support and avoid XHR on .manifest
  6413. this.enableOfflineSupport = true;
  6414. this.scenes = new Array();
  6415. this._windowIsBackground = false;
  6416. this._webGLVersion = "1.0";
  6417. this._badOS = false;
  6418. this._drawCalls = new BABYLON.PerfCounter();
  6419. this._renderingQueueLaunched = false;
  6420. this._activeRenderLoops = [];
  6421. // FPS
  6422. this.fpsRange = 60;
  6423. this.previousFramesDuration = [];
  6424. this.fps = 60;
  6425. this.deltaTime = 0;
  6426. // States
  6427. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6428. this._stencilState = new BABYLON.Internals._StencilState();
  6429. this._alphaState = new BABYLON.Internals._AlphaState();
  6430. this._alphaMode = Engine.ALPHA_DISABLE;
  6431. // Cache
  6432. this._loadedTexturesCache = new Array();
  6433. this._maxTextureChannels = 16;
  6434. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6435. this._compiledEffects = {};
  6436. this._vertexAttribArraysEnabled = [];
  6437. this._uintIndicesCurrentlySet = false;
  6438. this._currentBoundBuffer = new Array();
  6439. this._currentBufferPointers = [];
  6440. this._currentInstanceLocations = new Array();
  6441. this._currentInstanceBuffers = new Array();
  6442. this._onVRFullScreenTriggered = function () {
  6443. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6444. //get the old size before we change
  6445. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6446. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6447. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6448. //But actually, no browser follow the specs...
  6449. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6450. //get the width and height, change the render size
  6451. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6452. var width, height;
  6453. _this.setHardwareScalingLevel(1);
  6454. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6455. }
  6456. else {
  6457. //When the specs are implemented, need to uncomment this.
  6458. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6459. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6460. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6461. _this._vrDisplayEnabled = undefined;
  6462. }
  6463. };
  6464. this._renderingCanvas = canvas;
  6465. this._externalData = new BABYLON.StringDictionary();
  6466. options = options || {};
  6467. if (antialias != null) {
  6468. options.antialias = antialias;
  6469. }
  6470. if (options.preserveDrawingBuffer === undefined) {
  6471. options.preserveDrawingBuffer = false;
  6472. }
  6473. // Checks if some of the format renders first to allow the use of webgl inspector.
  6474. var renderToFullFloat = this._canRenderToFloatTexture();
  6475. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6476. // GL
  6477. //try {
  6478. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6479. // if (this._gl) {
  6480. // this._webGLVersion = "2.0";
  6481. // }
  6482. //} catch (e) {
  6483. // // Do nothing
  6484. //}
  6485. if (!this._gl) {
  6486. if (!canvas) {
  6487. throw new Error("The provided canvas is null or undefined.");
  6488. }
  6489. try {
  6490. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6491. }
  6492. catch (e) {
  6493. throw new Error("WebGL not supported");
  6494. }
  6495. }
  6496. if (!this._gl) {
  6497. throw new Error("WebGL not supported");
  6498. }
  6499. this._onBlur = function () {
  6500. _this._windowIsBackground = true;
  6501. };
  6502. this._onFocus = function () {
  6503. _this._windowIsBackground = false;
  6504. };
  6505. window.addEventListener("blur", this._onBlur);
  6506. window.addEventListener("focus", this._onFocus);
  6507. // Viewport
  6508. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6509. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6510. this.resize();
  6511. // Caps
  6512. this._isStencilEnable = options.stencil;
  6513. this._caps = new EngineCapabilities();
  6514. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6515. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6516. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6517. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6518. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6519. // Infos
  6520. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6521. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6522. if (rendererInfo != null) {
  6523. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6524. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6525. }
  6526. if (!this._glVendor) {
  6527. this._glVendor = "Unknown vendor";
  6528. }
  6529. if (!this._glRenderer) {
  6530. this._glRenderer = "Unknown renderer";
  6531. }
  6532. // Extensions
  6533. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6534. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6535. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6536. 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');
  6537. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6538. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6539. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6540. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6541. this._caps.highPrecisionShaderSupported = true;
  6542. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6543. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6544. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6545. this._caps.textureFloatRender = renderToFullFloat;
  6546. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6547. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6548. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6549. if (this._gl.getShaderPrecisionFormat) {
  6550. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6551. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6552. }
  6553. // Depth buffer
  6554. this.setDepthBuffer(true);
  6555. this.setDepthFunctionToLessOrEqual();
  6556. this.setDepthWrite(true);
  6557. // Fullscreen
  6558. this._onFullscreenChange = function () {
  6559. if (document.fullscreen !== undefined) {
  6560. _this.isFullscreen = document.fullscreen;
  6561. }
  6562. else if (document.mozFullScreen !== undefined) {
  6563. _this.isFullscreen = document.mozFullScreen;
  6564. }
  6565. else if (document.webkitIsFullScreen !== undefined) {
  6566. _this.isFullscreen = document.webkitIsFullScreen;
  6567. }
  6568. else if (document.msIsFullScreen !== undefined) {
  6569. _this.isFullscreen = document.msIsFullScreen;
  6570. }
  6571. // Pointer lock
  6572. if (_this.isFullscreen && _this._pointerLockRequested) {
  6573. canvas.requestPointerLock = canvas.requestPointerLock ||
  6574. canvas.msRequestPointerLock ||
  6575. canvas.mozRequestPointerLock ||
  6576. canvas.webkitRequestPointerLock;
  6577. if (canvas.requestPointerLock) {
  6578. canvas.requestPointerLock();
  6579. }
  6580. }
  6581. };
  6582. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6583. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6584. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6585. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6586. // Pointer lock
  6587. this._onPointerLockChange = function () {
  6588. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6589. document.webkitPointerLockElement === canvas ||
  6590. document.msPointerLockElement === canvas ||
  6591. document.pointerLockElement === canvas);
  6592. };
  6593. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6594. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6595. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6596. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6597. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6598. Engine.audioEngine = new BABYLON.AudioEngine();
  6599. }
  6600. //default loading screen
  6601. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6602. //Load WebVR Devices
  6603. if (options.autoEnableWebVR) {
  6604. this.initWebVR();
  6605. }
  6606. //Detect if we are running on a faulty buggy OS.
  6607. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6608. //ua sniffing is the tool of the devil.
  6609. this._badOS = regexp.test(navigator.userAgent);
  6610. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6611. }
  6612. Object.defineProperty(Engine, "NEVER", {
  6613. get: function () {
  6614. return Engine._NEVER;
  6615. },
  6616. enumerable: true,
  6617. configurable: true
  6618. });
  6619. Object.defineProperty(Engine, "ALWAYS", {
  6620. get: function () {
  6621. return Engine._ALWAYS;
  6622. },
  6623. enumerable: true,
  6624. configurable: true
  6625. });
  6626. Object.defineProperty(Engine, "LESS", {
  6627. get: function () {
  6628. return Engine._LESS;
  6629. },
  6630. enumerable: true,
  6631. configurable: true
  6632. });
  6633. Object.defineProperty(Engine, "EQUAL", {
  6634. get: function () {
  6635. return Engine._EQUAL;
  6636. },
  6637. enumerable: true,
  6638. configurable: true
  6639. });
  6640. Object.defineProperty(Engine, "LEQUAL", {
  6641. get: function () {
  6642. return Engine._LEQUAL;
  6643. },
  6644. enumerable: true,
  6645. configurable: true
  6646. });
  6647. Object.defineProperty(Engine, "GREATER", {
  6648. get: function () {
  6649. return Engine._GREATER;
  6650. },
  6651. enumerable: true,
  6652. configurable: true
  6653. });
  6654. Object.defineProperty(Engine, "GEQUAL", {
  6655. get: function () {
  6656. return Engine._GEQUAL;
  6657. },
  6658. enumerable: true,
  6659. configurable: true
  6660. });
  6661. Object.defineProperty(Engine, "NOTEQUAL", {
  6662. get: function () {
  6663. return Engine._NOTEQUAL;
  6664. },
  6665. enumerable: true,
  6666. configurable: true
  6667. });
  6668. Object.defineProperty(Engine, "KEEP", {
  6669. get: function () {
  6670. return Engine._KEEP;
  6671. },
  6672. enumerable: true,
  6673. configurable: true
  6674. });
  6675. Object.defineProperty(Engine, "REPLACE", {
  6676. get: function () {
  6677. return Engine._REPLACE;
  6678. },
  6679. enumerable: true,
  6680. configurable: true
  6681. });
  6682. Object.defineProperty(Engine, "INCR", {
  6683. get: function () {
  6684. return Engine._INCR;
  6685. },
  6686. enumerable: true,
  6687. configurable: true
  6688. });
  6689. Object.defineProperty(Engine, "DECR", {
  6690. get: function () {
  6691. return Engine._DECR;
  6692. },
  6693. enumerable: true,
  6694. configurable: true
  6695. });
  6696. Object.defineProperty(Engine, "INVERT", {
  6697. get: function () {
  6698. return Engine._INVERT;
  6699. },
  6700. enumerable: true,
  6701. configurable: true
  6702. });
  6703. Object.defineProperty(Engine, "INCR_WRAP", {
  6704. get: function () {
  6705. return Engine._INCR_WRAP;
  6706. },
  6707. enumerable: true,
  6708. configurable: true
  6709. });
  6710. Object.defineProperty(Engine, "DECR_WRAP", {
  6711. get: function () {
  6712. return Engine._DECR_WRAP;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6718. get: function () {
  6719. return Engine._ALPHA_DISABLE;
  6720. },
  6721. enumerable: true,
  6722. configurable: true
  6723. });
  6724. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6725. get: function () {
  6726. return Engine._ALPHA_ONEONE;
  6727. },
  6728. enumerable: true,
  6729. configurable: true
  6730. });
  6731. Object.defineProperty(Engine, "ALPHA_ADD", {
  6732. get: function () {
  6733. return Engine._ALPHA_ADD;
  6734. },
  6735. enumerable: true,
  6736. configurable: true
  6737. });
  6738. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6739. get: function () {
  6740. return Engine._ALPHA_COMBINE;
  6741. },
  6742. enumerable: true,
  6743. configurable: true
  6744. });
  6745. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6746. get: function () {
  6747. return Engine._ALPHA_SUBTRACT;
  6748. },
  6749. enumerable: true,
  6750. configurable: true
  6751. });
  6752. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6753. get: function () {
  6754. return Engine._ALPHA_MULTIPLY;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6760. get: function () {
  6761. return Engine._ALPHA_MAXIMIZED;
  6762. },
  6763. enumerable: true,
  6764. configurable: true
  6765. });
  6766. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6767. get: function () {
  6768. return Engine._DELAYLOADSTATE_NONE;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6774. get: function () {
  6775. return Engine._DELAYLOADSTATE_LOADED;
  6776. },
  6777. enumerable: true,
  6778. configurable: true
  6779. });
  6780. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6781. get: function () {
  6782. return Engine._DELAYLOADSTATE_LOADING;
  6783. },
  6784. enumerable: true,
  6785. configurable: true
  6786. });
  6787. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6788. get: function () {
  6789. return Engine._DELAYLOADSTATE_NOTLOADED;
  6790. },
  6791. enumerable: true,
  6792. configurable: true
  6793. });
  6794. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6795. get: function () {
  6796. return Engine._TEXTUREFORMAT_ALPHA;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6802. get: function () {
  6803. return Engine._TEXTUREFORMAT_LUMINANCE;
  6804. },
  6805. enumerable: true,
  6806. configurable: true
  6807. });
  6808. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6809. get: function () {
  6810. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6811. },
  6812. enumerable: true,
  6813. configurable: true
  6814. });
  6815. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6816. get: function () {
  6817. return Engine._TEXTUREFORMAT_RGB;
  6818. },
  6819. enumerable: true,
  6820. configurable: true
  6821. });
  6822. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6823. get: function () {
  6824. return Engine._TEXTUREFORMAT_RGBA;
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6830. get: function () {
  6831. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6832. },
  6833. enumerable: true,
  6834. configurable: true
  6835. });
  6836. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6837. get: function () {
  6838. return Engine._TEXTURETYPE_FLOAT;
  6839. },
  6840. enumerable: true,
  6841. configurable: true
  6842. });
  6843. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6844. get: function () {
  6845. return Engine._TEXTURETYPE_HALF_FLOAT;
  6846. },
  6847. enumerable: true,
  6848. configurable: true
  6849. });
  6850. Object.defineProperty(Engine, "Version", {
  6851. get: function () {
  6852. return "2.5.-beta";
  6853. },
  6854. enumerable: true,
  6855. configurable: true
  6856. });
  6857. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6858. get: function () {
  6859. return this._webGLVersion;
  6860. },
  6861. enumerable: true,
  6862. configurable: true
  6863. });
  6864. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6865. /**
  6866. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6867. */
  6868. get: function () {
  6869. return this._isStencilEnable;
  6870. },
  6871. enumerable: true,
  6872. configurable: true
  6873. });
  6874. Engine.prototype._prepareWorkingCanvas = function () {
  6875. if (this._workingCanvas) {
  6876. return;
  6877. }
  6878. this._workingCanvas = document.createElement("canvas");
  6879. this._workingContext = this._workingCanvas.getContext("2d");
  6880. };
  6881. Engine.prototype.resetTextureCache = function () {
  6882. for (var index = 0; index < this._maxTextureChannels; index++) {
  6883. this._activeTexturesCache[index] = null;
  6884. }
  6885. };
  6886. Engine.prototype.getGlInfo = function () {
  6887. return {
  6888. vendor: this._glVendor,
  6889. renderer: this._glRenderer,
  6890. version: this._glVersion
  6891. };
  6892. };
  6893. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6894. if (useScreen === void 0) { useScreen = false; }
  6895. var viewport = camera.viewport;
  6896. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6897. };
  6898. Engine.prototype.getRenderWidth = function (useScreen) {
  6899. if (useScreen === void 0) { useScreen = false; }
  6900. if (!useScreen && this._currentRenderTarget) {
  6901. return this._currentRenderTarget._width;
  6902. }
  6903. return this._renderingCanvas.width;
  6904. };
  6905. Engine.prototype.getRenderHeight = function (useScreen) {
  6906. if (useScreen === void 0) { useScreen = false; }
  6907. if (!useScreen && this._currentRenderTarget) {
  6908. return this._currentRenderTarget._height;
  6909. }
  6910. return this._renderingCanvas.height;
  6911. };
  6912. Engine.prototype.getRenderingCanvas = function () {
  6913. return this._renderingCanvas;
  6914. };
  6915. Engine.prototype.getRenderingCanvasClientRect = function () {
  6916. return this._renderingCanvas.getBoundingClientRect();
  6917. };
  6918. Engine.prototype.setHardwareScalingLevel = function (level) {
  6919. this._hardwareScalingLevel = level;
  6920. this.resize();
  6921. };
  6922. Engine.prototype.getHardwareScalingLevel = function () {
  6923. return this._hardwareScalingLevel;
  6924. };
  6925. Engine.prototype.getLoadedTexturesCache = function () {
  6926. return this._loadedTexturesCache;
  6927. };
  6928. Engine.prototype.getCaps = function () {
  6929. return this._caps;
  6930. };
  6931. Object.defineProperty(Engine.prototype, "drawCalls", {
  6932. get: function () {
  6933. return this._drawCalls.current;
  6934. },
  6935. enumerable: true,
  6936. configurable: true
  6937. });
  6938. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6939. get: function () {
  6940. return this._drawCalls;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Engine.prototype.getDepthFunction = function () {
  6946. return this._depthCullingState.depthFunc;
  6947. };
  6948. Engine.prototype.setDepthFunction = function (depthFunc) {
  6949. this._depthCullingState.depthFunc = depthFunc;
  6950. };
  6951. Engine.prototype.setDepthFunctionToGreater = function () {
  6952. this._depthCullingState.depthFunc = this._gl.GREATER;
  6953. };
  6954. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6955. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6956. };
  6957. Engine.prototype.setDepthFunctionToLess = function () {
  6958. this._depthCullingState.depthFunc = this._gl.LESS;
  6959. };
  6960. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6961. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6962. };
  6963. Engine.prototype.getStencilBuffer = function () {
  6964. return this._stencilState.stencilTest;
  6965. };
  6966. Engine.prototype.setStencilBuffer = function (enable) {
  6967. this._stencilState.stencilTest = enable;
  6968. };
  6969. Engine.prototype.getStencilMask = function () {
  6970. return this._stencilState.stencilMask;
  6971. };
  6972. Engine.prototype.setStencilMask = function (mask) {
  6973. this._stencilState.stencilMask = mask;
  6974. };
  6975. Engine.prototype.getStencilFunction = function () {
  6976. return this._stencilState.stencilFunc;
  6977. };
  6978. Engine.prototype.getStencilFunctionReference = function () {
  6979. return this._stencilState.stencilFuncRef;
  6980. };
  6981. Engine.prototype.getStencilFunctionMask = function () {
  6982. return this._stencilState.stencilFuncMask;
  6983. };
  6984. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6985. this._stencilState.stencilFunc = stencilFunc;
  6986. };
  6987. Engine.prototype.setStencilFunctionReference = function (reference) {
  6988. this._stencilState.stencilFuncRef = reference;
  6989. };
  6990. Engine.prototype.setStencilFunctionMask = function (mask) {
  6991. this._stencilState.stencilFuncMask = mask;
  6992. };
  6993. Engine.prototype.getStencilOperationFail = function () {
  6994. return this._stencilState.stencilOpStencilFail;
  6995. };
  6996. Engine.prototype.getStencilOperationDepthFail = function () {
  6997. return this._stencilState.stencilOpDepthFail;
  6998. };
  6999. Engine.prototype.getStencilOperationPass = function () {
  7000. return this._stencilState.stencilOpStencilDepthPass;
  7001. };
  7002. Engine.prototype.setStencilOperationFail = function (operation) {
  7003. this._stencilState.stencilOpStencilFail = operation;
  7004. };
  7005. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7006. this._stencilState.stencilOpDepthFail = operation;
  7007. };
  7008. Engine.prototype.setStencilOperationPass = function (operation) {
  7009. this._stencilState.stencilOpStencilDepthPass = operation;
  7010. };
  7011. /**
  7012. * stop executing a render loop function and remove it from the execution array
  7013. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7014. */
  7015. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7016. if (!renderFunction) {
  7017. this._activeRenderLoops = [];
  7018. return;
  7019. }
  7020. var index = this._activeRenderLoops.indexOf(renderFunction);
  7021. if (index >= 0) {
  7022. this._activeRenderLoops.splice(index, 1);
  7023. }
  7024. };
  7025. Engine.prototype._renderLoop = function () {
  7026. var shouldRender = true;
  7027. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7028. shouldRender = false;
  7029. }
  7030. if (shouldRender) {
  7031. // Start new frame
  7032. this.beginFrame();
  7033. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7034. var renderFunction = this._activeRenderLoops[index];
  7035. renderFunction();
  7036. }
  7037. // Present
  7038. this.endFrame();
  7039. }
  7040. if (this._activeRenderLoops.length > 0) {
  7041. // Register new frame
  7042. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7043. }
  7044. else {
  7045. this._renderingQueueLaunched = false;
  7046. }
  7047. };
  7048. /**
  7049. * Register and execute a render loop. The engine can have more than one render function.
  7050. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7051. * @example
  7052. * engine.runRenderLoop(function () {
  7053. * scene.render()
  7054. * })
  7055. */
  7056. Engine.prototype.runRenderLoop = function (renderFunction) {
  7057. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7058. return;
  7059. }
  7060. this._activeRenderLoops.push(renderFunction);
  7061. if (!this._renderingQueueLaunched) {
  7062. this._renderingQueueLaunched = true;
  7063. this._bindedRenderFunction = this._renderLoop.bind(this);
  7064. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7065. }
  7066. };
  7067. /**
  7068. * Toggle full screen mode.
  7069. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7070. * @param {any} options - an options object to be sent to the requestFullscreen function
  7071. */
  7072. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7073. if (this.isFullscreen) {
  7074. BABYLON.Tools.ExitFullscreen();
  7075. }
  7076. else {
  7077. this._pointerLockRequested = requestPointerLock;
  7078. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7079. }
  7080. };
  7081. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7082. if (stencil === void 0) { stencil = false; }
  7083. this.applyStates();
  7084. var mode = 0;
  7085. if (backBuffer) {
  7086. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7087. mode |= this._gl.COLOR_BUFFER_BIT;
  7088. }
  7089. if (depth) {
  7090. this._gl.clearDepth(1.0);
  7091. mode |= this._gl.DEPTH_BUFFER_BIT;
  7092. }
  7093. if (stencil) {
  7094. this._gl.clearStencil(0);
  7095. mode |= this._gl.STENCIL_BUFFER_BIT;
  7096. }
  7097. this._gl.clear(mode);
  7098. };
  7099. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7100. var gl = this._gl;
  7101. // Save state
  7102. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7103. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7104. // Change state
  7105. gl.enable(gl.SCISSOR_TEST);
  7106. gl.scissor(x, y, width, height);
  7107. // Clear
  7108. this.clear(clearColor, true, true, true);
  7109. // Restore state
  7110. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7111. if (curScissor === true) {
  7112. gl.enable(gl.SCISSOR_TEST);
  7113. }
  7114. else {
  7115. gl.disable(gl.SCISSOR_TEST);
  7116. }
  7117. };
  7118. /**
  7119. * Set the WebGL's viewport
  7120. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7121. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7122. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7123. */
  7124. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7125. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  7126. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  7127. var x = viewport.x || 0;
  7128. var y = viewport.y || 0;
  7129. this._cachedViewport = viewport;
  7130. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7131. };
  7132. /**
  7133. * Directly set the WebGL Viewport
  7134. * The x, y, width & height are directly passed to the WebGL call
  7135. * @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.
  7136. */
  7137. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7138. var currentViewport = this._cachedViewport;
  7139. this._cachedViewport = null;
  7140. this._gl.viewport(x, y, width, height);
  7141. return currentViewport;
  7142. };
  7143. Engine.prototype.beginFrame = function () {
  7144. this._measureFps();
  7145. };
  7146. Engine.prototype.endFrame = function () {
  7147. //force a flush in case we are using a bad OS.
  7148. if (this._badOS) {
  7149. this.flushFramebuffer();
  7150. }
  7151. //submit frame to the vr device, if enabled
  7152. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7153. this._vrDisplayEnabled.submitFrame();
  7154. }
  7155. };
  7156. /**
  7157. * resize the view according to the canvas' size.
  7158. * @example
  7159. * window.addEventListener("resize", function () {
  7160. * engine.resize();
  7161. * });
  7162. */
  7163. Engine.prototype.resize = function () {
  7164. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7165. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7166. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7167. for (var index = 0; index < this.scenes.length; index++) {
  7168. var scene = this.scenes[index];
  7169. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  7170. scene.debugLayer._syncPositions();
  7171. }
  7172. }
  7173. };
  7174. /**
  7175. * force a specific size of the canvas
  7176. * @param {number} width - the new canvas' width
  7177. * @param {number} height - the new canvas' height
  7178. */
  7179. Engine.prototype.setSize = function (width, height) {
  7180. this._renderingCanvas.width = width;
  7181. this._renderingCanvas.height = height;
  7182. for (var index = 0; index < this.scenes.length; index++) {
  7183. var scene = this.scenes[index];
  7184. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7185. var cam = scene.cameras[camIndex];
  7186. cam._currentRenderId = 0;
  7187. }
  7188. }
  7189. };
  7190. //WebVR functions
  7191. Engine.prototype.initWebVR = function () {
  7192. if (!this.vrDisplaysPromise) {
  7193. this._getVRDisplays();
  7194. }
  7195. };
  7196. Engine.prototype.enableVR = function (vrDevice) {
  7197. this._vrDisplayEnabled = vrDevice;
  7198. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7199. };
  7200. Engine.prototype.disableVR = function () {
  7201. if (this._vrDisplayEnabled) {
  7202. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7203. }
  7204. };
  7205. Engine.prototype._getVRDisplays = function () {
  7206. var _this = this;
  7207. var getWebVRDevices = function (devices) {
  7208. var size = devices.length;
  7209. var i = 0;
  7210. _this._vrDisplays = devices.filter(function (device) {
  7211. return devices[i] instanceof VRDisplay;
  7212. });
  7213. return _this._vrDisplays;
  7214. };
  7215. //using a key due to typescript
  7216. if (navigator.getVRDisplays) {
  7217. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7218. }
  7219. };
  7220. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7221. this._currentRenderTarget = texture;
  7222. this.bindUnboundFramebuffer(texture._framebuffer);
  7223. var gl = this._gl;
  7224. if (texture.isCube) {
  7225. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7226. }
  7227. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7228. this.wipeCaches();
  7229. };
  7230. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7231. if (this._currentFramebuffer !== framebuffer) {
  7232. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7233. this._currentFramebuffer = framebuffer;
  7234. }
  7235. };
  7236. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7237. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7238. this._currentRenderTarget = null;
  7239. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7240. var gl = this._gl;
  7241. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7242. gl.generateMipmap(gl.TEXTURE_2D);
  7243. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7244. }
  7245. this.bindUnboundFramebuffer(null);
  7246. };
  7247. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7248. if (texture.generateMipMaps) {
  7249. var gl = this._gl;
  7250. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7251. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7252. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7253. }
  7254. };
  7255. Engine.prototype.flushFramebuffer = function () {
  7256. this._gl.flush();
  7257. };
  7258. Engine.prototype.restoreDefaultFramebuffer = function () {
  7259. this._currentRenderTarget = null;
  7260. this.bindUnboundFramebuffer(null);
  7261. this.setViewport(this._cachedViewport);
  7262. this.wipeCaches();
  7263. };
  7264. // VBOs
  7265. Engine.prototype._resetVertexBufferBinding = function () {
  7266. this.bindArrayBuffer(null);
  7267. this._cachedVertexBuffers = null;
  7268. };
  7269. Engine.prototype.createVertexBuffer = function (vertices) {
  7270. var vbo = this._gl.createBuffer();
  7271. this.bindArrayBuffer(vbo);
  7272. if (vertices instanceof Float32Array) {
  7273. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7274. }
  7275. else {
  7276. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7277. }
  7278. this._resetVertexBufferBinding();
  7279. vbo.references = 1;
  7280. return vbo;
  7281. };
  7282. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7283. var vbo = this._gl.createBuffer();
  7284. this.bindArrayBuffer(vbo);
  7285. if (vertices instanceof Float32Array) {
  7286. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7287. }
  7288. else {
  7289. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7290. }
  7291. this._resetVertexBufferBinding();
  7292. vbo.references = 1;
  7293. return vbo;
  7294. };
  7295. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7296. this.bindArrayBuffer(vertexBuffer);
  7297. if (offset === undefined) {
  7298. offset = 0;
  7299. }
  7300. if (count === undefined) {
  7301. if (vertices instanceof Float32Array) {
  7302. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7303. }
  7304. else {
  7305. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7306. }
  7307. }
  7308. else {
  7309. if (vertices instanceof Float32Array) {
  7310. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7311. }
  7312. else {
  7313. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7314. }
  7315. }
  7316. this._resetVertexBufferBinding();
  7317. };
  7318. Engine.prototype._resetIndexBufferBinding = function () {
  7319. this.bindIndexBuffer(null);
  7320. this._cachedIndexBuffer = null;
  7321. };
  7322. Engine.prototype.createIndexBuffer = function (indices) {
  7323. var vbo = this._gl.createBuffer();
  7324. this.bindIndexBuffer(vbo);
  7325. // Check for 32 bits indices
  7326. var arrayBuffer;
  7327. var need32Bits = false;
  7328. if (this._caps.uintIndices) {
  7329. for (var index = 0; index < indices.length; index++) {
  7330. if (indices[index] > 65535) {
  7331. need32Bits = true;
  7332. break;
  7333. }
  7334. }
  7335. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7336. }
  7337. else {
  7338. arrayBuffer = new Uint16Array(indices);
  7339. }
  7340. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7341. this._resetIndexBufferBinding();
  7342. vbo.references = 1;
  7343. vbo.is32Bits = need32Bits;
  7344. return vbo;
  7345. };
  7346. Engine.prototype.bindArrayBuffer = function (buffer) {
  7347. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7348. };
  7349. Engine.prototype.bindIndexBuffer = function (buffer) {
  7350. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7351. };
  7352. Engine.prototype.bindBuffer = function (buffer, target) {
  7353. if (this._currentBoundBuffer[target] !== buffer) {
  7354. this._gl.bindBuffer(target, buffer);
  7355. this._currentBoundBuffer[target] = buffer;
  7356. }
  7357. };
  7358. Engine.prototype.updateArrayBuffer = function (data) {
  7359. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7360. };
  7361. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7362. var pointer = this._currentBufferPointers[indx];
  7363. var changed = false;
  7364. if (!pointer) {
  7365. changed = true;
  7366. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7367. }
  7368. else {
  7369. if (pointer.buffer !== buffer) {
  7370. pointer.buffer = buffer;
  7371. changed = true;
  7372. }
  7373. if (pointer.size !== size) {
  7374. pointer.size = size;
  7375. changed = true;
  7376. }
  7377. if (pointer.type !== type) {
  7378. pointer.type = type;
  7379. changed = true;
  7380. }
  7381. if (pointer.normalized !== normalized) {
  7382. pointer.normalized = normalized;
  7383. changed = true;
  7384. }
  7385. if (pointer.stride !== stride) {
  7386. pointer.stride = stride;
  7387. changed = true;
  7388. }
  7389. if (pointer.offset !== offset) {
  7390. pointer.offset = offset;
  7391. changed = true;
  7392. }
  7393. }
  7394. if (changed) {
  7395. this.bindArrayBuffer(buffer);
  7396. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7397. }
  7398. };
  7399. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7400. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7401. this._cachedVertexBuffers = vertexBuffer;
  7402. this._cachedEffectForVertexBuffers = effect;
  7403. var attributesCount = effect.getAttributesCount();
  7404. var offset = 0;
  7405. for (var index = 0; index < attributesCount; index++) {
  7406. if (index < vertexDeclaration.length) {
  7407. var order = effect.getAttributeLocation(index);
  7408. if (order >= 0) {
  7409. if (!this._vertexAttribArraysEnabled[order]) {
  7410. this._gl.enableVertexAttribArray(order);
  7411. this._vertexAttribArraysEnabled[order] = true;
  7412. }
  7413. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7414. }
  7415. offset += vertexDeclaration[index] * 4;
  7416. }
  7417. else {
  7418. //disable effect attributes that have no data
  7419. var order = effect.getAttributeLocation(index);
  7420. if (this._vertexAttribArraysEnabled[order]) {
  7421. this._gl.disableVertexAttribArray(order);
  7422. this._vertexAttribArraysEnabled[order] = false;
  7423. }
  7424. }
  7425. }
  7426. }
  7427. if (this._cachedIndexBuffer !== indexBuffer) {
  7428. this._cachedIndexBuffer = indexBuffer;
  7429. this.bindIndexBuffer(indexBuffer);
  7430. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7431. }
  7432. };
  7433. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7434. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7435. this._cachedVertexBuffers = vertexBuffers;
  7436. this._cachedEffectForVertexBuffers = effect;
  7437. var attributes = effect.getAttributesNames();
  7438. for (var index = 0; index < attributes.length; index++) {
  7439. var order = effect.getAttributeLocation(index);
  7440. if (order >= 0) {
  7441. var vertexBuffer = vertexBuffers[attributes[index]];
  7442. if (!vertexBuffer) {
  7443. if (this._vertexAttribArraysEnabled[order]) {
  7444. this._gl.disableVertexAttribArray(order);
  7445. this._vertexAttribArraysEnabled[order] = false;
  7446. }
  7447. continue;
  7448. }
  7449. if (!this._vertexAttribArraysEnabled[order]) {
  7450. this._gl.enableVertexAttribArray(order);
  7451. this._vertexAttribArraysEnabled[order] = true;
  7452. }
  7453. var buffer = vertexBuffer.getBuffer();
  7454. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7455. if (vertexBuffer.getIsInstanced()) {
  7456. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7457. this._currentInstanceLocations.push(order);
  7458. this._currentInstanceBuffers.push(buffer);
  7459. }
  7460. }
  7461. }
  7462. }
  7463. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7464. this._cachedIndexBuffer = indexBuffer;
  7465. this.bindIndexBuffer(indexBuffer);
  7466. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7467. }
  7468. };
  7469. Engine.prototype.unbindInstanceAttributes = function () {
  7470. var boundBuffer;
  7471. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7472. var instancesBuffer = this._currentInstanceBuffers[i];
  7473. if (boundBuffer != instancesBuffer) {
  7474. boundBuffer = instancesBuffer;
  7475. this.bindArrayBuffer(instancesBuffer);
  7476. }
  7477. var offsetLocation = this._currentInstanceLocations[i];
  7478. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7479. }
  7480. this._currentInstanceBuffers.length = 0;
  7481. this._currentInstanceLocations.length = 0;
  7482. };
  7483. Engine.prototype._releaseBuffer = function (buffer) {
  7484. buffer.references--;
  7485. if (buffer.references === 0) {
  7486. this._gl.deleteBuffer(buffer);
  7487. return true;
  7488. }
  7489. return false;
  7490. };
  7491. Engine.prototype.createInstancesBuffer = function (capacity) {
  7492. var buffer = this._gl.createBuffer();
  7493. buffer.capacity = capacity;
  7494. this.bindArrayBuffer(buffer);
  7495. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7496. return buffer;
  7497. };
  7498. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7499. this._gl.deleteBuffer(buffer);
  7500. };
  7501. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7502. this.bindArrayBuffer(instancesBuffer);
  7503. if (data) {
  7504. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7505. }
  7506. if (offsetLocations[0].index !== undefined) {
  7507. var stride = 0;
  7508. for (var i = 0; i < offsetLocations.length; i++) {
  7509. var ai = offsetLocations[i];
  7510. stride += ai.attributeSize * 4;
  7511. }
  7512. for (var i = 0; i < offsetLocations.length; i++) {
  7513. var ai = offsetLocations[i];
  7514. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7515. this._gl.enableVertexAttribArray(ai.index);
  7516. this._vertexAttribArraysEnabled[ai.index] = true;
  7517. }
  7518. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7519. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7520. this._currentInstanceLocations.push(ai.index);
  7521. this._currentInstanceBuffers.push(instancesBuffer);
  7522. }
  7523. }
  7524. else {
  7525. for (var index = 0; index < 4; index++) {
  7526. var offsetLocation = offsetLocations[index];
  7527. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7528. this._gl.enableVertexAttribArray(offsetLocation);
  7529. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7530. }
  7531. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7532. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7533. this._currentInstanceLocations.push(offsetLocation);
  7534. this._currentInstanceBuffers.push(instancesBuffer);
  7535. }
  7536. }
  7537. };
  7538. Engine.prototype.applyStates = function () {
  7539. this._depthCullingState.apply(this._gl);
  7540. this._stencilState.apply(this._gl);
  7541. this._alphaState.apply(this._gl);
  7542. };
  7543. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7544. // Apply states
  7545. this.applyStates();
  7546. this._drawCalls.addCount(1, false);
  7547. // Render
  7548. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7549. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7550. if (instancesCount) {
  7551. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7552. return;
  7553. }
  7554. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7555. };
  7556. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7557. // Apply states
  7558. this.applyStates();
  7559. this._drawCalls.addCount(1, false);
  7560. if (instancesCount) {
  7561. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7562. return;
  7563. }
  7564. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7565. };
  7566. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7567. // Apply states
  7568. this.applyStates();
  7569. this._drawCalls.addCount(1, false);
  7570. if (instancesCount) {
  7571. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7572. return;
  7573. }
  7574. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7575. };
  7576. // Shaders
  7577. Engine.prototype._releaseEffect = function (effect) {
  7578. if (this._compiledEffects[effect._key]) {
  7579. delete this._compiledEffects[effect._key];
  7580. if (effect.getProgram()) {
  7581. this._gl.deleteProgram(effect.getProgram());
  7582. }
  7583. }
  7584. };
  7585. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7586. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7587. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7588. var name = vertex + "+" + fragment + "@" + defines;
  7589. if (this._compiledEffects[name]) {
  7590. return this._compiledEffects[name];
  7591. }
  7592. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7593. effect._key = name;
  7594. this._compiledEffects[name] = effect;
  7595. return effect;
  7596. };
  7597. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7598. if (uniformsNames === void 0) { uniformsNames = []; }
  7599. if (samplers === void 0) { samplers = []; }
  7600. if (defines === void 0) { defines = ""; }
  7601. return this.createEffect({
  7602. vertex: "particles",
  7603. fragmentElement: fragmentName
  7604. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7605. };
  7606. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7607. context = context || this._gl;
  7608. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7609. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7610. var shaderProgram = context.createProgram();
  7611. context.attachShader(shaderProgram, vertexShader);
  7612. context.attachShader(shaderProgram, fragmentShader);
  7613. context.linkProgram(shaderProgram);
  7614. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7615. if (!linked) {
  7616. var error = context.getProgramInfoLog(shaderProgram);
  7617. if (error) {
  7618. throw new Error(error);
  7619. }
  7620. }
  7621. context.deleteShader(vertexShader);
  7622. context.deleteShader(fragmentShader);
  7623. return shaderProgram;
  7624. };
  7625. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7626. var results = [];
  7627. for (var index = 0; index < uniformsNames.length; index++) {
  7628. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7629. }
  7630. return results;
  7631. };
  7632. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7633. var results = [];
  7634. for (var index = 0; index < attributesNames.length; index++) {
  7635. try {
  7636. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7637. }
  7638. catch (e) {
  7639. results.push(-1);
  7640. }
  7641. }
  7642. return results;
  7643. };
  7644. Engine.prototype.enableEffect = function (effect) {
  7645. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7646. // if (effect && effect.onBind) {
  7647. // effect.onBind(effect);
  7648. // }
  7649. // return;
  7650. //}
  7651. // Use program
  7652. this.setProgram(effect.getProgram());
  7653. this._currentEffect = effect;
  7654. if (effect.onBind) {
  7655. effect.onBind(effect);
  7656. }
  7657. };
  7658. Engine.prototype.setIntArray = function (uniform, array) {
  7659. if (!uniform)
  7660. return;
  7661. this._gl.uniform1iv(uniform, array);
  7662. };
  7663. Engine.prototype.setIntArray2 = function (uniform, array) {
  7664. if (!uniform || array.length % 2 !== 0)
  7665. return;
  7666. this._gl.uniform2iv(uniform, array);
  7667. };
  7668. Engine.prototype.setIntArray3 = function (uniform, array) {
  7669. if (!uniform || array.length % 3 !== 0)
  7670. return;
  7671. this._gl.uniform3iv(uniform, array);
  7672. };
  7673. Engine.prototype.setIntArray4 = function (uniform, array) {
  7674. if (!uniform || array.length % 4 !== 0)
  7675. return;
  7676. this._gl.uniform4iv(uniform, array);
  7677. };
  7678. Engine.prototype.setFloatArray = function (uniform, array) {
  7679. if (!uniform)
  7680. return;
  7681. this._gl.uniform1fv(uniform, array);
  7682. };
  7683. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7684. if (!uniform || array.length % 2 !== 0)
  7685. return;
  7686. this._gl.uniform2fv(uniform, array);
  7687. };
  7688. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7689. if (!uniform || array.length % 3 !== 0)
  7690. return;
  7691. this._gl.uniform3fv(uniform, array);
  7692. };
  7693. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7694. if (!uniform || array.length % 4 !== 0)
  7695. return;
  7696. this._gl.uniform4fv(uniform, array);
  7697. };
  7698. Engine.prototype.setArray = function (uniform, array) {
  7699. if (!uniform)
  7700. return;
  7701. this._gl.uniform1fv(uniform, array);
  7702. };
  7703. Engine.prototype.setArray2 = function (uniform, array) {
  7704. if (!uniform || array.length % 2 !== 0)
  7705. return;
  7706. this._gl.uniform2fv(uniform, array);
  7707. };
  7708. Engine.prototype.setArray3 = function (uniform, array) {
  7709. if (!uniform || array.length % 3 !== 0)
  7710. return;
  7711. this._gl.uniform3fv(uniform, array);
  7712. };
  7713. Engine.prototype.setArray4 = function (uniform, array) {
  7714. if (!uniform || array.length % 4 !== 0)
  7715. return;
  7716. this._gl.uniform4fv(uniform, array);
  7717. };
  7718. Engine.prototype.setMatrices = function (uniform, matrices) {
  7719. if (!uniform)
  7720. return;
  7721. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7722. };
  7723. Engine.prototype.setMatrix = function (uniform, matrix) {
  7724. if (!uniform)
  7725. return;
  7726. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7727. };
  7728. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7729. if (!uniform)
  7730. return;
  7731. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7732. };
  7733. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7734. if (!uniform)
  7735. return;
  7736. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7737. };
  7738. Engine.prototype.setFloat = function (uniform, value) {
  7739. if (!uniform)
  7740. return;
  7741. this._gl.uniform1f(uniform, value);
  7742. };
  7743. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7744. if (!uniform)
  7745. return;
  7746. this._gl.uniform2f(uniform, x, y);
  7747. };
  7748. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7749. if (!uniform)
  7750. return;
  7751. this._gl.uniform3f(uniform, x, y, z);
  7752. };
  7753. Engine.prototype.setBool = function (uniform, bool) {
  7754. if (!uniform)
  7755. return;
  7756. this._gl.uniform1i(uniform, bool);
  7757. };
  7758. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7759. if (!uniform)
  7760. return;
  7761. this._gl.uniform4f(uniform, x, y, z, w);
  7762. };
  7763. Engine.prototype.setColor3 = function (uniform, color3) {
  7764. if (!uniform)
  7765. return;
  7766. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7767. };
  7768. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7769. if (!uniform)
  7770. return;
  7771. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7772. };
  7773. // States
  7774. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7775. if (zOffset === void 0) { zOffset = 0; }
  7776. if (reverseSide === void 0) { reverseSide = false; }
  7777. // Culling
  7778. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7779. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7780. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7781. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7782. if (culling) {
  7783. this._depthCullingState.cullFace = cullFace;
  7784. this._depthCullingState.cull = true;
  7785. }
  7786. else {
  7787. this._depthCullingState.cull = false;
  7788. }
  7789. }
  7790. // Z offset
  7791. this._depthCullingState.zOffset = zOffset;
  7792. };
  7793. Engine.prototype.setDepthBuffer = function (enable) {
  7794. this._depthCullingState.depthTest = enable;
  7795. };
  7796. Engine.prototype.getDepthWrite = function () {
  7797. return this._depthCullingState.depthMask;
  7798. };
  7799. Engine.prototype.setDepthWrite = function (enable) {
  7800. this._depthCullingState.depthMask = enable;
  7801. };
  7802. Engine.prototype.setColorWrite = function (enable) {
  7803. this._gl.colorMask(enable, enable, enable, enable);
  7804. };
  7805. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7806. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7807. if (this._alphaMode === mode) {
  7808. return;
  7809. }
  7810. switch (mode) {
  7811. case Engine.ALPHA_DISABLE:
  7812. this._alphaState.alphaBlend = false;
  7813. break;
  7814. case Engine.ALPHA_COMBINE:
  7815. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7816. this._alphaState.alphaBlend = true;
  7817. break;
  7818. case Engine.ALPHA_ONEONE:
  7819. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7820. this._alphaState.alphaBlend = true;
  7821. break;
  7822. case Engine.ALPHA_ADD:
  7823. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7824. this._alphaState.alphaBlend = true;
  7825. break;
  7826. case Engine.ALPHA_SUBTRACT:
  7827. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7828. this._alphaState.alphaBlend = true;
  7829. break;
  7830. case Engine.ALPHA_MULTIPLY:
  7831. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7832. this._alphaState.alphaBlend = true;
  7833. break;
  7834. case Engine.ALPHA_MAXIMIZED:
  7835. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7836. this._alphaState.alphaBlend = true;
  7837. break;
  7838. }
  7839. if (!noDepthWriteChange) {
  7840. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7841. }
  7842. this._alphaMode = mode;
  7843. };
  7844. Engine.prototype.getAlphaMode = function () {
  7845. return this._alphaMode;
  7846. };
  7847. Engine.prototype.setAlphaTesting = function (enable) {
  7848. this._alphaTest = enable;
  7849. };
  7850. Engine.prototype.getAlphaTesting = function () {
  7851. return this._alphaTest;
  7852. };
  7853. // Textures
  7854. Engine.prototype.wipeCaches = function () {
  7855. this.resetTextureCache();
  7856. this._currentEffect = null;
  7857. this._stencilState.reset();
  7858. this._depthCullingState.reset();
  7859. this.setDepthFunctionToLessOrEqual();
  7860. this._alphaState.reset();
  7861. this._cachedVertexBuffers = null;
  7862. this._cachedIndexBuffer = null;
  7863. this._cachedEffectForVertexBuffers = null;
  7864. };
  7865. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7866. var gl = this._gl;
  7867. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7868. var magFilter = gl.NEAREST;
  7869. var minFilter = gl.NEAREST;
  7870. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7871. magFilter = gl.LINEAR;
  7872. minFilter = gl.LINEAR;
  7873. }
  7874. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7875. magFilter = gl.LINEAR;
  7876. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7877. }
  7878. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7879. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7880. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7881. texture.samplingMode = samplingMode;
  7882. };
  7883. Engine.prototype.createTexture = function (urlOrList, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7884. var _this = this;
  7885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7886. if (onLoad === void 0) { onLoad = null; }
  7887. if (onError === void 0) { onError = null; }
  7888. if (buffer === void 0) { buffer = null; }
  7889. var texture = this._gl.createTexture();
  7890. var url = ((urlOrList.constructor === Array) ? urlOrList[0] : urlOrList);
  7891. var extension;
  7892. var fromData = false;
  7893. if (url.substr(0, 5) === "data:") {
  7894. fromData = true;
  7895. }
  7896. if (!fromData)
  7897. extension = url.substr(url.length - 4, 4).toLowerCase();
  7898. else {
  7899. var oldUrl = url;
  7900. fromData = oldUrl.split(':');
  7901. url = oldUrl;
  7902. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7903. }
  7904. var isDDS = (extension === ".dds");
  7905. var isTGA = (extension === ".tga");
  7906. scene._addPendingData(texture);
  7907. texture.url = url;
  7908. texture.noMipmap = noMipmap;
  7909. texture.references = 1;
  7910. texture.samplingMode = samplingMode;
  7911. texture.onLoadedCallbacks = [onLoad];
  7912. this._loadedTexturesCache.push(texture);
  7913. var onerror = function () {
  7914. scene._removePendingData(texture);
  7915. if (onError) {
  7916. onError();
  7917. }
  7918. };
  7919. var callback;
  7920. if (isTGA) {
  7921. callback = function (arrayBuffer) {
  7922. var data = new Uint8Array(arrayBuffer);
  7923. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7924. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7925. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7926. }, samplingMode);
  7927. };
  7928. if (!(fromData instanceof Array))
  7929. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7930. callback(arrayBuffer);
  7931. }, null, scene.database, true, onerror);
  7932. else
  7933. callback(buffer);
  7934. }
  7935. else if (isDDS) {
  7936. if (!this.getCaps().s3tc) {
  7937. if (urlOrList instanceof Array) {
  7938. var newList = urlOrList.slice(1);
  7939. if (newList.length > 0) {
  7940. return this.createTexture(newList, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer);
  7941. }
  7942. }
  7943. onerror();
  7944. return null;
  7945. }
  7946. callback = function (data) {
  7947. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7948. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7949. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7950. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7951. }, samplingMode);
  7952. };
  7953. if (!(fromData instanceof Array))
  7954. BABYLON.Tools.LoadFile(url, function (data) {
  7955. callback(data);
  7956. }, null, scene.database, true, onerror);
  7957. else
  7958. callback(buffer);
  7959. }
  7960. else {
  7961. var onload = function (img) {
  7962. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7963. var isPot = (img.width === potWidth && img.height === potHeight);
  7964. if (!isPot) {
  7965. _this._prepareWorkingCanvas();
  7966. _this._workingCanvas.width = potWidth;
  7967. _this._workingCanvas.height = potHeight;
  7968. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7969. _this._workingContext.imageSmoothingEnabled = false;
  7970. _this._workingContext.mozImageSmoothingEnabled = false;
  7971. _this._workingContext.oImageSmoothingEnabled = false;
  7972. _this._workingContext.webkitImageSmoothingEnabled = false;
  7973. _this._workingContext.msImageSmoothingEnabled = false;
  7974. }
  7975. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7976. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7977. _this._workingContext.imageSmoothingEnabled = true;
  7978. _this._workingContext.mozImageSmoothingEnabled = true;
  7979. _this._workingContext.oImageSmoothingEnabled = true;
  7980. _this._workingContext.webkitImageSmoothingEnabled = true;
  7981. _this._workingContext.msImageSmoothingEnabled = true;
  7982. }
  7983. }
  7984. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7985. }, samplingMode);
  7986. };
  7987. if (!(fromData instanceof Array))
  7988. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7989. else
  7990. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7991. }
  7992. return texture;
  7993. };
  7994. Engine.prototype._getInternalFormat = function (format) {
  7995. var internalFormat = this._gl.RGBA;
  7996. switch (format) {
  7997. case Engine.TEXTUREFORMAT_ALPHA:
  7998. internalFormat = this._gl.ALPHA;
  7999. break;
  8000. case Engine.TEXTUREFORMAT_LUMINANCE:
  8001. internalFormat = this._gl.LUMINANCE;
  8002. break;
  8003. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8004. internalFormat = this._gl.LUMINANCE_ALPHA;
  8005. break;
  8006. case Engine.TEXTUREFORMAT_RGB:
  8007. internalFormat = this._gl.RGB;
  8008. break;
  8009. case Engine.TEXTUREFORMAT_RGBA:
  8010. internalFormat = this._gl.RGBA;
  8011. break;
  8012. }
  8013. return internalFormat;
  8014. };
  8015. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8016. if (compression === void 0) { compression = null; }
  8017. var internalFormat = this._getInternalFormat(format);
  8018. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8019. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8020. if (texture._width % 4 !== 0) {
  8021. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8022. }
  8023. if (compression) {
  8024. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8025. }
  8026. else {
  8027. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8028. }
  8029. if (texture.generateMipMaps) {
  8030. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8031. }
  8032. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8033. this.resetTextureCache();
  8034. texture.isReady = true;
  8035. };
  8036. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8037. if (compression === void 0) { compression = null; }
  8038. var texture = this._gl.createTexture();
  8039. texture._baseWidth = width;
  8040. texture._baseHeight = height;
  8041. texture._width = width;
  8042. texture._height = height;
  8043. texture.references = 1;
  8044. this.updateRawTexture(texture, data, format, invertY, compression);
  8045. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8046. // Filters
  8047. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8048. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8049. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8050. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8051. texture.samplingMode = samplingMode;
  8052. this._loadedTexturesCache.push(texture);
  8053. return texture;
  8054. };
  8055. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8056. var texture = this._gl.createTexture();
  8057. texture._baseWidth = width;
  8058. texture._baseHeight = height;
  8059. if (generateMipMaps) {
  8060. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8061. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8062. }
  8063. this.resetTextureCache();
  8064. texture._width = width;
  8065. texture._height = height;
  8066. texture.isReady = false;
  8067. texture.generateMipMaps = generateMipMaps;
  8068. texture.references = 1;
  8069. texture.samplingMode = samplingMode;
  8070. this.updateTextureSamplingMode(samplingMode, texture);
  8071. this._loadedTexturesCache.push(texture);
  8072. return texture;
  8073. };
  8074. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8075. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8076. if (texture.isCube) {
  8077. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8078. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8079. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8080. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8081. }
  8082. else {
  8083. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8084. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8085. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8086. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8087. }
  8088. };
  8089. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8090. if (premulAlpha === void 0) { premulAlpha = false; }
  8091. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8092. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8093. if (premulAlpha) {
  8094. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8095. }
  8096. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8097. if (texture.generateMipMaps) {
  8098. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8099. }
  8100. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8101. if (premulAlpha) {
  8102. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8103. }
  8104. this.resetTextureCache();
  8105. texture.isReady = true;
  8106. };
  8107. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8108. if (texture._isDisabled) {
  8109. return;
  8110. }
  8111. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8112. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8113. try {
  8114. // Testing video texture support
  8115. if (this._videoTextureSupported === undefined) {
  8116. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8117. if (this._gl.getError() !== 0) {
  8118. this._videoTextureSupported = false;
  8119. }
  8120. else {
  8121. this._videoTextureSupported = true;
  8122. }
  8123. }
  8124. // Copy video through the current working canvas if video texture is not supported
  8125. if (!this._videoTextureSupported) {
  8126. if (!texture._workingCanvas) {
  8127. texture._workingCanvas = document.createElement("canvas");
  8128. texture._workingContext = texture._workingCanvas.getContext("2d");
  8129. texture._workingCanvas.width = texture._width;
  8130. texture._workingCanvas.height = texture._height;
  8131. }
  8132. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8133. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8134. }
  8135. else {
  8136. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8137. }
  8138. if (texture.generateMipMaps) {
  8139. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8140. }
  8141. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8142. this.resetTextureCache();
  8143. texture.isReady = true;
  8144. }
  8145. catch (ex) {
  8146. // Something unexpected
  8147. // Let's disable the texture
  8148. texture._isDisabled = true;
  8149. }
  8150. };
  8151. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8152. // old version had a "generateMipMaps" arg instead of options.
  8153. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8154. // in the same way, generateDepthBuffer is defaulted to true
  8155. var generateMipMaps = false;
  8156. var generateDepthBuffer = true;
  8157. var generateStencilBuffer = false;
  8158. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8159. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8160. if (options !== undefined) {
  8161. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8162. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8163. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8164. type = options.type === undefined ? type : options.type;
  8165. if (options.samplingMode !== undefined) {
  8166. samplingMode = options.samplingMode;
  8167. }
  8168. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8169. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8170. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8171. }
  8172. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8173. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8174. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8175. }
  8176. }
  8177. var gl = this._gl;
  8178. var texture = gl.createTexture();
  8179. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8180. var width = size.width || size;
  8181. var height = size.height || size;
  8182. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8183. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8184. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8185. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8186. }
  8187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8191. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8192. var depthStencilBuffer;
  8193. // Create the depth/stencil buffer
  8194. if (generateStencilBuffer) {
  8195. depthStencilBuffer = gl.createRenderbuffer();
  8196. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8197. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8198. }
  8199. else if (generateDepthBuffer) {
  8200. depthStencilBuffer = gl.createRenderbuffer();
  8201. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8202. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8203. }
  8204. // Create the framebuffer
  8205. var framebuffer = gl.createFramebuffer();
  8206. this.bindUnboundFramebuffer(framebuffer);
  8207. // Manage attachments
  8208. if (generateStencilBuffer) {
  8209. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8210. }
  8211. else if (generateDepthBuffer) {
  8212. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8213. }
  8214. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8215. if (generateMipMaps) {
  8216. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8217. }
  8218. // Unbind
  8219. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8220. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8221. this.bindUnboundFramebuffer(null);
  8222. texture._framebuffer = framebuffer;
  8223. if (generateDepthBuffer) {
  8224. texture._depthBuffer = depthStencilBuffer;
  8225. }
  8226. texture._baseWidth = width;
  8227. texture._baseHeight = height;
  8228. texture._width = width;
  8229. texture._height = height;
  8230. texture.isReady = true;
  8231. texture.generateMipMaps = generateMipMaps;
  8232. texture.references = 1;
  8233. texture.samplingMode = samplingMode;
  8234. texture.type = type;
  8235. this.resetTextureCache();
  8236. this._loadedTexturesCache.push(texture);
  8237. return texture;
  8238. };
  8239. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8240. var gl = this._gl;
  8241. var texture = gl.createTexture();
  8242. var generateMipMaps = true;
  8243. var generateDepthBuffer = true;
  8244. var generateStencilBuffer = false;
  8245. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8246. if (options !== undefined) {
  8247. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8248. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8249. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8250. if (options.samplingMode !== undefined) {
  8251. samplingMode = options.samplingMode;
  8252. }
  8253. }
  8254. texture.isCube = true;
  8255. texture.references = 1;
  8256. texture.generateMipMaps = generateMipMaps;
  8257. texture.references = 1;
  8258. texture.samplingMode = samplingMode;
  8259. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8260. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8261. for (var face = 0; face < 6; face++) {
  8262. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8263. }
  8264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8268. // Create the depth buffer
  8269. var depthStencilBuffer;
  8270. // Create the depth/stencil buffer
  8271. if (generateStencilBuffer) {
  8272. depthStencilBuffer = gl.createRenderbuffer();
  8273. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8274. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8275. }
  8276. else if (generateDepthBuffer) {
  8277. depthStencilBuffer = gl.createRenderbuffer();
  8278. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8279. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8280. }
  8281. // Create the framebuffer
  8282. var framebuffer = gl.createFramebuffer();
  8283. this.bindUnboundFramebuffer(framebuffer);
  8284. // Manage attachments
  8285. if (generateStencilBuffer) {
  8286. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8287. }
  8288. else if (generateDepthBuffer) {
  8289. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8290. }
  8291. // Mipmaps
  8292. if (texture.generateMipMaps) {
  8293. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8294. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8295. }
  8296. // Unbind
  8297. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8298. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8299. this.bindUnboundFramebuffer(null);
  8300. texture._framebuffer = framebuffer;
  8301. if (generateDepthBuffer) {
  8302. texture._depthBuffer = depthStencilBuffer;
  8303. }
  8304. texture._width = size;
  8305. texture._height = size;
  8306. texture.isReady = true;
  8307. this.resetTextureCache();
  8308. this._loadedTexturesCache.push(texture);
  8309. return texture;
  8310. };
  8311. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8312. var _this = this;
  8313. if (onLoad === void 0) { onLoad = null; }
  8314. if (onError === void 0) { onError = null; }
  8315. var gl = this._gl;
  8316. var texture = gl.createTexture();
  8317. texture.isCube = true;
  8318. texture.url = rootUrl;
  8319. texture.references = 1;
  8320. texture.onLoadedCallbacks = [];
  8321. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8322. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8323. if (isDDS) {
  8324. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8325. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8326. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8327. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8328. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8329. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8330. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8331. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8332. }
  8333. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8334. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8335. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8336. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8337. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8338. _this.resetTextureCache();
  8339. texture._width = info.width;
  8340. texture._height = info.height;
  8341. texture.isReady = true;
  8342. }, null, null, true, onError);
  8343. }
  8344. else {
  8345. cascadeLoad(rootUrl, scene, function (imgs) {
  8346. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8347. var height = width;
  8348. _this._prepareWorkingCanvas();
  8349. _this._workingCanvas.width = width;
  8350. _this._workingCanvas.height = height;
  8351. var faces = [
  8352. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8353. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8354. ];
  8355. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8356. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8357. for (var index = 0; index < faces.length; index++) {
  8358. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8359. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8360. }
  8361. if (!noMipmap) {
  8362. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8363. }
  8364. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8365. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8368. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8369. _this.resetTextureCache();
  8370. texture._width = width;
  8371. texture._height = height;
  8372. texture.isReady = true;
  8373. texture.onLoadedCallbacks.forEach(function (callback) {
  8374. callback();
  8375. });
  8376. if (onLoad) {
  8377. onLoad();
  8378. }
  8379. }, files, onError);
  8380. }
  8381. this._loadedTexturesCache.push(texture);
  8382. return texture;
  8383. };
  8384. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8385. texture._width = width;
  8386. texture._height = height;
  8387. texture._size = width * height;
  8388. texture._baseWidth = width;
  8389. texture._baseHeight = height;
  8390. };
  8391. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8392. var _this = this;
  8393. var gl = this._gl;
  8394. var texture = gl.createTexture();
  8395. scene._addPendingData(texture);
  8396. texture.isCube = true;
  8397. texture.references = 1;
  8398. texture.url = url;
  8399. var internalFormat = this._getInternalFormat(format);
  8400. var textureType = gl.UNSIGNED_BYTE;
  8401. if (type === Engine.TEXTURETYPE_FLOAT) {
  8402. textureType = gl.FLOAT;
  8403. }
  8404. var width = size;
  8405. var height = width;
  8406. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8407. texture._width = width;
  8408. texture._height = height;
  8409. var onerror = function () {
  8410. scene._removePendingData(texture);
  8411. };
  8412. var internalCallback = function (data) {
  8413. var rgbeDataArrays = callback(data);
  8414. var facesIndex = [
  8415. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8416. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8417. ];
  8418. width = texture._width;
  8419. height = texture._height;
  8420. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8421. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8422. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8423. if (!noMipmap && isPot) {
  8424. if (mipmmapGenerator) {
  8425. var arrayTemp = [];
  8426. // Data are known to be in +X +Y +Z -X -Y -Z
  8427. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8428. arrayTemp.push(rgbeDataArrays[0]); // +X
  8429. arrayTemp.push(rgbeDataArrays[3]); // -X
  8430. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8431. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8432. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8433. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8434. var mipData = mipmmapGenerator(arrayTemp);
  8435. for (var level = 0; level < mipData.length; level++) {
  8436. var mipSize = width >> level;
  8437. // mipData is order in +X -X +Y -Y +Z -Z
  8438. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8439. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8440. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8441. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8442. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8443. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8444. }
  8445. }
  8446. else {
  8447. // Data are known to be in +X +Y +Z -X -Y -Z
  8448. for (var index = 0; index < facesIndex.length; index++) {
  8449. var faceData = rgbeDataArrays[index];
  8450. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8451. }
  8452. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8453. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8454. // By following the webgl standard changes from Revision 7, 2014/11/24
  8455. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8456. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8457. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8458. // Data are known to be in +X +Y +Z -X -Y -Z
  8459. for (var index = 0; index < facesIndex.length; index++) {
  8460. var faceData = rgbeDataArrays[index];
  8461. // Create a new RGBA Face.
  8462. var newFaceData = new Float32Array(width * height * 4);
  8463. for (var x = 0; x < width; x++) {
  8464. for (var y = 0; y < height; y++) {
  8465. var index_1 = (y * width + x) * 3;
  8466. var newIndex = (y * width + x) * 4;
  8467. // Map Old Value to new value.
  8468. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8469. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8470. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8471. // Add fully opaque alpha channel.
  8472. newFaceData[newIndex + 3] = 1;
  8473. }
  8474. }
  8475. // Reupload the face.
  8476. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8477. }
  8478. // Try to generate mipmap again.
  8479. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8480. }
  8481. }
  8482. }
  8483. else {
  8484. noMipmap = true;
  8485. }
  8486. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8489. }
  8490. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8493. }
  8494. else {
  8495. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8496. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8497. }
  8498. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8499. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8500. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8501. texture.isReady = true;
  8502. _this.resetTextureCache();
  8503. scene._removePendingData(texture);
  8504. };
  8505. BABYLON.Tools.LoadFile(url, function (data) {
  8506. internalCallback(data);
  8507. }, onerror, scene.database, true);
  8508. return texture;
  8509. };
  8510. ;
  8511. Engine.prototype._releaseTexture = function (texture) {
  8512. var gl = this._gl;
  8513. if (texture._framebuffer) {
  8514. gl.deleteFramebuffer(texture._framebuffer);
  8515. }
  8516. if (texture._depthBuffer) {
  8517. gl.deleteRenderbuffer(texture._depthBuffer);
  8518. }
  8519. gl.deleteTexture(texture);
  8520. // Unbind channels
  8521. this.unbindAllTextures();
  8522. var index = this._loadedTexturesCache.indexOf(texture);
  8523. if (index !== -1) {
  8524. this._loadedTexturesCache.splice(index, 1);
  8525. }
  8526. };
  8527. Engine.prototype.setProgram = function (program) {
  8528. if (this._currentProgram !== program) {
  8529. this._gl.useProgram(program);
  8530. this._currentProgram = program;
  8531. }
  8532. };
  8533. Engine.prototype.bindSamplers = function (effect) {
  8534. this.setProgram(effect.getProgram());
  8535. var samplers = effect.getSamplers();
  8536. for (var index = 0; index < samplers.length; index++) {
  8537. var uniform = effect.getUniform(samplers[index]);
  8538. this._gl.uniform1i(uniform, index);
  8539. }
  8540. this._currentEffect = null;
  8541. };
  8542. Engine.prototype.activateTexture = function (texture) {
  8543. if (this._activeTexture !== texture) {
  8544. this._gl.activeTexture(texture);
  8545. this._activeTexture = texture;
  8546. }
  8547. };
  8548. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8549. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8550. this._gl.bindTexture(target, texture);
  8551. this._activeTexturesCache[this._activeTexture] = texture;
  8552. }
  8553. };
  8554. Engine.prototype._bindTexture = function (channel, texture) {
  8555. if (channel < 0) {
  8556. return;
  8557. }
  8558. this.activateTexture(this._gl["TEXTURE" + channel]);
  8559. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8560. };
  8561. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8562. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8563. };
  8564. Engine.prototype.unbindAllTextures = function () {
  8565. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8566. this.activateTexture(this._gl["TEXTURE" + channel]);
  8567. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8568. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8569. }
  8570. };
  8571. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8572. if (channel < 0) {
  8573. return;
  8574. }
  8575. this._gl.uniform1i(uniform, channel);
  8576. this._setTexture(channel, texture);
  8577. };
  8578. Engine.prototype._setTexture = function (channel, texture) {
  8579. // Not ready?
  8580. if (!texture || !texture.isReady()) {
  8581. if (this._activeTexturesCache[channel] != null) {
  8582. this.activateTexture(this._gl["TEXTURE" + channel]);
  8583. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8584. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8585. }
  8586. return;
  8587. }
  8588. // Video
  8589. var alreadyActivated = false;
  8590. if (texture instanceof BABYLON.VideoTexture) {
  8591. this.activateTexture(this._gl["TEXTURE" + channel]);
  8592. alreadyActivated = true;
  8593. texture.update();
  8594. }
  8595. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8596. texture.delayLoad();
  8597. return;
  8598. }
  8599. var internalTexture = texture.getInternalTexture();
  8600. if (this._activeTexturesCache[channel] === internalTexture) {
  8601. return;
  8602. }
  8603. if (!alreadyActivated) {
  8604. this.activateTexture(this._gl["TEXTURE" + channel]);
  8605. }
  8606. if (internalTexture.isCube) {
  8607. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8608. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8609. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8610. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8611. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8612. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8613. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8614. }
  8615. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8616. }
  8617. else {
  8618. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8619. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8620. internalTexture._cachedWrapU = texture.wrapU;
  8621. switch (texture.wrapU) {
  8622. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8623. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8624. break;
  8625. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8626. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8627. break;
  8628. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8629. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8630. break;
  8631. }
  8632. }
  8633. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8634. internalTexture._cachedWrapV = texture.wrapV;
  8635. switch (texture.wrapV) {
  8636. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8637. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8638. break;
  8639. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8640. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8641. break;
  8642. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8643. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8644. break;
  8645. }
  8646. }
  8647. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8648. }
  8649. };
  8650. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8651. if (channel < 0) {
  8652. return;
  8653. }
  8654. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8655. this._textureUnits = new Int32Array(textures.length);
  8656. }
  8657. for (var i = 0; i < textures.length; i++) {
  8658. this._textureUnits[i] = channel + i;
  8659. }
  8660. this._gl.uniform1iv(uniform, this._textureUnits);
  8661. for (var index = 0; index < textures.length; index++) {
  8662. this._setTexture(channel + index, textures[index]);
  8663. }
  8664. };
  8665. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8666. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8667. var value = texture.anisotropicFilteringLevel;
  8668. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8669. value = 1;
  8670. }
  8671. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8672. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8673. texture._cachedAnisotropicFilteringLevel = value;
  8674. }
  8675. };
  8676. Engine.prototype.readPixels = function (x, y, width, height) {
  8677. var data = new Uint8Array(height * width * 4);
  8678. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8679. return data;
  8680. };
  8681. /**
  8682. * Add an externaly attached data from its key.
  8683. * This method call will fail and return false, if such key already exists.
  8684. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8685. * @param key the unique key that identifies the data
  8686. * @param data the data object to associate to the key for this Engine instance
  8687. * @return true if no such key were already present and the data was added successfully, false otherwise
  8688. */
  8689. Engine.prototype.addExternalData = function (key, data) {
  8690. return this._externalData.add(key, data);
  8691. };
  8692. /**
  8693. * Get an externaly attached data from its key
  8694. * @param key the unique key that identifies the data
  8695. * @return the associated data, if present (can be null), or undefined if not present
  8696. */
  8697. Engine.prototype.getExternalData = function (key) {
  8698. return this._externalData.get(key);
  8699. };
  8700. /**
  8701. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8702. * @param key the unique key that identifies the data
  8703. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8704. * @return the associated data, can be null if the factory returned null.
  8705. */
  8706. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8707. return this._externalData.getOrAddWithFactory(key, factory);
  8708. };
  8709. /**
  8710. * Remove an externaly attached data from the Engine instance
  8711. * @param key the unique key that identifies the data
  8712. * @return true if the data was successfully removed, false if it doesn't exist
  8713. */
  8714. Engine.prototype.removeExternalData = function (key) {
  8715. return this._externalData.remove(key);
  8716. };
  8717. Engine.prototype.releaseInternalTexture = function (texture) {
  8718. if (!texture) {
  8719. return;
  8720. }
  8721. texture.references--;
  8722. // Final reference ?
  8723. if (texture.references === 0) {
  8724. var texturesCache = this.getLoadedTexturesCache();
  8725. var index = texturesCache.indexOf(texture);
  8726. if (index > -1) {
  8727. texturesCache.splice(index, 1);
  8728. }
  8729. this._releaseTexture(texture);
  8730. }
  8731. };
  8732. Engine.prototype.unbindAllAttributes = function () {
  8733. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8734. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8735. continue;
  8736. }
  8737. this._gl.disableVertexAttribArray(i);
  8738. this._vertexAttribArraysEnabled[i] = false;
  8739. }
  8740. };
  8741. // Dispose
  8742. Engine.prototype.dispose = function () {
  8743. this.hideLoadingUI();
  8744. this.stopRenderLoop();
  8745. // Release scenes
  8746. while (this.scenes.length) {
  8747. this.scenes[0].dispose();
  8748. }
  8749. // Release audio engine
  8750. Engine.audioEngine.dispose();
  8751. // Release effects
  8752. for (var name in this._compiledEffects) {
  8753. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8754. }
  8755. // Unbind
  8756. this.unbindAllAttributes();
  8757. this._gl = null;
  8758. //WebVR
  8759. this.disableVR();
  8760. // Events
  8761. window.removeEventListener("blur", this._onBlur);
  8762. window.removeEventListener("focus", this._onFocus);
  8763. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8764. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8765. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8766. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8767. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8768. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8769. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8770. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8771. };
  8772. // Loading screen
  8773. Engine.prototype.displayLoadingUI = function () {
  8774. this._loadingScreen.displayLoadingUI();
  8775. };
  8776. Engine.prototype.hideLoadingUI = function () {
  8777. this._loadingScreen.hideLoadingUI();
  8778. };
  8779. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8780. get: function () {
  8781. return this._loadingScreen;
  8782. },
  8783. set: function (loadingScreen) {
  8784. this._loadingScreen = loadingScreen;
  8785. },
  8786. enumerable: true,
  8787. configurable: true
  8788. });
  8789. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8790. set: function (text) {
  8791. this._loadingScreen.loadingUIText = text;
  8792. },
  8793. enumerable: true,
  8794. configurable: true
  8795. });
  8796. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8797. set: function (color) {
  8798. this._loadingScreen.loadingUIBackgroundColor = color;
  8799. },
  8800. enumerable: true,
  8801. configurable: true
  8802. });
  8803. Engine.prototype.attachContextLostEvent = function (callback) {
  8804. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8805. };
  8806. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8807. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8808. };
  8809. // FPS
  8810. Engine.prototype.getFps = function () {
  8811. return this.fps;
  8812. };
  8813. Engine.prototype.getDeltaTime = function () {
  8814. return this.deltaTime;
  8815. };
  8816. Engine.prototype._measureFps = function () {
  8817. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8818. var length = this.previousFramesDuration.length;
  8819. if (length >= 2) {
  8820. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8821. }
  8822. if (length >= this.fpsRange) {
  8823. if (length > this.fpsRange) {
  8824. this.previousFramesDuration.splice(0, 1);
  8825. length = this.previousFramesDuration.length;
  8826. }
  8827. var sum = 0;
  8828. for (var id = 0; id < length - 1; id++) {
  8829. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8830. }
  8831. this.fps = 1000.0 / (sum / (length - 1));
  8832. }
  8833. };
  8834. Engine.prototype._canRenderToFloatTexture = function () {
  8835. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8836. };
  8837. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8838. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8839. };
  8840. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8841. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8842. var tempcanvas = document.createElement("canvas");
  8843. tempcanvas.height = 16;
  8844. tempcanvas.width = 16;
  8845. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8846. // extension.
  8847. var ext = gl.getExtension(extension);
  8848. if (!ext) {
  8849. return false;
  8850. }
  8851. // setup GLSL program
  8852. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8853. var fragmentCode = "precision mediump float;\n uniform vec4 u_color;\n uniform sampler2D u_texture;\n\n void main() {\n gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n }";
  8854. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8855. gl.useProgram(program);
  8856. // look up where the vertex data needs to go.
  8857. var positionLocation = gl.getAttribLocation(program, "a_position");
  8858. var colorLoc = gl.getUniformLocation(program, "u_color");
  8859. // provide texture coordinates for the rectangle.
  8860. var positionBuffer = gl.createBuffer();
  8861. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8862. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8863. -1.0, -1.0,
  8864. 1.0, -1.0,
  8865. -1.0, 1.0,
  8866. -1.0, 1.0,
  8867. 1.0, -1.0,
  8868. 1.0, 1.0]), gl.STATIC_DRAW);
  8869. gl.enableVertexAttribArray(positionLocation);
  8870. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8871. var whiteTex = gl.createTexture();
  8872. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8873. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8874. var tex = gl.createTexture();
  8875. gl.bindTexture(gl.TEXTURE_2D, tex);
  8876. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8877. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8878. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8879. var fb = gl.createFramebuffer();
  8880. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8881. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8882. var cleanup = function () {
  8883. gl.deleteProgram(program);
  8884. gl.disableVertexAttribArray(positionLocation);
  8885. gl.deleteBuffer(positionBuffer);
  8886. gl.deleteFramebuffer(fb);
  8887. gl.deleteTexture(whiteTex);
  8888. gl.deleteTexture(tex);
  8889. };
  8890. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8891. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8892. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8893. cleanup();
  8894. return false;
  8895. }
  8896. // Draw the rectangle.
  8897. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8898. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8899. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8900. gl.bindTexture(gl.TEXTURE_2D, tex);
  8901. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8902. gl.clearColor(1, 0, 0, 1);
  8903. gl.clear(gl.COLOR_BUFFER_BIT);
  8904. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8905. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8906. var pixel = new Uint8Array(4);
  8907. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8908. if (pixel[0] !== 0 ||
  8909. pixel[1] < 248 ||
  8910. pixel[2] < 248 ||
  8911. pixel[3] < 254) {
  8912. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8913. cleanup();
  8914. return false;
  8915. }
  8916. // Succesfully rendered to "format" texture.
  8917. cleanup();
  8918. return true;
  8919. };
  8920. // Statics
  8921. Engine.isSupported = function () {
  8922. try {
  8923. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8924. if (navigator.isCocoonJS) {
  8925. return true;
  8926. }
  8927. var tempcanvas = document.createElement("canvas");
  8928. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8929. return gl != null && !!window.WebGLRenderingContext;
  8930. }
  8931. catch (e) {
  8932. return false;
  8933. }
  8934. };
  8935. // Const statics
  8936. Engine._ALPHA_DISABLE = 0;
  8937. Engine._ALPHA_ADD = 1;
  8938. Engine._ALPHA_COMBINE = 2;
  8939. Engine._ALPHA_SUBTRACT = 3;
  8940. Engine._ALPHA_MULTIPLY = 4;
  8941. Engine._ALPHA_MAXIMIZED = 5;
  8942. Engine._ALPHA_ONEONE = 6;
  8943. Engine._DELAYLOADSTATE_NONE = 0;
  8944. Engine._DELAYLOADSTATE_LOADED = 1;
  8945. Engine._DELAYLOADSTATE_LOADING = 2;
  8946. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8947. Engine._TEXTUREFORMAT_ALPHA = 0;
  8948. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8949. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8950. Engine._TEXTUREFORMAT_RGB = 4;
  8951. Engine._TEXTUREFORMAT_RGBA = 5;
  8952. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8953. Engine._TEXTURETYPE_FLOAT = 1;
  8954. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8955. // Depht or Stencil test Constants.
  8956. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  8957. 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.
  8958. 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.
  8959. 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.
  8960. 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.
  8961. 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.
  8962. 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.
  8963. 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.
  8964. // Stencil Actions Constants.
  8965. Engine._KEEP = 0x1E00;
  8966. Engine._REPLACE = 0x1E01;
  8967. Engine._INCR = 0x1E02;
  8968. Engine._DECR = 0x1E03;
  8969. Engine._INVERT = 0x150A;
  8970. Engine._INCR_WRAP = 0x8507;
  8971. Engine._DECR_WRAP = 0x8508;
  8972. // Updatable statics so stick with vars here
  8973. Engine.CollisionsEpsilon = 0.001;
  8974. Engine.CodeRepository = "src/";
  8975. Engine.ShadersRepository = "src/Shaders/";
  8976. return Engine;
  8977. }());
  8978. BABYLON.Engine = Engine;
  8979. })(BABYLON || (BABYLON = {}));
  8980. var BABYLON;
  8981. (function (BABYLON) {
  8982. /**
  8983. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8984. */
  8985. var Node = (function () {
  8986. /**
  8987. * @constructor
  8988. * @param {string} name - the name and id to be given to this node
  8989. * @param {BABYLON.Scene} the scene this node will be added to
  8990. */
  8991. function Node(name, scene) {
  8992. this.state = "";
  8993. this.metadata = null;
  8994. this.animations = new Array();
  8995. this._ranges = {};
  8996. this._childrenFlag = -1;
  8997. this._isEnabled = true;
  8998. this._isReady = true;
  8999. this._currentRenderId = -1;
  9000. this._parentRenderId = -1;
  9001. this.name = name;
  9002. this.id = name;
  9003. this._scene = scene;
  9004. this._initCache();
  9005. }
  9006. Object.defineProperty(Node.prototype, "parent", {
  9007. get: function () {
  9008. return this._parentNode;
  9009. },
  9010. set: function (parent) {
  9011. if (this._parentNode === parent) {
  9012. return;
  9013. }
  9014. if (this._parentNode) {
  9015. var index = this._parentNode._children.indexOf(this);
  9016. if (index !== -1) {
  9017. this._parentNode._children.splice(index, 1);
  9018. }
  9019. }
  9020. this._parentNode = parent;
  9021. if (this._parentNode) {
  9022. if (!this._parentNode._children) {
  9023. this._parentNode._children = new Array();
  9024. }
  9025. this._parentNode._children.push(this);
  9026. }
  9027. },
  9028. enumerable: true,
  9029. configurable: true
  9030. });
  9031. Node.prototype.getScene = function () {
  9032. return this._scene;
  9033. };
  9034. Node.prototype.getEngine = function () {
  9035. return this._scene.getEngine();
  9036. };
  9037. // override it in derived class
  9038. Node.prototype.getWorldMatrix = function () {
  9039. return BABYLON.Matrix.Identity();
  9040. };
  9041. // override it in derived class if you add new variables to the cache
  9042. // and call the parent class method
  9043. Node.prototype._initCache = function () {
  9044. this._cache = {};
  9045. this._cache.parent = undefined;
  9046. };
  9047. Node.prototype.updateCache = function (force) {
  9048. if (!force && this.isSynchronized())
  9049. return;
  9050. this._cache.parent = this.parent;
  9051. this._updateCache();
  9052. };
  9053. // override it in derived class if you add new variables to the cache
  9054. // and call the parent class method if !ignoreParentClass
  9055. Node.prototype._updateCache = function (ignoreParentClass) {
  9056. };
  9057. // override it in derived class if you add new variables to the cache
  9058. Node.prototype._isSynchronized = function () {
  9059. return true;
  9060. };
  9061. Node.prototype._markSyncedWithParent = function () {
  9062. this._parentRenderId = this.parent._currentRenderId;
  9063. };
  9064. Node.prototype.isSynchronizedWithParent = function () {
  9065. if (!this.parent) {
  9066. return true;
  9067. }
  9068. if (this._parentRenderId !== this.parent._currentRenderId) {
  9069. return false;
  9070. }
  9071. return this.parent.isSynchronized();
  9072. };
  9073. Node.prototype.isSynchronized = function (updateCache) {
  9074. var check = this.hasNewParent();
  9075. check = check || !this.isSynchronizedWithParent();
  9076. check = check || !this._isSynchronized();
  9077. if (updateCache)
  9078. this.updateCache(true);
  9079. return !check;
  9080. };
  9081. Node.prototype.hasNewParent = function (update) {
  9082. if (this._cache.parent === this.parent)
  9083. return false;
  9084. if (update)
  9085. this._cache.parent = this.parent;
  9086. return true;
  9087. };
  9088. /**
  9089. * Is this node ready to be used/rendered
  9090. * @return {boolean} is it ready
  9091. */
  9092. Node.prototype.isReady = function () {
  9093. return this._isReady;
  9094. };
  9095. /**
  9096. * Is this node enabled.
  9097. * If the node has a parent and is enabled, the parent will be inspected as well.
  9098. * @return {boolean} whether this node (and its parent) is enabled.
  9099. * @see setEnabled
  9100. */
  9101. Node.prototype.isEnabled = function () {
  9102. if (!this._isEnabled) {
  9103. return false;
  9104. }
  9105. if (this.parent) {
  9106. return this.parent.isEnabled();
  9107. }
  9108. return true;
  9109. };
  9110. /**
  9111. * Set the enabled state of this node.
  9112. * @param {boolean} value - the new enabled state
  9113. * @see isEnabled
  9114. */
  9115. Node.prototype.setEnabled = function (value) {
  9116. this._isEnabled = value;
  9117. };
  9118. /**
  9119. * Is this node a descendant of the given node.
  9120. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9121. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9122. * @see parent
  9123. */
  9124. Node.prototype.isDescendantOf = function (ancestor) {
  9125. if (this.parent) {
  9126. if (this.parent === ancestor) {
  9127. return true;
  9128. }
  9129. return this.parent.isDescendantOf(ancestor);
  9130. }
  9131. return false;
  9132. };
  9133. /**
  9134. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9135. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9136. * @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.
  9137. * @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.
  9138. */
  9139. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9140. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9141. if (!this._children) {
  9142. return;
  9143. }
  9144. for (var index = 0; index < this._children.length; index++) {
  9145. var item = this._children[index];
  9146. if (!predicate || predicate(item)) {
  9147. results.push(item);
  9148. }
  9149. if (!directDescendantsOnly) {
  9150. item._getDescendants(results, false, predicate);
  9151. }
  9152. }
  9153. };
  9154. /**
  9155. * Will return all nodes that have this node as ascendant.
  9156. * @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.
  9157. * @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.
  9158. * @return {BABYLON.Node[]} all children nodes of all types.
  9159. */
  9160. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9161. var results = [];
  9162. this._getDescendants(results, directDescendantsOnly, predicate);
  9163. return results;
  9164. };
  9165. /**
  9166. * @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.
  9167. * @Deprecated, legacy support.
  9168. * use getDecendants instead.
  9169. */
  9170. Node.prototype.getChildren = function (predicate) {
  9171. return this.getDescendants(true, predicate);
  9172. };
  9173. /**
  9174. * Get all child-meshes of this node.
  9175. */
  9176. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9177. var results = [];
  9178. this._getDescendants(results, directDecendantsOnly, function (node) {
  9179. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9180. });
  9181. return results;
  9182. };
  9183. Node.prototype._setReady = function (state) {
  9184. if (state === this._isReady) {
  9185. return;
  9186. }
  9187. if (!state) {
  9188. this._isReady = false;
  9189. return;
  9190. }
  9191. this._isReady = true;
  9192. if (this.onReady) {
  9193. this.onReady(this);
  9194. }
  9195. };
  9196. Node.prototype.getAnimationByName = function (name) {
  9197. for (var i = 0; i < this.animations.length; i++) {
  9198. var animation = this.animations[i];
  9199. if (animation.name === name) {
  9200. return animation;
  9201. }
  9202. }
  9203. return null;
  9204. };
  9205. Node.prototype.createAnimationRange = function (name, from, to) {
  9206. // check name not already in use
  9207. if (!this._ranges[name]) {
  9208. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9209. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9210. if (this.animations[i]) {
  9211. this.animations[i].createRange(name, from, to);
  9212. }
  9213. }
  9214. }
  9215. };
  9216. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9217. if (deleteFrames === void 0) { deleteFrames = true; }
  9218. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9219. if (this.animations[i]) {
  9220. this.animations[i].deleteRange(name, deleteFrames);
  9221. }
  9222. }
  9223. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9224. };
  9225. Node.prototype.getAnimationRange = function (name) {
  9226. return this._ranges[name];
  9227. };
  9228. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9229. var range = this.getAnimationRange(name);
  9230. if (!range) {
  9231. return null;
  9232. }
  9233. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9234. };
  9235. Node.prototype.serializeAnimationRanges = function () {
  9236. var serializationRanges = [];
  9237. for (var name in this._ranges) {
  9238. var range = {};
  9239. range.name = name;
  9240. range.from = this._ranges[name].from;
  9241. range.to = this._ranges[name].to;
  9242. serializationRanges.push(range);
  9243. }
  9244. return serializationRanges;
  9245. };
  9246. Node.prototype.dispose = function () {
  9247. this.parent = null;
  9248. };
  9249. Node.prototype.getDirection = function (localAxis) {
  9250. var result = BABYLON.Vector3.Zero();
  9251. this.getDirectionToRef(localAxis, result);
  9252. return result;
  9253. };
  9254. Node.prototype.getDirectionToRef = function (localAxis, result) {
  9255. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  9256. };
  9257. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9258. if (parsedNode.ranges) {
  9259. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9260. var data = parsedNode.ranges[index];
  9261. node.createAnimationRange(data.name, data.from, data.to);
  9262. }
  9263. }
  9264. };
  9265. __decorate([
  9266. BABYLON.serialize()
  9267. ], Node.prototype, "name", void 0);
  9268. __decorate([
  9269. BABYLON.serialize()
  9270. ], Node.prototype, "id", void 0);
  9271. __decorate([
  9272. BABYLON.serialize()
  9273. ], Node.prototype, "uniqueId", void 0);
  9274. __decorate([
  9275. BABYLON.serialize()
  9276. ], Node.prototype, "state", void 0);
  9277. __decorate([
  9278. BABYLON.serialize()
  9279. ], Node.prototype, "metadata", void 0);
  9280. return Node;
  9281. }());
  9282. BABYLON.Node = Node;
  9283. })(BABYLON || (BABYLON = {}));
  9284. var BABYLON;
  9285. (function (BABYLON) {
  9286. var FilesInput = (function () {
  9287. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9288. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9289. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9290. this._engine = p_engine;
  9291. this._canvas = p_canvas;
  9292. this._currentScene = p_scene;
  9293. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9294. this._progressCallback = p_progressCallback;
  9295. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9296. this._textureLoadingCallback = p_textureLoadingCallback;
  9297. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9298. }
  9299. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9300. var _this = this;
  9301. if (p_elementToMonitor) {
  9302. this._elementToMonitor = p_elementToMonitor;
  9303. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9304. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9305. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9306. }
  9307. };
  9308. FilesInput.prototype.renderFunction = function () {
  9309. if (this._additionnalRenderLoopLogicCallback) {
  9310. this._additionnalRenderLoopLogicCallback();
  9311. }
  9312. if (this._currentScene) {
  9313. if (this._textureLoadingCallback) {
  9314. var remaining = this._currentScene.getWaitingItemsCount();
  9315. if (remaining > 0) {
  9316. this._textureLoadingCallback(remaining);
  9317. }
  9318. }
  9319. this._currentScene.render();
  9320. }
  9321. };
  9322. FilesInput.prototype.drag = function (e) {
  9323. e.stopPropagation();
  9324. e.preventDefault();
  9325. };
  9326. FilesInput.prototype.drop = function (eventDrop) {
  9327. eventDrop.stopPropagation();
  9328. eventDrop.preventDefault();
  9329. this.loadFiles(eventDrop);
  9330. };
  9331. FilesInput.prototype.loadFiles = function (event) {
  9332. if (this._startingProcessingFilesCallback)
  9333. this._startingProcessingFilesCallback();
  9334. // Handling data transfer via drag'n'drop
  9335. if (event && event.dataTransfer && event.dataTransfer.files) {
  9336. this._filesToLoad = event.dataTransfer.files;
  9337. }
  9338. // Handling files from input files
  9339. if (event && event.target && event.target.files) {
  9340. this._filesToLoad = event.target.files;
  9341. }
  9342. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9343. for (var i = 0; i < this._filesToLoad.length; i++) {
  9344. switch (this._filesToLoad[i].type) {
  9345. case "image/jpeg":
  9346. case "image/png":
  9347. case "image/bmp":
  9348. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9349. break;
  9350. case "image/targa":
  9351. case "image/vnd.ms-dds":
  9352. case "audio/wav":
  9353. case "audio/x-wav":
  9354. case "audio/mp3":
  9355. case "audio/mpeg":
  9356. case "audio/mpeg3":
  9357. case "audio/x-mpeg-3":
  9358. case "audio/ogg":
  9359. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9360. break;
  9361. default:
  9362. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9363. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9364. }
  9365. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9366. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9367. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9368. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9369. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9370. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9371. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9372. this._sceneFileToLoad = this._filesToLoad[i];
  9373. }
  9374. break;
  9375. }
  9376. }
  9377. this.reload();
  9378. }
  9379. };
  9380. FilesInput.prototype.reload = function () {
  9381. var _this = this;
  9382. var that = this;
  9383. // If a ".babylon" file has been provided
  9384. if (this._sceneFileToLoad) {
  9385. if (this._currentScene) {
  9386. if (BABYLON.Tools.errorsCount > 0) {
  9387. BABYLON.Tools.ClearLogCache();
  9388. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9389. }
  9390. this._engine.stopRenderLoop();
  9391. this._currentScene.dispose();
  9392. }
  9393. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9394. that._currentScene = newScene;
  9395. // Wait for textures and shaders to be ready
  9396. that._currentScene.executeWhenReady(function () {
  9397. // Attach camera to canvas inputs
  9398. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9399. that._currentScene.createDefaultCameraOrLight();
  9400. }
  9401. that._currentScene.activeCamera.attachControl(that._canvas);
  9402. if (that._sceneLoadedCallback) {
  9403. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9404. }
  9405. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9406. });
  9407. }, function (progress) {
  9408. if (_this._progressCallback) {
  9409. _this._progressCallback(progress);
  9410. }
  9411. });
  9412. }
  9413. else {
  9414. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9415. }
  9416. };
  9417. FilesInput.FilesTextures = new Array();
  9418. FilesInput.FilesToLoad = new Array();
  9419. return FilesInput;
  9420. }());
  9421. BABYLON.FilesInput = FilesInput;
  9422. })(BABYLON || (BABYLON = {}));
  9423. var BABYLON;
  9424. (function (BABYLON) {
  9425. var IntersectionInfo = (function () {
  9426. function IntersectionInfo(bu, bv, distance) {
  9427. this.bu = bu;
  9428. this.bv = bv;
  9429. this.distance = distance;
  9430. this.faceId = 0;
  9431. this.subMeshId = 0;
  9432. }
  9433. return IntersectionInfo;
  9434. }());
  9435. BABYLON.IntersectionInfo = IntersectionInfo;
  9436. var PickingInfo = (function () {
  9437. function PickingInfo() {
  9438. this.hit = false;
  9439. this.distance = 0;
  9440. this.pickedPoint = null;
  9441. this.pickedMesh = null;
  9442. this.bu = 0;
  9443. this.bv = 0;
  9444. this.faceId = -1;
  9445. this.subMeshId = 0;
  9446. this.pickedSprite = null;
  9447. }
  9448. // Methods
  9449. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9450. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9451. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9452. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9453. return null;
  9454. }
  9455. var indices = this.pickedMesh.getIndices();
  9456. var result;
  9457. if (useVerticesNormals) {
  9458. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9459. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9460. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9461. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9462. normal0 = normal0.scale(this.bu);
  9463. normal1 = normal1.scale(this.bv);
  9464. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9465. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9466. }
  9467. else {
  9468. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9469. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9470. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9471. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9472. var p1p2 = vertex1.subtract(vertex2);
  9473. var p3p2 = vertex3.subtract(vertex2);
  9474. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9475. }
  9476. if (useWorldCoordinates) {
  9477. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9478. }
  9479. return BABYLON.Vector3.Normalize(result);
  9480. };
  9481. PickingInfo.prototype.getTextureCoordinates = function () {
  9482. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9483. return null;
  9484. }
  9485. var indices = this.pickedMesh.getIndices();
  9486. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9487. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9488. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9489. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9490. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9491. uv1 = uv1.scale(this.bu);
  9492. uv2 = uv2.scale(this.bv);
  9493. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9494. };
  9495. return PickingInfo;
  9496. }());
  9497. BABYLON.PickingInfo = PickingInfo;
  9498. })(BABYLON || (BABYLON = {}));
  9499. var BABYLON;
  9500. (function (BABYLON) {
  9501. var BoundingSphere = (function () {
  9502. function BoundingSphere(minimum, maximum) {
  9503. this.minimum = minimum;
  9504. this.maximum = maximum;
  9505. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9506. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9507. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9508. this.radius = distance * 0.5;
  9509. this.centerWorld = BABYLON.Vector3.Zero();
  9510. this._update(BABYLON.Matrix.Identity());
  9511. }
  9512. // Methods
  9513. BoundingSphere.prototype._update = function (world) {
  9514. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9515. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9516. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9517. };
  9518. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9519. for (var i = 0; i < 6; i++) {
  9520. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9521. return false;
  9522. }
  9523. return true;
  9524. };
  9525. BoundingSphere.prototype.intersectsPoint = function (point) {
  9526. var x = this.centerWorld.x - point.x;
  9527. var y = this.centerWorld.y - point.y;
  9528. var z = this.centerWorld.z - point.z;
  9529. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9530. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9531. return false;
  9532. return true;
  9533. };
  9534. // Statics
  9535. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9536. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9537. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9538. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9539. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9540. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9541. return false;
  9542. return true;
  9543. };
  9544. return BoundingSphere;
  9545. }());
  9546. BABYLON.BoundingSphere = BoundingSphere;
  9547. })(BABYLON || (BABYLON = {}));
  9548. var BABYLON;
  9549. (function (BABYLON) {
  9550. var BoundingBox = (function () {
  9551. function BoundingBox(minimum, maximum) {
  9552. this.minimum = minimum;
  9553. this.maximum = maximum;
  9554. this.vectors = new Array();
  9555. this.vectorsWorld = new Array();
  9556. // Bounding vectors
  9557. this.vectors.push(this.minimum.clone());
  9558. this.vectors.push(this.maximum.clone());
  9559. this.vectors.push(this.minimum.clone());
  9560. this.vectors[2].x = this.maximum.x;
  9561. this.vectors.push(this.minimum.clone());
  9562. this.vectors[3].y = this.maximum.y;
  9563. this.vectors.push(this.minimum.clone());
  9564. this.vectors[4].z = this.maximum.z;
  9565. this.vectors.push(this.maximum.clone());
  9566. this.vectors[5].z = this.minimum.z;
  9567. this.vectors.push(this.maximum.clone());
  9568. this.vectors[6].x = this.minimum.x;
  9569. this.vectors.push(this.maximum.clone());
  9570. this.vectors[7].y = this.minimum.y;
  9571. // OBB
  9572. this.center = this.maximum.add(this.minimum).scale(0.5);
  9573. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9574. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9575. // World
  9576. for (var index = 0; index < this.vectors.length; index++) {
  9577. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9578. }
  9579. this.minimumWorld = BABYLON.Vector3.Zero();
  9580. this.maximumWorld = BABYLON.Vector3.Zero();
  9581. this._update(BABYLON.Matrix.Identity());
  9582. }
  9583. // Methods
  9584. BoundingBox.prototype.getWorldMatrix = function () {
  9585. return this._worldMatrix;
  9586. };
  9587. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9588. this._worldMatrix.copyFrom(matrix);
  9589. return this;
  9590. };
  9591. BoundingBox.prototype._update = function (world) {
  9592. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9593. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9594. for (var index = 0; index < this.vectors.length; index++) {
  9595. var v = this.vectorsWorld[index];
  9596. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9597. if (v.x < this.minimumWorld.x)
  9598. this.minimumWorld.x = v.x;
  9599. if (v.y < this.minimumWorld.y)
  9600. this.minimumWorld.y = v.y;
  9601. if (v.z < this.minimumWorld.z)
  9602. this.minimumWorld.z = v.z;
  9603. if (v.x > this.maximumWorld.x)
  9604. this.maximumWorld.x = v.x;
  9605. if (v.y > this.maximumWorld.y)
  9606. this.maximumWorld.y = v.y;
  9607. if (v.z > this.maximumWorld.z)
  9608. this.maximumWorld.z = v.z;
  9609. }
  9610. // OBB
  9611. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9612. this.center.scaleInPlace(0.5);
  9613. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9614. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9615. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9616. this._worldMatrix = world;
  9617. };
  9618. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9619. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9620. };
  9621. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9622. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9623. };
  9624. BoundingBox.prototype.intersectsPoint = function (point) {
  9625. var delta = -BABYLON.Epsilon;
  9626. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9627. return false;
  9628. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9629. return false;
  9630. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9631. return false;
  9632. return true;
  9633. };
  9634. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9635. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9636. };
  9637. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9638. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9639. return false;
  9640. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9641. return false;
  9642. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9643. return false;
  9644. return true;
  9645. };
  9646. // Statics
  9647. BoundingBox.Intersects = function (box0, box1) {
  9648. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9649. return false;
  9650. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9651. return false;
  9652. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9653. return false;
  9654. return true;
  9655. };
  9656. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9657. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9658. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9659. return (num <= (sphereRadius * sphereRadius));
  9660. };
  9661. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9662. for (var p = 0; p < 6; p++) {
  9663. for (var i = 0; i < 8; i++) {
  9664. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9665. return false;
  9666. }
  9667. }
  9668. }
  9669. return true;
  9670. };
  9671. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9672. for (var p = 0; p < 6; p++) {
  9673. var inCount = 8;
  9674. for (var i = 0; i < 8; i++) {
  9675. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9676. --inCount;
  9677. }
  9678. else {
  9679. break;
  9680. }
  9681. }
  9682. if (inCount === 0)
  9683. return false;
  9684. }
  9685. return true;
  9686. };
  9687. return BoundingBox;
  9688. }());
  9689. BABYLON.BoundingBox = BoundingBox;
  9690. })(BABYLON || (BABYLON = {}));
  9691. var BABYLON;
  9692. (function (BABYLON) {
  9693. var computeBoxExtents = function (axis, box) {
  9694. var p = BABYLON.Vector3.Dot(box.center, axis);
  9695. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9696. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9697. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9698. var r = r0 + r1 + r2;
  9699. return {
  9700. min: p - r,
  9701. max: p + r
  9702. };
  9703. };
  9704. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9705. var axisOverlap = function (axis, box0, box1) {
  9706. var result0 = computeBoxExtents(axis, box0);
  9707. var result1 = computeBoxExtents(axis, box1);
  9708. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9709. };
  9710. var BoundingInfo = (function () {
  9711. function BoundingInfo(minimum, maximum) {
  9712. this.minimum = minimum;
  9713. this.maximum = maximum;
  9714. this._isLocked = false;
  9715. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9716. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9717. }
  9718. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9719. get: function () {
  9720. return this._isLocked;
  9721. },
  9722. set: function (value) {
  9723. this._isLocked = value;
  9724. },
  9725. enumerable: true,
  9726. configurable: true
  9727. });
  9728. // Methods
  9729. BoundingInfo.prototype.update = function (world) {
  9730. if (this._isLocked) {
  9731. return;
  9732. }
  9733. this.boundingBox._update(world);
  9734. this.boundingSphere._update(world);
  9735. };
  9736. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9737. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9738. return false;
  9739. return this.boundingBox.isInFrustum(frustumPlanes);
  9740. };
  9741. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9742. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9743. };
  9744. BoundingInfo.prototype._checkCollision = function (collider) {
  9745. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9746. };
  9747. BoundingInfo.prototype.intersectsPoint = function (point) {
  9748. if (!this.boundingSphere.centerWorld) {
  9749. return false;
  9750. }
  9751. if (!this.boundingSphere.intersectsPoint(point)) {
  9752. return false;
  9753. }
  9754. if (!this.boundingBox.intersectsPoint(point)) {
  9755. return false;
  9756. }
  9757. return true;
  9758. };
  9759. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9760. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9761. return false;
  9762. }
  9763. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9764. return false;
  9765. }
  9766. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9767. return false;
  9768. }
  9769. if (!precise) {
  9770. return true;
  9771. }
  9772. var box0 = this.boundingBox;
  9773. var box1 = boundingInfo.boundingBox;
  9774. if (!axisOverlap(box0.directions[0], box0, box1))
  9775. return false;
  9776. if (!axisOverlap(box0.directions[1], box0, box1))
  9777. return false;
  9778. if (!axisOverlap(box0.directions[2], box0, box1))
  9779. return false;
  9780. if (!axisOverlap(box1.directions[0], box0, box1))
  9781. return false;
  9782. if (!axisOverlap(box1.directions[1], box0, box1))
  9783. return false;
  9784. if (!axisOverlap(box1.directions[2], box0, box1))
  9785. return false;
  9786. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9787. return false;
  9788. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9789. return false;
  9790. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9791. return false;
  9792. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9793. return false;
  9794. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9795. return false;
  9796. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9797. return false;
  9798. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9799. return false;
  9800. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9801. return false;
  9802. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9803. return false;
  9804. return true;
  9805. };
  9806. return BoundingInfo;
  9807. }());
  9808. BABYLON.BoundingInfo = BoundingInfo;
  9809. })(BABYLON || (BABYLON = {}));
  9810. var BABYLON;
  9811. (function (BABYLON) {
  9812. var Ray = (function () {
  9813. function Ray(origin, direction, length) {
  9814. if (length === void 0) { length = Number.MAX_VALUE; }
  9815. this.origin = origin;
  9816. this.direction = direction;
  9817. this.length = length;
  9818. }
  9819. // Methods
  9820. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9821. var d = 0.0;
  9822. var maxValue = Number.MAX_VALUE;
  9823. var inv;
  9824. var min;
  9825. var max;
  9826. var temp;
  9827. if (Math.abs(this.direction.x) < 0.0000001) {
  9828. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9829. return false;
  9830. }
  9831. }
  9832. else {
  9833. inv = 1.0 / this.direction.x;
  9834. min = (minimum.x - this.origin.x) * inv;
  9835. max = (maximum.x - this.origin.x) * inv;
  9836. if (max === -Infinity) {
  9837. max = Infinity;
  9838. }
  9839. if (min > max) {
  9840. temp = min;
  9841. min = max;
  9842. max = temp;
  9843. }
  9844. d = Math.max(min, d);
  9845. maxValue = Math.min(max, maxValue);
  9846. if (d > maxValue) {
  9847. return false;
  9848. }
  9849. }
  9850. if (Math.abs(this.direction.y) < 0.0000001) {
  9851. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9852. return false;
  9853. }
  9854. }
  9855. else {
  9856. inv = 1.0 / this.direction.y;
  9857. min = (minimum.y - this.origin.y) * inv;
  9858. max = (maximum.y - this.origin.y) * inv;
  9859. if (max === -Infinity) {
  9860. max = Infinity;
  9861. }
  9862. if (min > max) {
  9863. temp = min;
  9864. min = max;
  9865. max = temp;
  9866. }
  9867. d = Math.max(min, d);
  9868. maxValue = Math.min(max, maxValue);
  9869. if (d > maxValue) {
  9870. return false;
  9871. }
  9872. }
  9873. if (Math.abs(this.direction.z) < 0.0000001) {
  9874. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9875. return false;
  9876. }
  9877. }
  9878. else {
  9879. inv = 1.0 / this.direction.z;
  9880. min = (minimum.z - this.origin.z) * inv;
  9881. max = (maximum.z - this.origin.z) * inv;
  9882. if (max === -Infinity) {
  9883. max = Infinity;
  9884. }
  9885. if (min > max) {
  9886. temp = min;
  9887. min = max;
  9888. max = temp;
  9889. }
  9890. d = Math.max(min, d);
  9891. maxValue = Math.min(max, maxValue);
  9892. if (d > maxValue) {
  9893. return false;
  9894. }
  9895. }
  9896. return true;
  9897. };
  9898. Ray.prototype.intersectsBox = function (box) {
  9899. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9900. };
  9901. Ray.prototype.intersectsSphere = function (sphere) {
  9902. var x = sphere.center.x - this.origin.x;
  9903. var y = sphere.center.y - this.origin.y;
  9904. var z = sphere.center.z - this.origin.z;
  9905. var pyth = (x * x) + (y * y) + (z * z);
  9906. var rr = sphere.radius * sphere.radius;
  9907. if (pyth <= rr) {
  9908. return true;
  9909. }
  9910. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9911. if (dot < 0.0) {
  9912. return false;
  9913. }
  9914. var temp = pyth - (dot * dot);
  9915. return temp <= rr;
  9916. };
  9917. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9918. if (!this._edge1) {
  9919. this._edge1 = BABYLON.Vector3.Zero();
  9920. this._edge2 = BABYLON.Vector3.Zero();
  9921. this._pvec = BABYLON.Vector3.Zero();
  9922. this._tvec = BABYLON.Vector3.Zero();
  9923. this._qvec = BABYLON.Vector3.Zero();
  9924. }
  9925. vertex1.subtractToRef(vertex0, this._edge1);
  9926. vertex2.subtractToRef(vertex0, this._edge2);
  9927. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9928. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9929. if (det === 0) {
  9930. return null;
  9931. }
  9932. var invdet = 1 / det;
  9933. this.origin.subtractToRef(vertex0, this._tvec);
  9934. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9935. if (bu < 0 || bu > 1.0) {
  9936. return null;
  9937. }
  9938. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9939. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9940. if (bv < 0 || bu + bv > 1.0) {
  9941. return null;
  9942. }
  9943. //check if the distance is longer than the predefined length.
  9944. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9945. if (distance > this.length) {
  9946. return null;
  9947. }
  9948. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9949. };
  9950. Ray.prototype.intersectsPlane = function (plane) {
  9951. var distance;
  9952. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9953. if (Math.abs(result1) < 9.99999997475243E-07) {
  9954. return null;
  9955. }
  9956. else {
  9957. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9958. distance = (-plane.d - result2) / result1;
  9959. if (distance < 0.0) {
  9960. if (distance < -9.99999997475243E-07) {
  9961. return null;
  9962. }
  9963. else {
  9964. return 0;
  9965. }
  9966. }
  9967. return distance;
  9968. }
  9969. };
  9970. /**
  9971. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9972. * @param sega the first point of the segment to test the intersection against
  9973. * @param segb the second point of the segment to test the intersection against
  9974. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9975. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9976. */
  9977. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9978. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9979. var u = segb.subtract(sega);
  9980. var v = rsegb.subtract(this.origin);
  9981. var w = sega.subtract(this.origin);
  9982. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9983. var b = BABYLON.Vector3.Dot(u, v);
  9984. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9985. var d = BABYLON.Vector3.Dot(u, w);
  9986. var e = BABYLON.Vector3.Dot(v, w);
  9987. var D = a * c - b * b; // always >= 0
  9988. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9989. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9990. // compute the line parameters of the two closest points
  9991. if (D < Ray.smallnum) {
  9992. sN = 0.0; // force using point P0 on segment S1
  9993. sD = 1.0; // to prevent possible division by 0.0 later
  9994. tN = e;
  9995. tD = c;
  9996. }
  9997. else {
  9998. sN = (b * e - c * d);
  9999. tN = (a * e - b * d);
  10000. if (sN < 0.0) {
  10001. sN = 0.0;
  10002. tN = e;
  10003. tD = c;
  10004. }
  10005. else if (sN > sD) {
  10006. sN = sD;
  10007. tN = e + b;
  10008. tD = c;
  10009. }
  10010. }
  10011. if (tN < 0.0) {
  10012. tN = 0.0;
  10013. // recompute sc for this edge
  10014. if (-d < 0.0) {
  10015. sN = 0.0;
  10016. }
  10017. else if (-d > a)
  10018. sN = sD;
  10019. else {
  10020. sN = -d;
  10021. sD = a;
  10022. }
  10023. }
  10024. else if (tN > tD) {
  10025. tN = tD;
  10026. // recompute sc for this edge
  10027. if ((-d + b) < 0.0) {
  10028. sN = 0;
  10029. }
  10030. else if ((-d + b) > a) {
  10031. sN = sD;
  10032. }
  10033. else {
  10034. sN = (-d + b);
  10035. sD = a;
  10036. }
  10037. }
  10038. // finally do the division to get sc and tc
  10039. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10040. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10041. // get the difference of the two closest points
  10042. var qtc = v.multiplyByFloats(tc, tc, tc);
  10043. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10044. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10045. if (isIntersected) {
  10046. return qtc.length();
  10047. }
  10048. return -1;
  10049. };
  10050. // Statics
  10051. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10052. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10053. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10054. var direction = end.subtract(start);
  10055. direction.normalize();
  10056. return new Ray(start, direction);
  10057. };
  10058. /**
  10059. * 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
  10060. * transformed to the given world matrix.
  10061. * @param origin The origin point
  10062. * @param end The end point
  10063. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10064. */
  10065. Ray.CreateNewFromTo = function (origin, end, world) {
  10066. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10067. var direction = end.subtract(origin);
  10068. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10069. direction.normalize();
  10070. return Ray.Transform(new Ray(origin, direction, length), world);
  10071. };
  10072. Ray.Transform = function (ray, matrix) {
  10073. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10074. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10075. newDirection.normalize();
  10076. return new Ray(newOrigin, newDirection, ray.length);
  10077. };
  10078. Ray.smallnum = 0.00000001;
  10079. Ray.rayl = 10e8;
  10080. return Ray;
  10081. }());
  10082. BABYLON.Ray = Ray;
  10083. })(BABYLON || (BABYLON = {}));
  10084. var BABYLON;
  10085. (function (BABYLON) {
  10086. var AbstractMesh = (function (_super) {
  10087. __extends(AbstractMesh, _super);
  10088. // Constructor
  10089. function AbstractMesh(name, scene) {
  10090. var _this = this;
  10091. _super.call(this, name, scene);
  10092. // Events
  10093. /**
  10094. * An event triggered when the mesh is disposed.
  10095. * @type {BABYLON.Observable}
  10096. */
  10097. this.onDisposeObservable = new BABYLON.Observable();
  10098. /**
  10099. * An event triggered when this mesh collides with another one
  10100. * @type {BABYLON.Observable}
  10101. */
  10102. this.onCollideObservable = new BABYLON.Observable();
  10103. /**
  10104. * An event triggered when the collision's position changes
  10105. * @type {BABYLON.Observable}
  10106. */
  10107. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10108. /**
  10109. * An event triggered after the world matrix is updated
  10110. * @type {BABYLON.Observable}
  10111. */
  10112. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10113. // Properties
  10114. this.definedFacingForward = true; // orientation for POV movement & rotation
  10115. this.position = new BABYLON.Vector3(0, 0, 0);
  10116. this._rotation = new BABYLON.Vector3(0, 0, 0);
  10117. this._scaling = new BABYLON.Vector3(1, 1, 1);
  10118. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10119. this.visibility = 1.0;
  10120. this.alphaIndex = Number.MAX_VALUE;
  10121. this.infiniteDistance = false;
  10122. this.isVisible = true;
  10123. this.isPickable = true;
  10124. this.showBoundingBox = false;
  10125. this.showSubMeshesBoundingBox = false;
  10126. this.isBlocker = false;
  10127. this.renderingGroupId = 0;
  10128. this.receiveShadows = false;
  10129. this.renderOutline = false;
  10130. this.outlineColor = BABYLON.Color3.Red();
  10131. this.outlineWidth = 0.02;
  10132. this.renderOverlay = false;
  10133. this.overlayColor = BABYLON.Color3.Red();
  10134. this.overlayAlpha = 0.5;
  10135. this.hasVertexAlpha = false;
  10136. this.useVertexColors = true;
  10137. this.applyFog = true;
  10138. this.computeBonesUsingShaders = true;
  10139. this.scalingDeterminant = 1;
  10140. this.numBoneInfluencers = 4;
  10141. this.useOctreeForRenderingSelection = true;
  10142. this.useOctreeForPicking = true;
  10143. this.useOctreeForCollisions = true;
  10144. this.layerMask = 0x0FFFFFFF;
  10145. this.alwaysSelectAsActiveMesh = false;
  10146. // Collisions
  10147. this._checkCollisions = false;
  10148. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10149. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10150. this._collider = new BABYLON.Collider();
  10151. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10152. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10153. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10154. // Edges
  10155. this.edgesWidth = 1;
  10156. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10157. // Cache
  10158. this._localWorld = BABYLON.Matrix.Zero();
  10159. this._worldMatrix = BABYLON.Matrix.Zero();
  10160. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10161. this._absolutePosition = BABYLON.Vector3.Zero();
  10162. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10163. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10164. this._isDirty = false;
  10165. this._pivotMatrix = BABYLON.Matrix.Identity();
  10166. this._isDisposed = false;
  10167. this._renderId = 0;
  10168. this._intersectionsInProgress = new Array();
  10169. this._isWorldMatrixFrozen = false;
  10170. this._unIndexed = false;
  10171. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10172. if (collidedMesh === void 0) { collidedMesh = null; }
  10173. //TODO move this to the collision coordinator!
  10174. if (_this.getScene().workerCollisions)
  10175. newPosition.multiplyInPlace(_this._collider.radius);
  10176. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10177. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10178. _this.position.addInPlace(_this._diffPositionForCollisions);
  10179. }
  10180. if (collidedMesh) {
  10181. _this.onCollideObservable.notifyObservers(collidedMesh);
  10182. }
  10183. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10184. };
  10185. scene.addMesh(this);
  10186. }
  10187. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10188. get: function () {
  10189. return AbstractMesh._BILLBOARDMODE_NONE;
  10190. },
  10191. enumerable: true,
  10192. configurable: true
  10193. });
  10194. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10195. get: function () {
  10196. return AbstractMesh._BILLBOARDMODE_X;
  10197. },
  10198. enumerable: true,
  10199. configurable: true
  10200. });
  10201. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10202. get: function () {
  10203. return AbstractMesh._BILLBOARDMODE_Y;
  10204. },
  10205. enumerable: true,
  10206. configurable: true
  10207. });
  10208. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10209. get: function () {
  10210. return AbstractMesh._BILLBOARDMODE_Z;
  10211. },
  10212. enumerable: true,
  10213. configurable: true
  10214. });
  10215. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10216. get: function () {
  10217. return AbstractMesh._BILLBOARDMODE_ALL;
  10218. },
  10219. enumerable: true,
  10220. configurable: true
  10221. });
  10222. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  10223. set: function (callback) {
  10224. if (this._onDisposeObserver) {
  10225. this.onDisposeObservable.remove(this._onDisposeObserver);
  10226. }
  10227. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10228. },
  10229. enumerable: true,
  10230. configurable: true
  10231. });
  10232. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10233. set: function (callback) {
  10234. if (this._onCollideObserver) {
  10235. this.onCollideObservable.remove(this._onCollideObserver);
  10236. }
  10237. this._onCollideObserver = this.onCollideObservable.add(callback);
  10238. },
  10239. enumerable: true,
  10240. configurable: true
  10241. });
  10242. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10243. set: function (callback) {
  10244. if (this._onCollisionPositionChangeObserver) {
  10245. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10246. }
  10247. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10248. },
  10249. enumerable: true,
  10250. configurable: true
  10251. });
  10252. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10253. get: function () {
  10254. return this._skeleton;
  10255. },
  10256. set: function (value) {
  10257. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10258. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10259. }
  10260. if (value && value.needInitialSkinMatrix) {
  10261. value._registerMeshWithPoseMatrix(this);
  10262. }
  10263. this._skeleton = value;
  10264. if (!this._skeleton) {
  10265. this._bonesTransformMatrices = null;
  10266. }
  10267. },
  10268. enumerable: true,
  10269. configurable: true
  10270. });
  10271. /**
  10272. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10273. */
  10274. AbstractMesh.prototype.toString = function (fullDetails) {
  10275. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10276. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10277. if (this._skeleton) {
  10278. ret += ", skeleton: " + this._skeleton.name;
  10279. }
  10280. if (fullDetails) {
  10281. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10282. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10283. }
  10284. return ret;
  10285. };
  10286. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10287. /**
  10288. * Getting the rotation object.
  10289. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10290. */
  10291. get: function () {
  10292. return this._rotation;
  10293. },
  10294. set: function (newRotation) {
  10295. this._rotation = newRotation;
  10296. },
  10297. enumerable: true,
  10298. configurable: true
  10299. });
  10300. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10301. get: function () {
  10302. return this._scaling;
  10303. },
  10304. set: function (newScaling) {
  10305. this._scaling = newScaling;
  10306. if (this.physicsImpostor) {
  10307. this.physicsImpostor.forceUpdate();
  10308. }
  10309. },
  10310. enumerable: true,
  10311. configurable: true
  10312. });
  10313. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10314. get: function () {
  10315. return this._rotationQuaternion;
  10316. },
  10317. set: function (quaternion) {
  10318. this._rotationQuaternion = quaternion;
  10319. //reset the rotation vector.
  10320. if (quaternion && this.rotation.length()) {
  10321. this.rotation.copyFromFloats(0, 0, 0);
  10322. }
  10323. },
  10324. enumerable: true,
  10325. configurable: true
  10326. });
  10327. // Methods
  10328. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10329. this._poseMatrix.copyFrom(matrix);
  10330. };
  10331. AbstractMesh.prototype.getPoseMatrix = function () {
  10332. return this._poseMatrix;
  10333. };
  10334. AbstractMesh.prototype.disableEdgesRendering = function () {
  10335. if (this._edgesRenderer !== undefined) {
  10336. this._edgesRenderer.dispose();
  10337. this._edgesRenderer = undefined;
  10338. }
  10339. };
  10340. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10341. if (epsilon === void 0) { epsilon = 0.95; }
  10342. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10343. this.disableEdgesRendering();
  10344. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10345. };
  10346. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10347. get: function () {
  10348. return false;
  10349. },
  10350. enumerable: true,
  10351. configurable: true
  10352. });
  10353. AbstractMesh.prototype.getLOD = function (camera) {
  10354. return this;
  10355. };
  10356. AbstractMesh.prototype.getTotalVertices = function () {
  10357. return 0;
  10358. };
  10359. AbstractMesh.prototype.getIndices = function () {
  10360. return null;
  10361. };
  10362. AbstractMesh.prototype.getVerticesData = function (kind) {
  10363. return null;
  10364. };
  10365. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10366. return false;
  10367. };
  10368. AbstractMesh.prototype.getBoundingInfo = function () {
  10369. if (this._masterMesh) {
  10370. return this._masterMesh.getBoundingInfo();
  10371. }
  10372. if (!this._boundingInfo) {
  10373. this._updateBoundingInfo();
  10374. }
  10375. return this._boundingInfo;
  10376. };
  10377. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10378. this._boundingInfo = boundingInfo;
  10379. };
  10380. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10381. get: function () {
  10382. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10383. },
  10384. enumerable: true,
  10385. configurable: true
  10386. });
  10387. AbstractMesh.prototype._preActivate = function () {
  10388. };
  10389. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10390. };
  10391. AbstractMesh.prototype._activate = function (renderId) {
  10392. this._renderId = renderId;
  10393. };
  10394. AbstractMesh.prototype.getWorldMatrix = function () {
  10395. if (this._masterMesh) {
  10396. return this._masterMesh.getWorldMatrix();
  10397. }
  10398. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10399. this.computeWorldMatrix();
  10400. }
  10401. return this._worldMatrix;
  10402. };
  10403. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10404. get: function () {
  10405. return this._worldMatrix;
  10406. },
  10407. enumerable: true,
  10408. configurable: true
  10409. });
  10410. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10411. get: function () {
  10412. return this._absolutePosition;
  10413. },
  10414. enumerable: true,
  10415. configurable: true
  10416. });
  10417. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10418. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10419. this.computeWorldMatrix(true);
  10420. this._isWorldMatrixFrozen = true;
  10421. };
  10422. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10423. this._isWorldMatrixFrozen = false;
  10424. this.computeWorldMatrix(true);
  10425. };
  10426. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10427. get: function () {
  10428. return this._isWorldMatrixFrozen;
  10429. },
  10430. enumerable: true,
  10431. configurable: true
  10432. });
  10433. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10434. axis.normalize();
  10435. if (!this.rotationQuaternion) {
  10436. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10437. this.rotation = BABYLON.Vector3.Zero();
  10438. }
  10439. var rotationQuaternion;
  10440. if (!space || space === BABYLON.Space.LOCAL) {
  10441. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10442. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10443. }
  10444. else {
  10445. if (this.parent) {
  10446. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10447. invertParentWorldMatrix.invert();
  10448. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10449. }
  10450. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10451. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10452. }
  10453. };
  10454. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10455. var displacementVector = axis.scale(distance);
  10456. if (!space || space === BABYLON.Space.LOCAL) {
  10457. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10458. this.setPositionWithLocalVector(tempV3);
  10459. }
  10460. else {
  10461. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10462. }
  10463. };
  10464. AbstractMesh.prototype.getAbsolutePosition = function () {
  10465. this.computeWorldMatrix();
  10466. return this._absolutePosition;
  10467. };
  10468. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10469. if (!absolutePosition) {
  10470. return;
  10471. }
  10472. var absolutePositionX;
  10473. var absolutePositionY;
  10474. var absolutePositionZ;
  10475. if (absolutePosition.x === undefined) {
  10476. if (arguments.length < 3) {
  10477. return;
  10478. }
  10479. absolutePositionX = arguments[0];
  10480. absolutePositionY = arguments[1];
  10481. absolutePositionZ = arguments[2];
  10482. }
  10483. else {
  10484. absolutePositionX = absolutePosition.x;
  10485. absolutePositionY = absolutePosition.y;
  10486. absolutePositionZ = absolutePosition.z;
  10487. }
  10488. if (this.parent) {
  10489. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10490. invertParentWorldMatrix.invert();
  10491. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10492. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10493. }
  10494. else {
  10495. this.position.x = absolutePositionX;
  10496. this.position.y = absolutePositionY;
  10497. this.position.z = absolutePositionZ;
  10498. }
  10499. };
  10500. // ================================== Point of View Movement =================================
  10501. /**
  10502. * Perform relative position change from the point of view of behind the front of the mesh.
  10503. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10504. * Supports definition of mesh facing forward or backward.
  10505. * @param {number} amountRight
  10506. * @param {number} amountUp
  10507. * @param {number} amountForward
  10508. */
  10509. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10510. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10511. };
  10512. /**
  10513. * Calculate relative position change from the point of view of behind the front of the mesh.
  10514. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10515. * Supports definition of mesh facing forward or backward.
  10516. * @param {number} amountRight
  10517. * @param {number} amountUp
  10518. * @param {number} amountForward
  10519. */
  10520. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10521. var rotMatrix = new BABYLON.Matrix();
  10522. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10523. rotQuaternion.toRotationMatrix(rotMatrix);
  10524. var translationDelta = BABYLON.Vector3.Zero();
  10525. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10526. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10527. return translationDelta;
  10528. };
  10529. // ================================== Point of View Rotation =================================
  10530. /**
  10531. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10532. * Supports definition of mesh facing forward or backward.
  10533. * @param {number} flipBack
  10534. * @param {number} twirlClockwise
  10535. * @param {number} tiltRight
  10536. */
  10537. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10538. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10539. };
  10540. /**
  10541. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10542. * Supports definition of mesh facing forward or backward.
  10543. * @param {number} flipBack
  10544. * @param {number} twirlClockwise
  10545. * @param {number} tiltRight
  10546. */
  10547. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10548. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10549. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10550. };
  10551. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10552. this._pivotMatrix = matrix;
  10553. this._cache.pivotMatrixUpdated = true;
  10554. };
  10555. AbstractMesh.prototype.getPivotMatrix = function () {
  10556. return this._pivotMatrix;
  10557. };
  10558. AbstractMesh.prototype._isSynchronized = function () {
  10559. if (this._isDirty) {
  10560. return false;
  10561. }
  10562. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10563. return false;
  10564. if (this._cache.pivotMatrixUpdated) {
  10565. return false;
  10566. }
  10567. if (this.infiniteDistance) {
  10568. return false;
  10569. }
  10570. if (!this._cache.position.equals(this.position))
  10571. return false;
  10572. if (this.rotationQuaternion) {
  10573. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10574. return false;
  10575. }
  10576. if (!this._cache.rotation.equals(this.rotation))
  10577. return false;
  10578. if (!this._cache.scaling.equals(this.scaling))
  10579. return false;
  10580. return true;
  10581. };
  10582. AbstractMesh.prototype._initCache = function () {
  10583. _super.prototype._initCache.call(this);
  10584. this._cache.localMatrixUpdated = false;
  10585. this._cache.position = BABYLON.Vector3.Zero();
  10586. this._cache.scaling = BABYLON.Vector3.Zero();
  10587. this._cache.rotation = BABYLON.Vector3.Zero();
  10588. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10589. this._cache.billboardMode = -1;
  10590. };
  10591. AbstractMesh.prototype.markAsDirty = function (property) {
  10592. if (property === "rotation") {
  10593. this.rotationQuaternion = null;
  10594. }
  10595. this._currentRenderId = Number.MAX_VALUE;
  10596. this._isDirty = true;
  10597. };
  10598. AbstractMesh.prototype._updateBoundingInfo = function () {
  10599. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10600. this._boundingInfo.update(this.worldMatrixFromCache);
  10601. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10602. };
  10603. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10604. if (!this.subMeshes) {
  10605. return;
  10606. }
  10607. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10608. var subMesh = this.subMeshes[subIndex];
  10609. if (!subMesh.IsGlobal) {
  10610. subMesh.updateBoundingInfo(matrix);
  10611. }
  10612. }
  10613. };
  10614. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10615. if (this._isWorldMatrixFrozen) {
  10616. return this._worldMatrix;
  10617. }
  10618. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10619. this._currentRenderId = this.getScene().getRenderId();
  10620. return this._worldMatrix;
  10621. }
  10622. this._cache.position.copyFrom(this.position);
  10623. this._cache.scaling.copyFrom(this.scaling);
  10624. this._cache.pivotMatrixUpdated = false;
  10625. this._cache.billboardMode = this.billboardMode;
  10626. this._currentRenderId = this.getScene().getRenderId();
  10627. this._isDirty = false;
  10628. // Scaling
  10629. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10630. // Rotation
  10631. //rotate, if quaternion is set and rotation was used
  10632. if (this.rotationQuaternion) {
  10633. var len = this.rotation.length();
  10634. if (len) {
  10635. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10636. this.rotation.copyFromFloats(0, 0, 0);
  10637. }
  10638. }
  10639. if (this.rotationQuaternion) {
  10640. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10641. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10642. }
  10643. else {
  10644. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10645. this._cache.rotation.copyFrom(this.rotation);
  10646. }
  10647. // Translation
  10648. if (this.infiniteDistance && !this.parent) {
  10649. var camera = this.getScene().activeCamera;
  10650. if (camera) {
  10651. var cameraWorldMatrix = camera.getWorldMatrix();
  10652. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10653. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10654. }
  10655. }
  10656. else {
  10657. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10658. }
  10659. // Composing transformations
  10660. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10661. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10662. // Billboarding
  10663. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10664. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10665. var localPosition = BABYLON.Tmp.Vector3[0];
  10666. if (this.parent && this.parent.getWorldMatrix) {
  10667. this._markSyncedWithParent();
  10668. var parentMatrix;
  10669. if (this._meshToBoneReferal) {
  10670. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10671. parentMatrix = BABYLON.Tmp.Matrix[6];
  10672. }
  10673. else {
  10674. parentMatrix = this.parent.getWorldMatrix();
  10675. }
  10676. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10677. localPosition = BABYLON.Tmp.Vector3[1];
  10678. }
  10679. var zero = this.getScene().activeCamera.globalPosition.clone();
  10680. if (this.parent && this.parent.position) {
  10681. localPosition.addInPlace(this.parent.position);
  10682. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10683. }
  10684. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10685. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10686. zero.x = localPosition.x + BABYLON.Epsilon;
  10687. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10688. zero.y = localPosition.y + BABYLON.Epsilon;
  10689. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10690. zero.z = localPosition.z + BABYLON.Epsilon;
  10691. }
  10692. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10693. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10694. BABYLON.Tmp.Matrix[3].invert();
  10695. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10696. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10697. }
  10698. // Local world
  10699. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10700. // Parent
  10701. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10702. this._markSyncedWithParent();
  10703. if (this._meshToBoneReferal) {
  10704. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10705. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10706. }
  10707. else {
  10708. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10709. }
  10710. }
  10711. else {
  10712. this._worldMatrix.copyFrom(this._localWorld);
  10713. }
  10714. // Bounding info
  10715. this._updateBoundingInfo();
  10716. // Absolute position
  10717. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10718. // Callbacks
  10719. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10720. if (!this._poseMatrix) {
  10721. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10722. }
  10723. return this._worldMatrix;
  10724. };
  10725. /**
  10726. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10727. * @param func: callback function to add
  10728. */
  10729. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10730. this.onAfterWorldMatrixUpdateObservable.add(func);
  10731. };
  10732. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10733. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10734. };
  10735. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10736. this.computeWorldMatrix();
  10737. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10738. };
  10739. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10740. this.computeWorldMatrix();
  10741. var invLocalWorldMatrix = this._localWorld.clone();
  10742. invLocalWorldMatrix.invert();
  10743. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10744. };
  10745. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10746. this.computeWorldMatrix(true);
  10747. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10748. };
  10749. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10750. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10751. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10752. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10753. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10754. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10755. /// <returns>Mesh oriented towards targetMesh</returns>
  10756. if (yawCor === void 0) { yawCor = 0; }
  10757. if (pitchCor === void 0) { pitchCor = 0; }
  10758. if (rollCor === void 0) { rollCor = 0; }
  10759. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10760. var dv = AbstractMesh._lookAtVectorCache;
  10761. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10762. targetPoint.subtractToRef(pos, dv);
  10763. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10764. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10765. var pitch = Math.atan2(dv.y, len);
  10766. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10767. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10768. };
  10769. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10770. this._meshToBoneReferal = affectedMesh;
  10771. this.parent = bone;
  10772. if (bone.getWorldMatrix().determinant() < 0) {
  10773. this.scalingDeterminant *= -1;
  10774. }
  10775. };
  10776. AbstractMesh.prototype.detachFromBone = function () {
  10777. if (this.parent.getWorldMatrix().determinant() < 0) {
  10778. this.scalingDeterminant *= -1;
  10779. }
  10780. this._meshToBoneReferal = null;
  10781. this.parent = null;
  10782. };
  10783. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10784. return this._boundingInfo.isInFrustum(frustumPlanes);
  10785. };
  10786. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10787. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10788. ;
  10789. };
  10790. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10791. if (!this._boundingInfo || !mesh._boundingInfo) {
  10792. return false;
  10793. }
  10794. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10795. };
  10796. AbstractMesh.prototype.intersectsPoint = function (point) {
  10797. if (!this._boundingInfo) {
  10798. return false;
  10799. }
  10800. return this._boundingInfo.intersectsPoint(point);
  10801. };
  10802. // Physics
  10803. /**
  10804. * @Deprecated. Use new PhysicsImpostor instead.
  10805. * */
  10806. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10807. //legacy support
  10808. if (impostor.impostor) {
  10809. options = impostor;
  10810. impostor = impostor.impostor;
  10811. }
  10812. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10813. return this.physicsImpostor.physicsBody;
  10814. };
  10815. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10816. return this.physicsImpostor;
  10817. };
  10818. /**
  10819. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10820. */
  10821. AbstractMesh.prototype.getPhysicsMass = function () {
  10822. return this.physicsImpostor.getParam("mass");
  10823. };
  10824. /**
  10825. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10826. */
  10827. AbstractMesh.prototype.getPhysicsFriction = function () {
  10828. return this.physicsImpostor.getParam("friction");
  10829. };
  10830. /**
  10831. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10832. */
  10833. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10834. return this.physicsImpostor.getParam("restitution");
  10835. };
  10836. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10837. if (!camera) {
  10838. camera = this.getScene().activeCamera;
  10839. }
  10840. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10841. };
  10842. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10843. if (!camera) {
  10844. camera = this.getScene().activeCamera;
  10845. }
  10846. return this.absolutePosition.subtract(camera.position).length();
  10847. };
  10848. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10849. if (!this.physicsImpostor) {
  10850. return;
  10851. }
  10852. this.physicsImpostor.applyImpulse(force, contactPoint);
  10853. };
  10854. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10855. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10856. return;
  10857. }
  10858. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10859. mainPivot: pivot1,
  10860. connectedPivot: pivot2,
  10861. nativeParams: options
  10862. });
  10863. };
  10864. /**
  10865. * @Deprecated
  10866. */
  10867. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10868. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10869. this.updatePhysicsBody();
  10870. };
  10871. /**
  10872. * @Deprecated
  10873. * Calling this function is not needed anymore.
  10874. * The physics engine takes care of transofmration automatically.
  10875. */
  10876. AbstractMesh.prototype.updatePhysicsBody = function () {
  10877. //Unneeded
  10878. };
  10879. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10880. // Collisions
  10881. get: function () {
  10882. return this._checkCollisions;
  10883. },
  10884. set: function (collisionEnabled) {
  10885. this._checkCollisions = collisionEnabled;
  10886. if (this.getScene().workerCollisions) {
  10887. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10888. }
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10894. var globalPosition = this.getAbsolutePosition();
  10895. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10896. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10897. this._collider.radius = this.ellipsoid;
  10898. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10899. };
  10900. // Submeshes octree
  10901. /**
  10902. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10903. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10904. */
  10905. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10906. if (maxCapacity === void 0) { maxCapacity = 64; }
  10907. if (maxDepth === void 0) { maxDepth = 2; }
  10908. if (!this._submeshesOctree) {
  10909. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10910. }
  10911. this.computeWorldMatrix(true);
  10912. // Update octree
  10913. var bbox = this.getBoundingInfo().boundingBox;
  10914. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10915. return this._submeshesOctree;
  10916. };
  10917. // Collisions
  10918. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10919. this._generatePointsArray();
  10920. // Transformation
  10921. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10922. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10923. subMesh._lastColliderWorldVertices = [];
  10924. subMesh._trianglePlanes = [];
  10925. var start = subMesh.verticesStart;
  10926. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10927. for (var i = start; i < end; i++) {
  10928. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10929. }
  10930. }
  10931. // Collide
  10932. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10933. if (collider.collisionFound) {
  10934. collider.collidedMesh = this;
  10935. }
  10936. };
  10937. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10938. var subMeshes;
  10939. var len;
  10940. // Octrees
  10941. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10942. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10943. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10944. len = intersections.length;
  10945. subMeshes = intersections.data;
  10946. }
  10947. else {
  10948. subMeshes = this.subMeshes;
  10949. len = subMeshes.length;
  10950. }
  10951. for (var index = 0; index < len; index++) {
  10952. var subMesh = subMeshes[index];
  10953. // Bounding test
  10954. if (len > 1 && !subMesh._checkCollision(collider))
  10955. continue;
  10956. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10957. }
  10958. };
  10959. AbstractMesh.prototype._checkCollision = function (collider) {
  10960. // Bounding box test
  10961. if (!this._boundingInfo._checkCollision(collider))
  10962. return;
  10963. // Transformation matrix
  10964. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10965. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10966. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10967. };
  10968. // Picking
  10969. AbstractMesh.prototype._generatePointsArray = function () {
  10970. return false;
  10971. };
  10972. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10973. var pickingInfo = new BABYLON.PickingInfo();
  10974. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10975. return pickingInfo;
  10976. }
  10977. if (!this._generatePointsArray()) {
  10978. return pickingInfo;
  10979. }
  10980. var intersectInfo = null;
  10981. // Octrees
  10982. var subMeshes;
  10983. var len;
  10984. if (this._submeshesOctree && this.useOctreeForPicking) {
  10985. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10986. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10987. len = intersections.length;
  10988. subMeshes = intersections.data;
  10989. }
  10990. else {
  10991. subMeshes = this.subMeshes;
  10992. len = subMeshes.length;
  10993. }
  10994. for (var index = 0; index < len; index++) {
  10995. var subMesh = subMeshes[index];
  10996. // Bounding test
  10997. if (len > 1 && !subMesh.canIntersects(ray))
  10998. continue;
  10999. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11000. if (currentIntersectInfo) {
  11001. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11002. intersectInfo = currentIntersectInfo;
  11003. intersectInfo.subMeshId = index;
  11004. if (fastCheck) {
  11005. break;
  11006. }
  11007. }
  11008. }
  11009. }
  11010. if (intersectInfo) {
  11011. // Get picked point
  11012. var world = this.getWorldMatrix();
  11013. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11014. var direction = ray.direction.clone();
  11015. direction = direction.scale(intersectInfo.distance);
  11016. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11017. var pickedPoint = worldOrigin.add(worldDirection);
  11018. // Return result
  11019. pickingInfo.hit = true;
  11020. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11021. pickingInfo.pickedPoint = pickedPoint;
  11022. pickingInfo.pickedMesh = this;
  11023. pickingInfo.bu = intersectInfo.bu;
  11024. pickingInfo.bv = intersectInfo.bv;
  11025. pickingInfo.faceId = intersectInfo.faceId;
  11026. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11027. return pickingInfo;
  11028. }
  11029. return pickingInfo;
  11030. };
  11031. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11032. return null;
  11033. };
  11034. AbstractMesh.prototype.releaseSubMeshes = function () {
  11035. if (this.subMeshes) {
  11036. while (this.subMeshes.length) {
  11037. this.subMeshes[0].dispose();
  11038. }
  11039. }
  11040. else {
  11041. this.subMeshes = new Array();
  11042. }
  11043. };
  11044. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11045. var _this = this;
  11046. var index;
  11047. // Action manager
  11048. if (this.actionManager) {
  11049. this.actionManager.dispose();
  11050. this.actionManager = null;
  11051. }
  11052. // Skeleton
  11053. this.skeleton = null;
  11054. // Animations
  11055. this.getScene().stopAnimation(this);
  11056. // Physics
  11057. if (this.physicsImpostor) {
  11058. this.physicsImpostor.dispose();
  11059. }
  11060. // Intersections in progress
  11061. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11062. var other = this._intersectionsInProgress[index];
  11063. var pos = other._intersectionsInProgress.indexOf(this);
  11064. other._intersectionsInProgress.splice(pos, 1);
  11065. }
  11066. this._intersectionsInProgress = [];
  11067. // Lights
  11068. var lights = this.getScene().lights;
  11069. lights.forEach(function (light) {
  11070. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11071. if (meshIndex !== -1) {
  11072. light.includedOnlyMeshes.splice(meshIndex, 1);
  11073. }
  11074. meshIndex = light.excludedMeshes.indexOf(_this);
  11075. if (meshIndex !== -1) {
  11076. light.excludedMeshes.splice(meshIndex, 1);
  11077. }
  11078. // Shadow generators
  11079. var generator = light.getShadowGenerator();
  11080. if (generator) {
  11081. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11082. if (meshIndex !== -1) {
  11083. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11084. }
  11085. }
  11086. });
  11087. // Edges
  11088. if (this._edgesRenderer) {
  11089. this._edgesRenderer.dispose();
  11090. this._edgesRenderer = null;
  11091. }
  11092. // SubMeshes
  11093. this.releaseSubMeshes();
  11094. // Engine
  11095. this.getScene().getEngine().unbindAllAttributes();
  11096. // Remove from scene
  11097. this.getScene().removeMesh(this);
  11098. if (!doNotRecurse) {
  11099. // Particles
  11100. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11101. if (this.getScene().particleSystems[index].emitter === this) {
  11102. this.getScene().particleSystems[index].dispose();
  11103. index--;
  11104. }
  11105. }
  11106. // Children
  11107. var objects = this.getDescendants(true);
  11108. for (index = 0; index < objects.length; index++) {
  11109. objects[index].dispose();
  11110. }
  11111. }
  11112. else {
  11113. var childMeshes = this.getChildMeshes(true);
  11114. for (index = 0; index < childMeshes.length; index++) {
  11115. var child = childMeshes[index];
  11116. child.parent = null;
  11117. child.computeWorldMatrix(true);
  11118. }
  11119. }
  11120. _super.prototype.dispose.call(this);
  11121. this.onAfterWorldMatrixUpdateObservable.clear();
  11122. this.onCollideObservable.clear();
  11123. this.onCollisionPositionChangeObservable.clear();
  11124. this._isDisposed = true;
  11125. // Callback
  11126. this.onDisposeObservable.notifyObservers(this);
  11127. this.onDisposeObservable.clear();
  11128. };
  11129. // Statics
  11130. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11131. AbstractMesh._BILLBOARDMODE_X = 1;
  11132. AbstractMesh._BILLBOARDMODE_Y = 2;
  11133. AbstractMesh._BILLBOARDMODE_Z = 4;
  11134. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11135. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11136. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11137. return AbstractMesh;
  11138. }(BABYLON.Node));
  11139. BABYLON.AbstractMesh = AbstractMesh;
  11140. })(BABYLON || (BABYLON = {}));
  11141. var BABYLON;
  11142. (function (BABYLON) {
  11143. var Light = (function (_super) {
  11144. __extends(Light, _super);
  11145. function Light(name, scene) {
  11146. _super.call(this, name, scene);
  11147. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11148. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11149. this.intensity = 1.0;
  11150. this.range = Number.MAX_VALUE;
  11151. this.includeOnlyWithLayerMask = 0;
  11152. this.includedOnlyMeshes = new Array();
  11153. this.excludedMeshes = new Array();
  11154. this.excludeWithLayerMask = 0;
  11155. this.lightmapMode = 0;
  11156. // PBR Properties.
  11157. this.radius = 0.00001;
  11158. this._excludedMeshesIds = new Array();
  11159. this._includedOnlyMeshesIds = new Array();
  11160. scene.addLight(this);
  11161. }
  11162. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11163. /**
  11164. * If every light affecting the material is in this lightmapMode,
  11165. * material.lightmapTexture adds or multiplies
  11166. * (depends on material.useLightmapAsShadowmap)
  11167. * after every other light calculations.
  11168. */
  11169. get: function () {
  11170. return Light._LIGHTMAP_DEFAULT;
  11171. },
  11172. enumerable: true,
  11173. configurable: true
  11174. });
  11175. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11176. /**
  11177. * material.lightmapTexture as only diffuse lighting from this light
  11178. * adds pnly specular lighting from this light
  11179. * adds dynamic shadows
  11180. */
  11181. get: function () {
  11182. return Light._LIGHTMAP_SPECULAR;
  11183. },
  11184. enumerable: true,
  11185. configurable: true
  11186. });
  11187. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11188. /**
  11189. * material.lightmapTexture as only lighting
  11190. * no light calculation from this light
  11191. * only adds dynamic shadows from this light
  11192. */
  11193. get: function () {
  11194. return Light._LIGHTMAP_SHADOWSONLY;
  11195. },
  11196. enumerable: true,
  11197. configurable: true
  11198. });
  11199. /**
  11200. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11201. */
  11202. Light.prototype.toString = function (fullDetails) {
  11203. var ret = "Name: " + this.name;
  11204. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11205. if (this.animations) {
  11206. for (var i = 0; i < this.animations.length; i++) {
  11207. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11208. }
  11209. }
  11210. if (fullDetails) {
  11211. }
  11212. return ret;
  11213. };
  11214. Light.prototype.getShadowGenerator = function () {
  11215. return this._shadowGenerator;
  11216. };
  11217. Light.prototype.getAbsolutePosition = function () {
  11218. return BABYLON.Vector3.Zero();
  11219. };
  11220. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11221. };
  11222. Light.prototype._getWorldMatrix = function () {
  11223. return BABYLON.Matrix.Identity();
  11224. };
  11225. Light.prototype.canAffectMesh = function (mesh) {
  11226. if (!mesh) {
  11227. return true;
  11228. }
  11229. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11230. return false;
  11231. }
  11232. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11233. return false;
  11234. }
  11235. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11236. return false;
  11237. }
  11238. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11239. return false;
  11240. }
  11241. return true;
  11242. };
  11243. Light.prototype.getWorldMatrix = function () {
  11244. this._currentRenderId = this.getScene().getRenderId();
  11245. var worldMatrix = this._getWorldMatrix();
  11246. if (this.parent && this.parent.getWorldMatrix) {
  11247. if (!this._parentedWorldMatrix) {
  11248. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11249. }
  11250. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11251. this._markSyncedWithParent();
  11252. return this._parentedWorldMatrix;
  11253. }
  11254. return worldMatrix;
  11255. };
  11256. Light.prototype.dispose = function () {
  11257. if (this._shadowGenerator) {
  11258. this._shadowGenerator.dispose();
  11259. this._shadowGenerator = null;
  11260. }
  11261. // Animations
  11262. this.getScene().stopAnimation(this);
  11263. // Remove from scene
  11264. this.getScene().removeLight(this);
  11265. _super.prototype.dispose.call(this);
  11266. };
  11267. Light.prototype.getTypeID = function () {
  11268. return 0;
  11269. };
  11270. Light.prototype.clone = function (name) {
  11271. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11272. };
  11273. Light.prototype.serialize = function () {
  11274. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11275. // Type
  11276. serializationObject.type = this.getTypeID();
  11277. // Parent
  11278. if (this.parent) {
  11279. serializationObject.parentId = this.parent.id;
  11280. }
  11281. // Inclusion / exclusions
  11282. if (this.excludedMeshes.length > 0) {
  11283. serializationObject.excludedMeshesIds = [];
  11284. this.excludedMeshes.forEach(function (mesh) {
  11285. serializationObject.excludedMeshesIds.push(mesh.id);
  11286. });
  11287. }
  11288. if (this.includedOnlyMeshes.length > 0) {
  11289. serializationObject.includedOnlyMeshesIds = [];
  11290. this.includedOnlyMeshes.forEach(function (mesh) {
  11291. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11292. });
  11293. }
  11294. // Animations
  11295. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11296. serializationObject.ranges = this.serializeAnimationRanges();
  11297. return serializationObject;
  11298. };
  11299. Light.GetConstructorFromName = function (type, name, scene) {
  11300. switch (type) {
  11301. case 0:
  11302. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11303. case 1:
  11304. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11305. case 2:
  11306. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11307. case 3:
  11308. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11309. }
  11310. };
  11311. Light.Parse = function (parsedLight, scene) {
  11312. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11313. // Inclusion / exclusions
  11314. if (parsedLight.excludedMeshesIds) {
  11315. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11316. }
  11317. if (parsedLight.includedOnlyMeshesIds) {
  11318. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11319. }
  11320. // Parent
  11321. if (parsedLight.parentId) {
  11322. light._waitingParentId = parsedLight.parentId;
  11323. }
  11324. // Animations
  11325. if (parsedLight.animations) {
  11326. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11327. var parsedAnimation = parsedLight.animations[animationIndex];
  11328. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11329. }
  11330. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11331. }
  11332. if (parsedLight.autoAnimate) {
  11333. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11334. }
  11335. return light;
  11336. };
  11337. //lightmapMode Consts
  11338. Light._LIGHTMAP_DEFAULT = 0;
  11339. Light._LIGHTMAP_SPECULAR = 1;
  11340. Light._LIGHTMAP_SHADOWSONLY = 2;
  11341. __decorate([
  11342. BABYLON.serializeAsColor3()
  11343. ], Light.prototype, "diffuse", void 0);
  11344. __decorate([
  11345. BABYLON.serializeAsColor3()
  11346. ], Light.prototype, "specular", void 0);
  11347. __decorate([
  11348. BABYLON.serialize()
  11349. ], Light.prototype, "intensity", void 0);
  11350. __decorate([
  11351. BABYLON.serialize()
  11352. ], Light.prototype, "range", void 0);
  11353. __decorate([
  11354. BABYLON.serialize()
  11355. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11356. __decorate([
  11357. BABYLON.serialize()
  11358. ], Light.prototype, "excludeWithLayerMask", void 0);
  11359. __decorate([
  11360. BABYLON.serialize()
  11361. ], Light.prototype, "lightmapMode", void 0);
  11362. __decorate([
  11363. BABYLON.serialize()
  11364. ], Light.prototype, "radius", void 0);
  11365. return Light;
  11366. }(BABYLON.Node));
  11367. BABYLON.Light = Light;
  11368. })(BABYLON || (BABYLON = {}));
  11369. var BABYLON;
  11370. (function (BABYLON) {
  11371. var PointLight = (function (_super) {
  11372. __extends(PointLight, _super);
  11373. function PointLight(name, position, scene) {
  11374. _super.call(this, name, scene);
  11375. this.position = position;
  11376. }
  11377. PointLight.prototype.getAbsolutePosition = function () {
  11378. return this.transformedPosition ? this.transformedPosition : this.position;
  11379. };
  11380. PointLight.prototype.computeTransformedPosition = function () {
  11381. if (this.parent && this.parent.getWorldMatrix) {
  11382. if (!this.transformedPosition) {
  11383. this.transformedPosition = BABYLON.Vector3.Zero();
  11384. }
  11385. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11386. return true;
  11387. }
  11388. return false;
  11389. };
  11390. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11391. if (this.parent && this.parent.getWorldMatrix) {
  11392. this.computeTransformedPosition();
  11393. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11394. return;
  11395. }
  11396. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11397. };
  11398. PointLight.prototype.needCube = function () {
  11399. return true;
  11400. };
  11401. PointLight.prototype.supportsVSM = function () {
  11402. return false;
  11403. };
  11404. PointLight.prototype.needRefreshPerFrame = function () {
  11405. return false;
  11406. };
  11407. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11408. switch (faceIndex) {
  11409. case 0:
  11410. return new BABYLON.Vector3(1, 0, 0);
  11411. case 1:
  11412. return new BABYLON.Vector3(-1, 0, 0);
  11413. case 2:
  11414. return new BABYLON.Vector3(0, -1, 0);
  11415. case 3:
  11416. return new BABYLON.Vector3(0, 1, 0);
  11417. case 4:
  11418. return new BABYLON.Vector3(0, 0, 1);
  11419. case 5:
  11420. return new BABYLON.Vector3(0, 0, -1);
  11421. }
  11422. return BABYLON.Vector3.Zero();
  11423. };
  11424. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11425. var activeCamera = this.getScene().activeCamera;
  11426. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11427. };
  11428. PointLight.prototype._getWorldMatrix = function () {
  11429. if (!this._worldMatrix) {
  11430. this._worldMatrix = BABYLON.Matrix.Identity();
  11431. }
  11432. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11433. return this._worldMatrix;
  11434. };
  11435. PointLight.prototype.getTypeID = function () {
  11436. return 0;
  11437. };
  11438. __decorate([
  11439. BABYLON.serializeAsVector3()
  11440. ], PointLight.prototype, "position", void 0);
  11441. return PointLight;
  11442. }(BABYLON.Light));
  11443. BABYLON.PointLight = PointLight;
  11444. })(BABYLON || (BABYLON = {}));
  11445. var BABYLON;
  11446. (function (BABYLON) {
  11447. var SpotLight = (function (_super) {
  11448. __extends(SpotLight, _super);
  11449. function SpotLight(name, position, direction, angle, exponent, scene) {
  11450. _super.call(this, name, scene);
  11451. this.position = position;
  11452. this.direction = direction;
  11453. this.angle = angle;
  11454. this.exponent = exponent;
  11455. }
  11456. SpotLight.prototype.getAbsolutePosition = function () {
  11457. return this.transformedPosition ? this.transformedPosition : this.position;
  11458. };
  11459. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11460. var activeCamera = this.getScene().activeCamera;
  11461. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11462. };
  11463. SpotLight.prototype.needCube = function () {
  11464. return false;
  11465. };
  11466. SpotLight.prototype.supportsVSM = function () {
  11467. return true;
  11468. };
  11469. SpotLight.prototype.needRefreshPerFrame = function () {
  11470. return false;
  11471. };
  11472. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11473. return this.direction;
  11474. };
  11475. SpotLight.prototype.setDirectionToTarget = function (target) {
  11476. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11477. return this.direction;
  11478. };
  11479. SpotLight.prototype.computeTransformedPosition = function () {
  11480. if (this.parent && this.parent.getWorldMatrix) {
  11481. if (!this.transformedPosition) {
  11482. this.transformedPosition = BABYLON.Vector3.Zero();
  11483. }
  11484. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11485. return true;
  11486. }
  11487. return false;
  11488. };
  11489. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11490. var normalizeDirection;
  11491. if (this.parent && this.parent.getWorldMatrix) {
  11492. if (!this._transformedDirection) {
  11493. this._transformedDirection = BABYLON.Vector3.Zero();
  11494. }
  11495. this.computeTransformedPosition();
  11496. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11497. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11498. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11499. }
  11500. else {
  11501. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11502. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11503. }
  11504. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11505. };
  11506. SpotLight.prototype._getWorldMatrix = function () {
  11507. if (!this._worldMatrix) {
  11508. this._worldMatrix = BABYLON.Matrix.Identity();
  11509. }
  11510. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11511. return this._worldMatrix;
  11512. };
  11513. SpotLight.prototype.getTypeID = function () {
  11514. return 2;
  11515. };
  11516. __decorate([
  11517. BABYLON.serializeAsVector3()
  11518. ], SpotLight.prototype, "position", void 0);
  11519. __decorate([
  11520. BABYLON.serializeAsVector3()
  11521. ], SpotLight.prototype, "direction", void 0);
  11522. __decorate([
  11523. BABYLON.serialize()
  11524. ], SpotLight.prototype, "angle", void 0);
  11525. __decorate([
  11526. BABYLON.serialize()
  11527. ], SpotLight.prototype, "exponent", void 0);
  11528. return SpotLight;
  11529. }(BABYLON.Light));
  11530. BABYLON.SpotLight = SpotLight;
  11531. })(BABYLON || (BABYLON = {}));
  11532. var BABYLON;
  11533. (function (BABYLON) {
  11534. var HemisphericLight = (function (_super) {
  11535. __extends(HemisphericLight, _super);
  11536. function HemisphericLight(name, direction, scene) {
  11537. _super.call(this, name, scene);
  11538. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11539. this.direction = direction;
  11540. }
  11541. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11542. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11543. return this.direction;
  11544. };
  11545. HemisphericLight.prototype.getShadowGenerator = function () {
  11546. return null;
  11547. };
  11548. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11549. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11550. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11551. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11552. };
  11553. HemisphericLight.prototype._getWorldMatrix = function () {
  11554. if (!this._worldMatrix) {
  11555. this._worldMatrix = BABYLON.Matrix.Identity();
  11556. }
  11557. return this._worldMatrix;
  11558. };
  11559. HemisphericLight.prototype.getTypeID = function () {
  11560. return 3;
  11561. };
  11562. __decorate([
  11563. BABYLON.serializeAsColor3()
  11564. ], HemisphericLight.prototype, "groundColor", void 0);
  11565. __decorate([
  11566. BABYLON.serializeAsVector3()
  11567. ], HemisphericLight.prototype, "direction", void 0);
  11568. return HemisphericLight;
  11569. }(BABYLON.Light));
  11570. BABYLON.HemisphericLight = HemisphericLight;
  11571. })(BABYLON || (BABYLON = {}));
  11572. var BABYLON;
  11573. (function (BABYLON) {
  11574. var DirectionalLight = (function (_super) {
  11575. __extends(DirectionalLight, _super);
  11576. function DirectionalLight(name, direction, scene) {
  11577. _super.call(this, name, scene);
  11578. this.shadowOrthoScale = 0.5;
  11579. this.autoUpdateExtends = true;
  11580. // Cache
  11581. this._orthoLeft = Number.MAX_VALUE;
  11582. this._orthoRight = Number.MIN_VALUE;
  11583. this._orthoTop = Number.MIN_VALUE;
  11584. this._orthoBottom = Number.MAX_VALUE;
  11585. this.position = direction.scale(-1);
  11586. this.direction = direction;
  11587. }
  11588. DirectionalLight.prototype.getAbsolutePosition = function () {
  11589. return this.transformedPosition ? this.transformedPosition : this.position;
  11590. };
  11591. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11592. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11593. return this.direction;
  11594. };
  11595. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11596. var activeCamera = this.getScene().activeCamera;
  11597. // Check extends
  11598. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11599. var tempVector3 = BABYLON.Vector3.Zero();
  11600. this._orthoLeft = Number.MAX_VALUE;
  11601. this._orthoRight = Number.MIN_VALUE;
  11602. this._orthoTop = Number.MIN_VALUE;
  11603. this._orthoBottom = Number.MAX_VALUE;
  11604. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11605. var mesh = renderList[meshIndex];
  11606. if (!mesh) {
  11607. continue;
  11608. }
  11609. var boundingInfo = mesh.getBoundingInfo();
  11610. if (!boundingInfo) {
  11611. continue;
  11612. }
  11613. var boundingBox = boundingInfo.boundingBox;
  11614. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11615. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11616. if (tempVector3.x < this._orthoLeft)
  11617. this._orthoLeft = tempVector3.x;
  11618. if (tempVector3.y < this._orthoBottom)
  11619. this._orthoBottom = tempVector3.y;
  11620. if (tempVector3.x > this._orthoRight)
  11621. this._orthoRight = tempVector3.x;
  11622. if (tempVector3.y > this._orthoTop)
  11623. this._orthoTop = tempVector3.y;
  11624. }
  11625. }
  11626. }
  11627. var xOffset = this._orthoRight - this._orthoLeft;
  11628. var yOffset = this._orthoTop - this._orthoBottom;
  11629. 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);
  11630. };
  11631. DirectionalLight.prototype.supportsVSM = function () {
  11632. return true;
  11633. };
  11634. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11635. return true;
  11636. };
  11637. DirectionalLight.prototype.needCube = function () {
  11638. return false;
  11639. };
  11640. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11641. return this.direction;
  11642. };
  11643. DirectionalLight.prototype.computeTransformedPosition = function () {
  11644. if (this.parent && this.parent.getWorldMatrix) {
  11645. if (!this.transformedPosition) {
  11646. this.transformedPosition = BABYLON.Vector3.Zero();
  11647. }
  11648. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11649. return true;
  11650. }
  11651. return false;
  11652. };
  11653. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11654. if (this.parent && this.parent.getWorldMatrix) {
  11655. if (!this._transformedDirection) {
  11656. this._transformedDirection = BABYLON.Vector3.Zero();
  11657. }
  11658. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11659. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11660. return;
  11661. }
  11662. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11663. };
  11664. DirectionalLight.prototype._getWorldMatrix = function () {
  11665. if (!this._worldMatrix) {
  11666. this._worldMatrix = BABYLON.Matrix.Identity();
  11667. }
  11668. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11669. return this._worldMatrix;
  11670. };
  11671. DirectionalLight.prototype.getTypeID = function () {
  11672. return 1;
  11673. };
  11674. __decorate([
  11675. BABYLON.serializeAsVector3()
  11676. ], DirectionalLight.prototype, "position", void 0);
  11677. __decorate([
  11678. BABYLON.serializeAsVector3()
  11679. ], DirectionalLight.prototype, "direction", void 0);
  11680. __decorate([
  11681. BABYLON.serialize()
  11682. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11683. __decorate([
  11684. BABYLON.serialize()
  11685. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11686. return DirectionalLight;
  11687. }(BABYLON.Light));
  11688. BABYLON.DirectionalLight = DirectionalLight;
  11689. })(BABYLON || (BABYLON = {}));
  11690. var BABYLON;
  11691. (function (BABYLON) {
  11692. var ShadowGenerator = (function () {
  11693. function ShadowGenerator(mapSize, light) {
  11694. var _this = this;
  11695. // Members
  11696. this._filter = ShadowGenerator.FILTER_NONE;
  11697. this.blurScale = 2;
  11698. this._blurBoxOffset = 0;
  11699. this._bias = 0.00005;
  11700. this._lightDirection = BABYLON.Vector3.Zero();
  11701. this.forceBackFacesOnly = false;
  11702. this._darkness = 0;
  11703. this._transparencyShadow = false;
  11704. this._viewMatrix = BABYLON.Matrix.Zero();
  11705. this._projectionMatrix = BABYLON.Matrix.Zero();
  11706. this._transformMatrix = BABYLON.Matrix.Zero();
  11707. this._worldViewProjection = BABYLON.Matrix.Zero();
  11708. this._currentFaceIndex = 0;
  11709. this._currentFaceIndexCache = 0;
  11710. this._useFullFloat = true;
  11711. this._light = light;
  11712. this._scene = light.getScene();
  11713. this._mapSize = mapSize;
  11714. light._shadowGenerator = this;
  11715. // Texture type fallback from float to int if not supported.
  11716. var textureType;
  11717. var caps = this._scene.getEngine().getCaps();
  11718. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11719. this._useFullFloat = true;
  11720. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11721. }
  11722. else {
  11723. this._useFullFloat = false;
  11724. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11725. }
  11726. // Render target
  11727. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11728. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11729. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11730. this._shadowMap.anisotropicFilteringLevel = 1;
  11731. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11732. this._shadowMap.renderParticles = false;
  11733. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11734. _this._currentFaceIndex = faceIndex;
  11735. });
  11736. this._shadowMap.onAfterUnbindObservable.add(function () {
  11737. if (!_this.useBlurVarianceShadowMap) {
  11738. return;
  11739. }
  11740. if (!_this._shadowMap2) {
  11741. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11742. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11743. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11744. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11745. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11746. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11747. effect.setTexture("textureSampler", _this._shadowMap);
  11748. });
  11749. _this.blurBoxOffset = 1;
  11750. }
  11751. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11752. });
  11753. // Custom render function
  11754. var renderSubMesh = function (subMesh) {
  11755. var mesh = subMesh.getRenderingMesh();
  11756. var scene = _this._scene;
  11757. var engine = scene.getEngine();
  11758. // Culling
  11759. engine.setState(subMesh.getMaterial().backFaceCulling);
  11760. // Managing instances
  11761. var batch = mesh._getInstancesRenderList(subMesh._id);
  11762. if (batch.mustReturn) {
  11763. return;
  11764. }
  11765. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11766. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11767. engine.enableEffect(_this._effect);
  11768. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11769. var material = subMesh.getMaterial();
  11770. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11771. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11772. if (_this.getLight().needCube()) {
  11773. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11774. }
  11775. // Alpha test
  11776. if (material && material.needAlphaTesting()) {
  11777. var alphaTexture = material.getAlphaTestTexture();
  11778. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11779. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11780. }
  11781. // Bones
  11782. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11783. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11784. }
  11785. if (_this.forceBackFacesOnly) {
  11786. engine.setState(true, 0, false, true);
  11787. }
  11788. // Draw
  11789. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11790. if (_this.forceBackFacesOnly) {
  11791. engine.setState(true, 0, false, false);
  11792. }
  11793. }
  11794. else {
  11795. // Need to reset refresh rate of the shadowMap
  11796. _this._shadowMap.resetRefreshCounter();
  11797. }
  11798. };
  11799. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11800. var index;
  11801. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11802. renderSubMesh(opaqueSubMeshes.data[index]);
  11803. }
  11804. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11805. renderSubMesh(alphaTestSubMeshes.data[index]);
  11806. }
  11807. if (_this._transparencyShadow) {
  11808. for (index = 0; index < transparentSubMeshes.length; index++) {
  11809. renderSubMesh(transparentSubMeshes.data[index]);
  11810. }
  11811. }
  11812. };
  11813. this._shadowMap.onClearObservable.add(function (engine) {
  11814. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11815. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11816. }
  11817. else {
  11818. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11819. }
  11820. });
  11821. }
  11822. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11823. // Static
  11824. get: function () {
  11825. return ShadowGenerator._FILTER_NONE;
  11826. },
  11827. enumerable: true,
  11828. configurable: true
  11829. });
  11830. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11831. get: function () {
  11832. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11833. },
  11834. enumerable: true,
  11835. configurable: true
  11836. });
  11837. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11838. get: function () {
  11839. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11845. get: function () {
  11846. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11847. },
  11848. enumerable: true,
  11849. configurable: true
  11850. });
  11851. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11852. get: function () {
  11853. return this._bias;
  11854. },
  11855. set: function (bias) {
  11856. this._bias = bias;
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11862. get: function () {
  11863. return this._blurBoxOffset;
  11864. },
  11865. set: function (value) {
  11866. var _this = this;
  11867. if (this._blurBoxOffset === value) {
  11868. return;
  11869. }
  11870. this._blurBoxOffset = value;
  11871. if (this._boxBlurPostprocess) {
  11872. this._boxBlurPostprocess.dispose();
  11873. }
  11874. 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);
  11875. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11876. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11877. });
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11883. get: function () {
  11884. return this._filter;
  11885. },
  11886. set: function (value) {
  11887. if (this._filter === value) {
  11888. return;
  11889. }
  11890. this._filter = value;
  11891. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11892. this._shadowMap.anisotropicFilteringLevel = 16;
  11893. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11894. }
  11895. else {
  11896. this._shadowMap.anisotropicFilteringLevel = 1;
  11897. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11898. }
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11904. get: function () {
  11905. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11906. },
  11907. set: function (value) {
  11908. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11914. get: function () {
  11915. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11916. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11917. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11918. },
  11919. set: function (value) {
  11920. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11921. },
  11922. enumerable: true,
  11923. configurable: true
  11924. });
  11925. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11926. get: function () {
  11927. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11928. },
  11929. set: function (value) {
  11930. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11936. var defines = [];
  11937. if (this._useFullFloat) {
  11938. defines.push("#define FULLFLOAT");
  11939. }
  11940. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11941. defines.push("#define VSM");
  11942. }
  11943. if (this.getLight().needCube()) {
  11944. defines.push("#define CUBEMAP");
  11945. }
  11946. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11947. var mesh = subMesh.getMesh();
  11948. var material = subMesh.getMaterial();
  11949. // Alpha test
  11950. if (material && material.needAlphaTesting()) {
  11951. defines.push("#define ALPHATEST");
  11952. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11953. attribs.push(BABYLON.VertexBuffer.UVKind);
  11954. defines.push("#define UV1");
  11955. }
  11956. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11957. var alphaTexture = material.getAlphaTestTexture();
  11958. if (alphaTexture.coordinatesIndex === 1) {
  11959. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11960. defines.push("#define UV2");
  11961. }
  11962. }
  11963. }
  11964. // Bones
  11965. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11966. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11967. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11968. if (mesh.numBoneInfluencers > 4) {
  11969. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11970. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11971. }
  11972. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11973. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11974. }
  11975. else {
  11976. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11977. }
  11978. // Instances
  11979. if (useInstances) {
  11980. defines.push("#define INSTANCES");
  11981. attribs.push("world0");
  11982. attribs.push("world1");
  11983. attribs.push("world2");
  11984. attribs.push("world3");
  11985. }
  11986. // Get correct effect
  11987. var join = defines.join("\n");
  11988. if (this._cachedDefines !== join) {
  11989. this._cachedDefines = join;
  11990. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11991. }
  11992. return this._effect.isReady();
  11993. };
  11994. ShadowGenerator.prototype.getShadowMap = function () {
  11995. return this._shadowMap;
  11996. };
  11997. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11998. if (this._shadowMap2) {
  11999. return this._shadowMap2;
  12000. }
  12001. return this._shadowMap;
  12002. };
  12003. ShadowGenerator.prototype.getLight = function () {
  12004. return this._light;
  12005. };
  12006. // Methods
  12007. ShadowGenerator.prototype.getTransformMatrix = function () {
  12008. var scene = this._scene;
  12009. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12010. return this._transformMatrix;
  12011. }
  12012. this._currentRenderID = scene.getRenderId();
  12013. this._currentFaceIndexCache = this._currentFaceIndex;
  12014. var lightPosition = this._light.position;
  12015. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12016. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12017. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12018. }
  12019. if (this._light.computeTransformedPosition()) {
  12020. lightPosition = this._light.transformedPosition;
  12021. }
  12022. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12023. this._cachedPosition = lightPosition.clone();
  12024. this._cachedDirection = this._lightDirection.clone();
  12025. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12026. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12027. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12028. }
  12029. return this._transformMatrix;
  12030. };
  12031. ShadowGenerator.prototype.getDarkness = function () {
  12032. return this._darkness;
  12033. };
  12034. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12035. if (darkness >= 1.0)
  12036. this._darkness = 1.0;
  12037. else if (darkness <= 0.0)
  12038. this._darkness = 0.0;
  12039. else
  12040. this._darkness = darkness;
  12041. };
  12042. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12043. this._transparencyShadow = hasShadow;
  12044. };
  12045. ShadowGenerator.prototype._packHalf = function (depth) {
  12046. var scale = depth * 255.0;
  12047. var fract = scale - Math.floor(scale);
  12048. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12049. };
  12050. ShadowGenerator.prototype.dispose = function () {
  12051. this._shadowMap.dispose();
  12052. if (this._shadowMap2) {
  12053. this._shadowMap2.dispose();
  12054. }
  12055. if (this._downSamplePostprocess) {
  12056. this._downSamplePostprocess.dispose();
  12057. }
  12058. if (this._boxBlurPostprocess) {
  12059. this._boxBlurPostprocess.dispose();
  12060. }
  12061. };
  12062. ShadowGenerator.prototype.serialize = function () {
  12063. var serializationObject = {};
  12064. serializationObject.lightId = this._light.id;
  12065. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12066. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12067. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12068. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12069. serializationObject.renderList = [];
  12070. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12071. var mesh = this.getShadowMap().renderList[meshIndex];
  12072. serializationObject.renderList.push(mesh.id);
  12073. }
  12074. return serializationObject;
  12075. };
  12076. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12077. //casting to point light, as light is missing the position attr and typescript complains.
  12078. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12079. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12080. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12081. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12082. meshes.forEach(function (mesh) {
  12083. shadowGenerator.getShadowMap().renderList.push(mesh);
  12084. });
  12085. }
  12086. if (parsedShadowGenerator.usePoissonSampling) {
  12087. shadowGenerator.usePoissonSampling = true;
  12088. }
  12089. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12090. shadowGenerator.useVarianceShadowMap = true;
  12091. }
  12092. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12093. shadowGenerator.useBlurVarianceShadowMap = true;
  12094. if (parsedShadowGenerator.blurScale) {
  12095. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12096. }
  12097. if (parsedShadowGenerator.blurBoxOffset) {
  12098. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12099. }
  12100. }
  12101. if (parsedShadowGenerator.bias !== undefined) {
  12102. shadowGenerator.bias = parsedShadowGenerator.bias;
  12103. }
  12104. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12105. return shadowGenerator;
  12106. };
  12107. ShadowGenerator._FILTER_NONE = 0;
  12108. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12109. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12110. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12111. return ShadowGenerator;
  12112. }());
  12113. BABYLON.ShadowGenerator = ShadowGenerator;
  12114. })(BABYLON || (BABYLON = {}));
  12115. var BABYLON;
  12116. (function (BABYLON) {
  12117. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12118. if (boxMin.x > sphereCenter.x + sphereRadius)
  12119. return false;
  12120. if (sphereCenter.x - sphereRadius > boxMax.x)
  12121. return false;
  12122. if (boxMin.y > sphereCenter.y + sphereRadius)
  12123. return false;
  12124. if (sphereCenter.y - sphereRadius > boxMax.y)
  12125. return false;
  12126. if (boxMin.z > sphereCenter.z + sphereRadius)
  12127. return false;
  12128. if (sphereCenter.z - sphereRadius > boxMax.z)
  12129. return false;
  12130. return true;
  12131. };
  12132. var getLowestRoot = (function () {
  12133. var result = { root: 0, found: false };
  12134. return function (a, b, c, maxR) {
  12135. result.root = 0;
  12136. result.found = false;
  12137. var determinant = b * b - 4.0 * a * c;
  12138. if (determinant < 0)
  12139. return result;
  12140. var sqrtD = Math.sqrt(determinant);
  12141. var r1 = (-b - sqrtD) / (2.0 * a);
  12142. var r2 = (-b + sqrtD) / (2.0 * a);
  12143. if (r1 > r2) {
  12144. var temp = r2;
  12145. r2 = r1;
  12146. r1 = temp;
  12147. }
  12148. if (r1 > 0 && r1 < maxR) {
  12149. result.root = r1;
  12150. result.found = true;
  12151. return result;
  12152. }
  12153. if (r2 > 0 && r2 < maxR) {
  12154. result.root = r2;
  12155. result.found = true;
  12156. return result;
  12157. }
  12158. return result;
  12159. };
  12160. })();
  12161. var Collider = (function () {
  12162. function Collider() {
  12163. this.radius = new BABYLON.Vector3(1, 1, 1);
  12164. this.retry = 0;
  12165. this.basePointWorld = BABYLON.Vector3.Zero();
  12166. this.velocityWorld = BABYLON.Vector3.Zero();
  12167. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12168. this._collisionPoint = BABYLON.Vector3.Zero();
  12169. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12170. this._tempVector = BABYLON.Vector3.Zero();
  12171. this._tempVector2 = BABYLON.Vector3.Zero();
  12172. this._tempVector3 = BABYLON.Vector3.Zero();
  12173. this._tempVector4 = BABYLON.Vector3.Zero();
  12174. this._edge = BABYLON.Vector3.Zero();
  12175. this._baseToVertex = BABYLON.Vector3.Zero();
  12176. this._destinationPoint = BABYLON.Vector3.Zero();
  12177. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12178. this._displacementVector = BABYLON.Vector3.Zero();
  12179. }
  12180. // Methods
  12181. Collider.prototype._initialize = function (source, dir, e) {
  12182. this.velocity = dir;
  12183. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12184. this.basePoint = source;
  12185. source.multiplyToRef(this.radius, this.basePointWorld);
  12186. dir.multiplyToRef(this.radius, this.velocityWorld);
  12187. this.velocityWorldLength = this.velocityWorld.length();
  12188. this.epsilon = e;
  12189. this.collisionFound = false;
  12190. };
  12191. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12192. pa.subtractToRef(point, this._tempVector);
  12193. pb.subtractToRef(point, this._tempVector2);
  12194. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12195. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12196. if (d < 0)
  12197. return false;
  12198. pc.subtractToRef(point, this._tempVector3);
  12199. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12200. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12201. if (d < 0)
  12202. return false;
  12203. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12204. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12205. return d >= 0;
  12206. };
  12207. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12208. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12209. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12210. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12211. return false;
  12212. }
  12213. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12214. return false;
  12215. return true;
  12216. };
  12217. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12218. var t0;
  12219. var embeddedInPlane = false;
  12220. //defensive programming, actually not needed.
  12221. if (!trianglePlaneArray) {
  12222. trianglePlaneArray = [];
  12223. }
  12224. if (!trianglePlaneArray[faceIndex]) {
  12225. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12226. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12227. }
  12228. var trianglePlane = trianglePlaneArray[faceIndex];
  12229. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12230. return;
  12231. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12232. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12233. if (normalDotVelocity == 0) {
  12234. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12235. return;
  12236. embeddedInPlane = true;
  12237. t0 = 0;
  12238. }
  12239. else {
  12240. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12241. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12242. if (t0 > t1) {
  12243. var temp = t1;
  12244. t1 = t0;
  12245. t0 = temp;
  12246. }
  12247. if (t0 > 1.0 || t1 < 0.0)
  12248. return;
  12249. if (t0 < 0)
  12250. t0 = 0;
  12251. if (t0 > 1.0)
  12252. t0 = 1.0;
  12253. }
  12254. this._collisionPoint.copyFromFloats(0, 0, 0);
  12255. var found = false;
  12256. var t = 1.0;
  12257. if (!embeddedInPlane) {
  12258. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12259. this.velocity.scaleToRef(t0, this._tempVector);
  12260. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12261. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12262. found = true;
  12263. t = t0;
  12264. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12265. }
  12266. }
  12267. if (!found) {
  12268. var velocitySquaredLength = this.velocity.lengthSquared();
  12269. var a = velocitySquaredLength;
  12270. this.basePoint.subtractToRef(p1, this._tempVector);
  12271. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12272. var c = this._tempVector.lengthSquared() - 1.0;
  12273. var lowestRoot = getLowestRoot(a, b, c, t);
  12274. if (lowestRoot.found) {
  12275. t = lowestRoot.root;
  12276. found = true;
  12277. this._collisionPoint.copyFrom(p1);
  12278. }
  12279. this.basePoint.subtractToRef(p2, this._tempVector);
  12280. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12281. c = this._tempVector.lengthSquared() - 1.0;
  12282. lowestRoot = getLowestRoot(a, b, c, t);
  12283. if (lowestRoot.found) {
  12284. t = lowestRoot.root;
  12285. found = true;
  12286. this._collisionPoint.copyFrom(p2);
  12287. }
  12288. this.basePoint.subtractToRef(p3, this._tempVector);
  12289. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12290. c = this._tempVector.lengthSquared() - 1.0;
  12291. lowestRoot = getLowestRoot(a, b, c, t);
  12292. if (lowestRoot.found) {
  12293. t = lowestRoot.root;
  12294. found = true;
  12295. this._collisionPoint.copyFrom(p3);
  12296. }
  12297. p2.subtractToRef(p1, this._edge);
  12298. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12299. var edgeSquaredLength = this._edge.lengthSquared();
  12300. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12301. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12302. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12303. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12304. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12305. lowestRoot = getLowestRoot(a, b, c, t);
  12306. if (lowestRoot.found) {
  12307. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12308. if (f >= 0.0 && f <= 1.0) {
  12309. t = lowestRoot.root;
  12310. found = true;
  12311. this._edge.scaleInPlace(f);
  12312. p1.addToRef(this._edge, this._collisionPoint);
  12313. }
  12314. }
  12315. p3.subtractToRef(p2, this._edge);
  12316. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12317. edgeSquaredLength = this._edge.lengthSquared();
  12318. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12319. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12320. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12321. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12322. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12323. lowestRoot = getLowestRoot(a, b, c, t);
  12324. if (lowestRoot.found) {
  12325. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12326. if (f >= 0.0 && f <= 1.0) {
  12327. t = lowestRoot.root;
  12328. found = true;
  12329. this._edge.scaleInPlace(f);
  12330. p2.addToRef(this._edge, this._collisionPoint);
  12331. }
  12332. }
  12333. p1.subtractToRef(p3, this._edge);
  12334. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12335. edgeSquaredLength = this._edge.lengthSquared();
  12336. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12337. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12338. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12339. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12340. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12341. lowestRoot = getLowestRoot(a, b, c, t);
  12342. if (lowestRoot.found) {
  12343. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12344. if (f >= 0.0 && f <= 1.0) {
  12345. t = lowestRoot.root;
  12346. found = true;
  12347. this._edge.scaleInPlace(f);
  12348. p3.addToRef(this._edge, this._collisionPoint);
  12349. }
  12350. }
  12351. }
  12352. if (found) {
  12353. var distToCollision = t * this.velocity.length();
  12354. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12355. if (!this.intersectionPoint) {
  12356. this.intersectionPoint = this._collisionPoint.clone();
  12357. }
  12358. else {
  12359. this.intersectionPoint.copyFrom(this._collisionPoint);
  12360. }
  12361. this.nearestDistance = distToCollision;
  12362. this.collisionFound = true;
  12363. }
  12364. }
  12365. };
  12366. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12367. for (var i = indexStart; i < indexEnd; i += 3) {
  12368. var p1 = pts[indices[i] - decal];
  12369. var p2 = pts[indices[i + 1] - decal];
  12370. var p3 = pts[indices[i + 2] - decal];
  12371. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12372. }
  12373. };
  12374. Collider.prototype._getResponse = function (pos, vel) {
  12375. pos.addToRef(vel, this._destinationPoint);
  12376. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12377. this.basePoint.addToRef(vel, pos);
  12378. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12379. this._slidePlaneNormal.normalize();
  12380. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12381. pos.addInPlace(this._displacementVector);
  12382. this.intersectionPoint.addInPlace(this._displacementVector);
  12383. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12384. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12385. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12386. };
  12387. return Collider;
  12388. }());
  12389. BABYLON.Collider = Collider;
  12390. })(BABYLON || (BABYLON = {}));
  12391. var BABYLON;
  12392. (function (BABYLON) {
  12393. //WebWorker code will be inserted to this variable.
  12394. BABYLON.CollisionWorker = "";
  12395. (function (WorkerTaskType) {
  12396. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12397. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12398. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12399. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12400. var WorkerTaskType = BABYLON.WorkerTaskType;
  12401. (function (WorkerReplyType) {
  12402. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12403. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12404. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12405. var WorkerReplyType = BABYLON.WorkerReplyType;
  12406. var CollisionCoordinatorWorker = (function () {
  12407. function CollisionCoordinatorWorker() {
  12408. var _this = this;
  12409. this._scaledPosition = BABYLON.Vector3.Zero();
  12410. this._scaledVelocity = BABYLON.Vector3.Zero();
  12411. this.onMeshUpdated = function (mesh) {
  12412. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12413. };
  12414. this.onGeometryUpdated = function (geometry) {
  12415. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12416. };
  12417. this._afterRender = function () {
  12418. if (!_this._init)
  12419. return;
  12420. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12421. return;
  12422. }
  12423. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12424. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12425. if (_this._runningUpdated > 4) {
  12426. return;
  12427. }
  12428. ++_this._runningUpdated;
  12429. var payload = {
  12430. updatedMeshes: _this._addUpdateMeshesList,
  12431. updatedGeometries: _this._addUpdateGeometriesList,
  12432. removedGeometries: _this._toRemoveGeometryArray,
  12433. removedMeshes: _this._toRemoveMeshesArray
  12434. };
  12435. var message = {
  12436. payload: payload,
  12437. taskType: WorkerTaskType.UPDATE
  12438. };
  12439. var serializable = [];
  12440. for (var id in payload.updatedGeometries) {
  12441. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12442. //prepare transferables
  12443. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12444. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12445. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12446. }
  12447. }
  12448. _this._worker.postMessage(message, serializable);
  12449. _this._addUpdateMeshesList = {};
  12450. _this._addUpdateGeometriesList = {};
  12451. _this._toRemoveGeometryArray = [];
  12452. _this._toRemoveMeshesArray = [];
  12453. };
  12454. this._onMessageFromWorker = function (e) {
  12455. var returnData = e.data;
  12456. if (returnData.error != WorkerReplyType.SUCCESS) {
  12457. //TODO what errors can be returned from the worker?
  12458. BABYLON.Tools.Warn("error returned from worker!");
  12459. return;
  12460. }
  12461. switch (returnData.taskType) {
  12462. case WorkerTaskType.INIT:
  12463. _this._init = true;
  12464. //Update the worked with ALL of the scene's current state
  12465. _this._scene.meshes.forEach(function (mesh) {
  12466. _this.onMeshAdded(mesh);
  12467. });
  12468. _this._scene.getGeometries().forEach(function (geometry) {
  12469. _this.onGeometryAdded(geometry);
  12470. });
  12471. break;
  12472. case WorkerTaskType.UPDATE:
  12473. _this._runningUpdated--;
  12474. break;
  12475. case WorkerTaskType.COLLIDE:
  12476. _this._runningCollisionTask = false;
  12477. var returnPayload = returnData.payload;
  12478. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12479. return;
  12480. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12481. //cleanup
  12482. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12483. break;
  12484. }
  12485. };
  12486. this._collisionsCallbackArray = [];
  12487. this._init = false;
  12488. this._runningUpdated = 0;
  12489. this._runningCollisionTask = false;
  12490. this._addUpdateMeshesList = {};
  12491. this._addUpdateGeometriesList = {};
  12492. this._toRemoveGeometryArray = [];
  12493. this._toRemoveMeshesArray = [];
  12494. }
  12495. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12496. if (!this._init)
  12497. return;
  12498. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12499. return;
  12500. position.divideToRef(collider.radius, this._scaledPosition);
  12501. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12502. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12503. var payload = {
  12504. collider: {
  12505. position: this._scaledPosition.asArray(),
  12506. velocity: this._scaledVelocity.asArray(),
  12507. radius: collider.radius.asArray()
  12508. },
  12509. collisionId: collisionIndex,
  12510. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12511. maximumRetry: maximumRetry
  12512. };
  12513. var message = {
  12514. payload: payload,
  12515. taskType: WorkerTaskType.COLLIDE
  12516. };
  12517. this._worker.postMessage(message);
  12518. };
  12519. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12520. this._scene = scene;
  12521. this._scene.registerAfterRender(this._afterRender);
  12522. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12523. this._worker = new Worker(workerUrl);
  12524. this._worker.onmessage = this._onMessageFromWorker;
  12525. var message = {
  12526. payload: {},
  12527. taskType: WorkerTaskType.INIT
  12528. };
  12529. this._worker.postMessage(message);
  12530. };
  12531. CollisionCoordinatorWorker.prototype.destroy = function () {
  12532. this._scene.unregisterAfterRender(this._afterRender);
  12533. this._worker.terminate();
  12534. };
  12535. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12536. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12537. this.onMeshUpdated(mesh);
  12538. };
  12539. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12540. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12541. };
  12542. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12543. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12544. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12545. this.onGeometryUpdated(geometry);
  12546. };
  12547. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12548. this._toRemoveGeometryArray.push(geometry.id);
  12549. };
  12550. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12551. var submeshes = [];
  12552. if (mesh.subMeshes) {
  12553. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12554. return {
  12555. position: idx,
  12556. verticesStart: sm.verticesStart,
  12557. verticesCount: sm.verticesCount,
  12558. indexStart: sm.indexStart,
  12559. indexCount: sm.indexCount,
  12560. hasMaterial: !!sm.getMaterial(),
  12561. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12562. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12563. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12564. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12565. };
  12566. });
  12567. }
  12568. var geometryId = null;
  12569. if (mesh instanceof BABYLON.Mesh) {
  12570. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12571. }
  12572. else if (mesh instanceof BABYLON.InstancedMesh) {
  12573. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12574. }
  12575. return {
  12576. uniqueId: mesh.uniqueId,
  12577. id: mesh.id,
  12578. name: mesh.name,
  12579. geometryId: geometryId,
  12580. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12581. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12582. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12583. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12584. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12585. subMeshes: submeshes,
  12586. checkCollisions: mesh.checkCollisions
  12587. };
  12588. };
  12589. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12590. return {
  12591. id: geometry.id,
  12592. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12593. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12594. indices: new Int32Array(geometry.getIndices() || []),
  12595. };
  12596. };
  12597. return CollisionCoordinatorWorker;
  12598. }());
  12599. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12600. var CollisionCoordinatorLegacy = (function () {
  12601. function CollisionCoordinatorLegacy() {
  12602. this._scaledPosition = BABYLON.Vector3.Zero();
  12603. this._scaledVelocity = BABYLON.Vector3.Zero();
  12604. this._finalPosition = BABYLON.Vector3.Zero();
  12605. }
  12606. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12607. position.divideToRef(collider.radius, this._scaledPosition);
  12608. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12609. collider.collidedMesh = null;
  12610. collider.retry = 0;
  12611. collider.initialVelocity = this._scaledVelocity;
  12612. collider.initialPosition = this._scaledPosition;
  12613. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12614. this._finalPosition.multiplyInPlace(collider.radius);
  12615. //run the callback
  12616. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12617. };
  12618. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12619. this._scene = scene;
  12620. };
  12621. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12622. //Legacy need no destruction method.
  12623. };
  12624. //No update in legacy mode
  12625. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12626. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12627. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12628. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12629. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12630. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12631. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12632. if (excludedMesh === void 0) { excludedMesh = null; }
  12633. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12634. if (collider.retry >= maximumRetry) {
  12635. finalPosition.copyFrom(position);
  12636. return;
  12637. }
  12638. collider._initialize(position, velocity, closeDistance);
  12639. // Check all meshes
  12640. for (var index = 0; index < this._scene.meshes.length; index++) {
  12641. var mesh = this._scene.meshes[index];
  12642. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12643. mesh._checkCollision(collider);
  12644. }
  12645. }
  12646. if (!collider.collisionFound) {
  12647. position.addToRef(velocity, finalPosition);
  12648. return;
  12649. }
  12650. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12651. collider._getResponse(position, velocity);
  12652. }
  12653. if (velocity.length() <= closeDistance) {
  12654. finalPosition.copyFrom(position);
  12655. return;
  12656. }
  12657. collider.retry++;
  12658. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12659. };
  12660. return CollisionCoordinatorLegacy;
  12661. }());
  12662. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12663. })(BABYLON || (BABYLON = {}));
  12664. var BABYLON;
  12665. (function (BABYLON) {
  12666. var Camera = (function (_super) {
  12667. __extends(Camera, _super);
  12668. function Camera(name, position, scene) {
  12669. _super.call(this, name, scene);
  12670. this.upVector = BABYLON.Vector3.Up();
  12671. this.orthoLeft = null;
  12672. this.orthoRight = null;
  12673. this.orthoBottom = null;
  12674. this.orthoTop = null;
  12675. this.fov = 0.8;
  12676. this.minZ = 1.0;
  12677. this.maxZ = 10000.0;
  12678. this.inertia = 0.9;
  12679. this.mode = Camera.PERSPECTIVE_CAMERA;
  12680. this.isIntermediate = false;
  12681. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12682. this.layerMask = 0x0FFFFFFF;
  12683. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12684. // Camera rig members
  12685. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12686. this._rigCameras = new Array();
  12687. // Cache
  12688. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12689. this._projectionMatrix = new BABYLON.Matrix();
  12690. this._doNotComputeProjectionMatrix = false;
  12691. this._postProcesses = new Array();
  12692. this._transformMatrix = BABYLON.Matrix.Zero();
  12693. this._webvrViewMatrix = BABYLON.Matrix.Identity();
  12694. this._activeMeshes = new BABYLON.SmartArray(256);
  12695. this._globalPosition = BABYLON.Vector3.Zero();
  12696. this._refreshFrustumPlanes = true;
  12697. scene.addCamera(this);
  12698. if (!scene.activeCamera) {
  12699. scene.activeCamera = this;
  12700. }
  12701. this.position = position;
  12702. }
  12703. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12704. get: function () {
  12705. return Camera._PERSPECTIVE_CAMERA;
  12706. },
  12707. enumerable: true,
  12708. configurable: true
  12709. });
  12710. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12711. get: function () {
  12712. return Camera._ORTHOGRAPHIC_CAMERA;
  12713. },
  12714. enumerable: true,
  12715. configurable: true
  12716. });
  12717. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12718. get: function () {
  12719. return Camera._FOVMODE_VERTICAL_FIXED;
  12720. },
  12721. enumerable: true,
  12722. configurable: true
  12723. });
  12724. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12725. get: function () {
  12726. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12727. },
  12728. enumerable: true,
  12729. configurable: true
  12730. });
  12731. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12732. get: function () {
  12733. return Camera._RIG_MODE_NONE;
  12734. },
  12735. enumerable: true,
  12736. configurable: true
  12737. });
  12738. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12739. get: function () {
  12740. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12741. },
  12742. enumerable: true,
  12743. configurable: true
  12744. });
  12745. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12746. get: function () {
  12747. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12748. },
  12749. enumerable: true,
  12750. configurable: true
  12751. });
  12752. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12753. get: function () {
  12754. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12755. },
  12756. enumerable: true,
  12757. configurable: true
  12758. });
  12759. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12760. get: function () {
  12761. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12762. },
  12763. enumerable: true,
  12764. configurable: true
  12765. });
  12766. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12767. get: function () {
  12768. return Camera._RIG_MODE_VR;
  12769. },
  12770. enumerable: true,
  12771. configurable: true
  12772. });
  12773. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12774. get: function () {
  12775. return Camera._RIG_MODE_WEBVR;
  12776. },
  12777. enumerable: true,
  12778. configurable: true
  12779. });
  12780. /**
  12781. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12782. */
  12783. Camera.prototype.toString = function (fullDetails) {
  12784. var ret = "Name: " + this.name;
  12785. ret += ", type: " + this.getTypeName();
  12786. if (this.animations) {
  12787. for (var i = 0; i < this.animations.length; i++) {
  12788. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12789. }
  12790. }
  12791. if (fullDetails) {
  12792. }
  12793. return ret;
  12794. };
  12795. Object.defineProperty(Camera.prototype, "globalPosition", {
  12796. get: function () {
  12797. return this._globalPosition;
  12798. },
  12799. enumerable: true,
  12800. configurable: true
  12801. });
  12802. Camera.prototype.getActiveMeshes = function () {
  12803. return this._activeMeshes;
  12804. };
  12805. Camera.prototype.isActiveMesh = function (mesh) {
  12806. return (this._activeMeshes.indexOf(mesh) !== -1);
  12807. };
  12808. //Cache
  12809. Camera.prototype._initCache = function () {
  12810. _super.prototype._initCache.call(this);
  12811. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12812. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12813. this._cache.mode = undefined;
  12814. this._cache.minZ = undefined;
  12815. this._cache.maxZ = undefined;
  12816. this._cache.fov = undefined;
  12817. this._cache.fovMode = undefined;
  12818. this._cache.aspectRatio = undefined;
  12819. this._cache.orthoLeft = undefined;
  12820. this._cache.orthoRight = undefined;
  12821. this._cache.orthoBottom = undefined;
  12822. this._cache.orthoTop = undefined;
  12823. this._cache.renderWidth = undefined;
  12824. this._cache.renderHeight = undefined;
  12825. };
  12826. Camera.prototype._updateCache = function (ignoreParentClass) {
  12827. if (!ignoreParentClass) {
  12828. _super.prototype._updateCache.call(this);
  12829. }
  12830. var engine = this.getEngine();
  12831. this._cache.position.copyFrom(this.position);
  12832. this._cache.upVector.copyFrom(this.upVector);
  12833. this._cache.mode = this.mode;
  12834. this._cache.minZ = this.minZ;
  12835. this._cache.maxZ = this.maxZ;
  12836. this._cache.fov = this.fov;
  12837. this._cache.fovMode = this.fovMode;
  12838. this._cache.aspectRatio = engine.getAspectRatio(this);
  12839. this._cache.orthoLeft = this.orthoLeft;
  12840. this._cache.orthoRight = this.orthoRight;
  12841. this._cache.orthoBottom = this.orthoBottom;
  12842. this._cache.orthoTop = this.orthoTop;
  12843. this._cache.renderWidth = engine.getRenderWidth();
  12844. this._cache.renderHeight = engine.getRenderHeight();
  12845. };
  12846. Camera.prototype._updateFromScene = function () {
  12847. this.updateCache();
  12848. this.update();
  12849. };
  12850. // Synchronized
  12851. Camera.prototype._isSynchronized = function () {
  12852. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12853. };
  12854. Camera.prototype._isSynchronizedViewMatrix = function () {
  12855. if (!_super.prototype._isSynchronized.call(this))
  12856. return false;
  12857. return this._cache.position.equals(this.position)
  12858. && this._cache.upVector.equals(this.upVector)
  12859. && this.isSynchronizedWithParent();
  12860. };
  12861. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12862. var check = this._cache.mode === this.mode
  12863. && this._cache.minZ === this.minZ
  12864. && this._cache.maxZ === this.maxZ;
  12865. if (!check) {
  12866. return false;
  12867. }
  12868. var engine = this.getEngine();
  12869. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12870. check = this._cache.fov === this.fov
  12871. && this._cache.fovMode === this.fovMode
  12872. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12873. }
  12874. else {
  12875. check = this._cache.orthoLeft === this.orthoLeft
  12876. && this._cache.orthoRight === this.orthoRight
  12877. && this._cache.orthoBottom === this.orthoBottom
  12878. && this._cache.orthoTop === this.orthoTop
  12879. && this._cache.renderWidth === engine.getRenderWidth()
  12880. && this._cache.renderHeight === engine.getRenderHeight();
  12881. }
  12882. return check;
  12883. };
  12884. // Controls
  12885. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12886. };
  12887. Camera.prototype.detachControl = function (element) {
  12888. };
  12889. Camera.prototype.update = function () {
  12890. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12891. this._updateRigCameras();
  12892. }
  12893. this._checkInputs();
  12894. };
  12895. Camera.prototype._checkInputs = function () {
  12896. };
  12897. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12898. // invalidate framebuffer
  12899. if (this._postProcesses.length > 0) {
  12900. this._postProcesses[0].markTextureDirty();
  12901. }
  12902. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12903. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12904. var cam = this._rigCameras[i];
  12905. var rigPostProcess = cam._rigPostProcess;
  12906. // for VR rig, there does not have to be a post process
  12907. if (rigPostProcess) {
  12908. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12909. if (isPass) {
  12910. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12911. cam.isIntermediate = this._postProcesses.length === 0;
  12912. }
  12913. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12914. rigPostProcess.markTextureDirty();
  12915. }
  12916. else {
  12917. cam._postProcesses = this._postProcesses.slice(0);
  12918. }
  12919. }
  12920. };
  12921. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12922. if (insertAt === void 0) { insertAt = null; }
  12923. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12924. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12925. return 0;
  12926. }
  12927. if (insertAt == null || insertAt < 0) {
  12928. this._postProcesses.push(postProcess);
  12929. }
  12930. else {
  12931. this._postProcesses.splice(insertAt, 0, postProcess);
  12932. }
  12933. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12934. return this._postProcesses.indexOf(postProcess);
  12935. };
  12936. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12937. if (atIndices === void 0) { atIndices = null; }
  12938. var result = [];
  12939. var i;
  12940. var index;
  12941. if (!atIndices) {
  12942. var idx = this._postProcesses.indexOf(postProcess);
  12943. if (idx !== -1) {
  12944. this._postProcesses.splice(idx, 1);
  12945. }
  12946. }
  12947. else {
  12948. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12949. // iterate descending, so can just splice as we go
  12950. for (i = atIndices.length - 1; i >= 0; i--) {
  12951. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12952. result.push(i);
  12953. continue;
  12954. }
  12955. this._postProcesses.splice(index, 1);
  12956. }
  12957. }
  12958. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12959. return result;
  12960. };
  12961. Camera.prototype.getWorldMatrix = function () {
  12962. if (!this._worldMatrix) {
  12963. this._worldMatrix = BABYLON.Matrix.Identity();
  12964. }
  12965. var viewMatrix = this.getViewMatrix();
  12966. viewMatrix.invertToRef(this._worldMatrix);
  12967. return this._worldMatrix;
  12968. };
  12969. Camera.prototype._getViewMatrix = function () {
  12970. return BABYLON.Matrix.Identity();
  12971. };
  12972. Camera.prototype.getViewMatrix = function (force) {
  12973. this._computedViewMatrix = this._computeViewMatrix(force);
  12974. if (!force && this._isSynchronizedViewMatrix()) {
  12975. return this._computedViewMatrix;
  12976. }
  12977. this._refreshFrustumPlanes = true;
  12978. if (!this.parent || !this.parent.getWorldMatrix) {
  12979. this._globalPosition.copyFrom(this.position);
  12980. }
  12981. else {
  12982. if (!this._worldMatrix) {
  12983. this._worldMatrix = BABYLON.Matrix.Identity();
  12984. }
  12985. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12986. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12987. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12988. this._computedViewMatrix.invert();
  12989. this._markSyncedWithParent();
  12990. }
  12991. this._currentRenderId = this.getScene().getRenderId();
  12992. return this._computedViewMatrix;
  12993. };
  12994. Camera.prototype._computeViewMatrix = function (force) {
  12995. if (!force && this._isSynchronizedViewMatrix()) {
  12996. return this._computedViewMatrix;
  12997. }
  12998. this._computedViewMatrix = this._getViewMatrix();
  12999. this._currentRenderId = this.getScene().getRenderId();
  13000. return this._computedViewMatrix;
  13001. };
  13002. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13003. this._doNotComputeProjectionMatrix = true;
  13004. if (projection !== undefined) {
  13005. this._projectionMatrix = projection;
  13006. }
  13007. };
  13008. ;
  13009. Camera.prototype.unfreezeProjectionMatrix = function () {
  13010. this._doNotComputeProjectionMatrix = false;
  13011. };
  13012. ;
  13013. Camera.prototype.getProjectionMatrix = function (force) {
  13014. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13015. return this._projectionMatrix;
  13016. }
  13017. this._refreshFrustumPlanes = true;
  13018. var engine = this.getEngine();
  13019. var scene = this.getScene();
  13020. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13021. if (this.minZ <= 0) {
  13022. this.minZ = 0.1;
  13023. }
  13024. if (scene.useRightHandedSystem) {
  13025. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13026. }
  13027. else {
  13028. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13029. }
  13030. return this._projectionMatrix;
  13031. }
  13032. var halfWidth = engine.getRenderWidth() / 2.0;
  13033. var halfHeight = engine.getRenderHeight() / 2.0;
  13034. if (scene.useRightHandedSystem) {
  13035. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13036. }
  13037. else {
  13038. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13039. }
  13040. return this._projectionMatrix;
  13041. };
  13042. Camera.prototype.getTranformationMatrix = function () {
  13043. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13044. return this._transformMatrix;
  13045. };
  13046. Camera.prototype.updateFrustumPlanes = function () {
  13047. if (!this._refreshFrustumPlanes) {
  13048. return;
  13049. }
  13050. this.getTranformationMatrix();
  13051. if (!this._frustumPlanes) {
  13052. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13053. }
  13054. else {
  13055. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13056. }
  13057. this._refreshFrustumPlanes = false;
  13058. };
  13059. Camera.prototype.isInFrustum = function (target) {
  13060. this.updateFrustumPlanes();
  13061. return target.isInFrustum(this._frustumPlanes);
  13062. };
  13063. Camera.prototype.isCompletelyInFrustum = function (target) {
  13064. this.updateFrustumPlanes();
  13065. return target.isCompletelyInFrustum(this._frustumPlanes);
  13066. };
  13067. Camera.prototype.dispose = function () {
  13068. // Animations
  13069. this.getScene().stopAnimation(this);
  13070. // Remove from scene
  13071. this.getScene().removeCamera(this);
  13072. while (this._rigCameras.length > 0) {
  13073. this._rigCameras.pop().dispose();
  13074. }
  13075. // Postprocesses
  13076. for (var i = 0; i < this._postProcesses.length; ++i) {
  13077. this._postProcesses[i].dispose(this);
  13078. }
  13079. _super.prototype.dispose.call(this);
  13080. };
  13081. // ---- Camera rigs section ----
  13082. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13083. while (this._rigCameras.length > 0) {
  13084. this._rigCameras.pop().dispose();
  13085. }
  13086. this.cameraRigMode = mode;
  13087. this._cameraRigParams = {};
  13088. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13089. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13090. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13091. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13092. // create the rig cameras, unless none
  13093. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13094. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13095. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13096. }
  13097. switch (this.cameraRigMode) {
  13098. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13099. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13100. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13101. break;
  13102. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13103. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13104. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13105. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13106. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13107. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13108. break;
  13109. case Camera.RIG_MODE_VR:
  13110. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13111. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13112. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13113. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13114. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13115. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13116. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13117. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13118. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13119. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13120. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13121. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13122. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13123. if (metrics.compensateDistortion) {
  13124. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13125. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13126. }
  13127. break;
  13128. case Camera.RIG_MODE_WEBVR:
  13129. if (rigParams.vrDisplay) {
  13130. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13131. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13132. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13133. this._rigCameras[0].setCameraRigParameter("left", true);
  13134. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13135. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13136. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13137. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13138. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13139. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13140. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13141. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13142. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13143. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13144. }
  13145. break;
  13146. }
  13147. this._cascadePostProcessesToRigCams();
  13148. this.
  13149. update();
  13150. };
  13151. Camera.prototype._getVRProjectionMatrix = function () {
  13152. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13153. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13154. return this._projectionMatrix;
  13155. };
  13156. Camera.prototype._getWebVRProjectionMatrix = function () {
  13157. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13158. //babylon compatible matrix
  13159. [8, 9, 10, 11].forEach(function (num) {
  13160. projectionArray[num] *= -1;
  13161. });
  13162. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13163. return this._projectionMatrix;
  13164. };
  13165. //Can be used, but we'll use the free camera's view matrix calculation
  13166. Camera.prototype._getWebVRViewMatrix = function () {
  13167. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13168. //babylon compatible matrix
  13169. [8, 9, 10, 11].forEach(function (num) {
  13170. projectionArray[num] *= -1;
  13171. });
  13172. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13173. return this._webvrViewMatrix;
  13174. };
  13175. Camera.prototype.setCameraRigParameter = function (name, value) {
  13176. if (!this._cameraRigParams) {
  13177. this._cameraRigParams = {};
  13178. }
  13179. this._cameraRigParams[name] = value;
  13180. //provisionnally:
  13181. if (name === "interaxialDistance") {
  13182. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13183. }
  13184. };
  13185. /**
  13186. * needs to be overridden by children so sub has required properties to be copied
  13187. */
  13188. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13189. return null;
  13190. };
  13191. /**
  13192. * May need to be overridden by children
  13193. */
  13194. Camera.prototype._updateRigCameras = function () {
  13195. for (var i = 0; i < this._rigCameras.length; i++) {
  13196. this._rigCameras[i].minZ = this.minZ;
  13197. this._rigCameras[i].maxZ = this.maxZ;
  13198. this._rigCameras[i].fov = this.fov;
  13199. }
  13200. // only update viewport when ANAGLYPH
  13201. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13202. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13203. }
  13204. };
  13205. Camera.prototype._setupInputs = function () {
  13206. };
  13207. Camera.prototype.serialize = function () {
  13208. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13209. // Type
  13210. serializationObject.type = this.getTypeName();
  13211. // Parent
  13212. if (this.parent) {
  13213. serializationObject.parentId = this.parent.id;
  13214. }
  13215. if (this.inputs) {
  13216. this.inputs.serialize(serializationObject);
  13217. }
  13218. // Animations
  13219. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13220. serializationObject.ranges = this.serializeAnimationRanges();
  13221. return serializationObject;
  13222. };
  13223. Camera.prototype.getTypeName = function () {
  13224. return "Camera";
  13225. };
  13226. Camera.prototype.clone = function (name) {
  13227. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13228. };
  13229. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13230. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13231. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13232. switch (type) {
  13233. case "ArcRotateCamera":
  13234. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13235. case "DeviceOrientationCamera":
  13236. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13237. case "FollowCamera":
  13238. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13239. case "ArcFollowCamera":
  13240. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13241. case "GamepadCamera":
  13242. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13243. case "TouchCamera":
  13244. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13245. case "VirtualJoysticksCamera":
  13246. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13247. case "WebVRFreeCamera":
  13248. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13249. case "VRDeviceOrientationFreeCamera":
  13250. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13251. case "AnaglyphArcRotateCamera":
  13252. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13253. case "AnaglyphFreeCamera":
  13254. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13255. case "AnaglyphGamepadCamera":
  13256. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13257. case "AnaglyphUniversalCamera":
  13258. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13259. case "StereoscopicArcRotateCamera":
  13260. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13261. case "StereoscopicFreeCamera":
  13262. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13263. case "StereoscopicGamepadCamera":
  13264. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13265. case "StereoscopicUniversalCamera":
  13266. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13267. case "FreeCamera":
  13268. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13269. default:
  13270. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13271. }
  13272. };
  13273. Camera.Parse = function (parsedCamera, scene) {
  13274. var type = parsedCamera.type;
  13275. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13276. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13277. // Parent
  13278. if (parsedCamera.parentId) {
  13279. camera._waitingParentId = parsedCamera.parentId;
  13280. }
  13281. //If camera has an input manager, let it parse inputs settings
  13282. if (camera.inputs) {
  13283. camera.inputs.parse(parsedCamera);
  13284. camera._setupInputs();
  13285. }
  13286. // Target
  13287. if (parsedCamera.target) {
  13288. if (camera.setTarget) {
  13289. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13290. }
  13291. }
  13292. // Apply 3d rig, when found
  13293. if (parsedCamera.cameraRigMode) {
  13294. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13295. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13296. }
  13297. // Animations
  13298. if (parsedCamera.animations) {
  13299. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13300. var parsedAnimation = parsedCamera.animations[animationIndex];
  13301. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13302. }
  13303. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13304. }
  13305. if (parsedCamera.autoAnimate) {
  13306. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13307. }
  13308. return camera;
  13309. };
  13310. // Statics
  13311. Camera._PERSPECTIVE_CAMERA = 0;
  13312. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13313. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13314. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13315. Camera._RIG_MODE_NONE = 0;
  13316. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13317. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13318. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13319. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13320. Camera._RIG_MODE_VR = 20;
  13321. Camera._RIG_MODE_WEBVR = 21;
  13322. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13323. __decorate([
  13324. BABYLON.serializeAsVector3()
  13325. ], Camera.prototype, "position", void 0);
  13326. __decorate([
  13327. BABYLON.serializeAsVector3()
  13328. ], Camera.prototype, "upVector", void 0);
  13329. __decorate([
  13330. BABYLON.serialize()
  13331. ], Camera.prototype, "orthoLeft", void 0);
  13332. __decorate([
  13333. BABYLON.serialize()
  13334. ], Camera.prototype, "orthoRight", void 0);
  13335. __decorate([
  13336. BABYLON.serialize()
  13337. ], Camera.prototype, "orthoBottom", void 0);
  13338. __decorate([
  13339. BABYLON.serialize()
  13340. ], Camera.prototype, "orthoTop", void 0);
  13341. __decorate([
  13342. BABYLON.serialize()
  13343. ], Camera.prototype, "fov", void 0);
  13344. __decorate([
  13345. BABYLON.serialize()
  13346. ], Camera.prototype, "minZ", void 0);
  13347. __decorate([
  13348. BABYLON.serialize()
  13349. ], Camera.prototype, "maxZ", void 0);
  13350. __decorate([
  13351. BABYLON.serialize()
  13352. ], Camera.prototype, "inertia", void 0);
  13353. __decorate([
  13354. BABYLON.serialize()
  13355. ], Camera.prototype, "mode", void 0);
  13356. __decorate([
  13357. BABYLON.serialize()
  13358. ], Camera.prototype, "layerMask", void 0);
  13359. __decorate([
  13360. BABYLON.serialize()
  13361. ], Camera.prototype, "fovMode", void 0);
  13362. __decorate([
  13363. BABYLON.serialize()
  13364. ], Camera.prototype, "cameraRigMode", void 0);
  13365. __decorate([
  13366. BABYLON.serialize()
  13367. ], Camera.prototype, "interaxialDistance", void 0);
  13368. __decorate([
  13369. BABYLON.serialize()
  13370. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13371. return Camera;
  13372. }(BABYLON.Node));
  13373. BABYLON.Camera = Camera;
  13374. })(BABYLON || (BABYLON = {}));
  13375. var BABYLON;
  13376. (function (BABYLON) {
  13377. BABYLON.CameraInputTypes = {};
  13378. var CameraInputsManager = (function () {
  13379. function CameraInputsManager(camera) {
  13380. this.attached = {};
  13381. this.camera = camera;
  13382. this.checkInputs = function () { };
  13383. }
  13384. CameraInputsManager.prototype.add = function (input) {
  13385. var type = input.getSimpleName();
  13386. if (this.attached[type]) {
  13387. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13388. return;
  13389. }
  13390. this.attached[type] = input;
  13391. input.camera = this.camera;
  13392. //for checkInputs, we are dynamically creating a function
  13393. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13394. if (input.checkInputs) {
  13395. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13396. }
  13397. if (this.attachedElement) {
  13398. input.attachControl(this.attachedElement);
  13399. }
  13400. };
  13401. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13402. for (var cam in this.attached) {
  13403. var input = this.attached[cam];
  13404. if (input === inputToRemove) {
  13405. input.detachControl(this.attachedElement);
  13406. delete this.attached[cam];
  13407. this.rebuildInputCheck();
  13408. }
  13409. }
  13410. };
  13411. CameraInputsManager.prototype.removeByType = function (inputType) {
  13412. for (var cam in this.attached) {
  13413. var input = this.attached[cam];
  13414. if (input.getTypeName() === inputType) {
  13415. input.detachControl(this.attachedElement);
  13416. delete this.attached[cam];
  13417. this.rebuildInputCheck();
  13418. }
  13419. }
  13420. };
  13421. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13422. var current = this.checkInputs;
  13423. return function () {
  13424. current();
  13425. fn();
  13426. };
  13427. };
  13428. CameraInputsManager.prototype.attachInput = function (input) {
  13429. input.attachControl(this.attachedElement, this.noPreventDefault);
  13430. };
  13431. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13432. if (this.attachedElement) {
  13433. return;
  13434. }
  13435. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13436. this.attachedElement = element;
  13437. this.noPreventDefault = noPreventDefault;
  13438. for (var cam in this.attached) {
  13439. var input = this.attached[cam];
  13440. this.attached[cam].attachControl(element, noPreventDefault);
  13441. }
  13442. };
  13443. CameraInputsManager.prototype.detachElement = function (element) {
  13444. if (this.attachedElement !== element) {
  13445. return;
  13446. }
  13447. for (var cam in this.attached) {
  13448. var input = this.attached[cam];
  13449. this.attached[cam].detachControl(element);
  13450. }
  13451. this.attachedElement = null;
  13452. };
  13453. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13454. this.checkInputs = function () { };
  13455. for (var cam in this.attached) {
  13456. var input = this.attached[cam];
  13457. if (input.checkInputs) {
  13458. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13459. }
  13460. }
  13461. };
  13462. CameraInputsManager.prototype.clear = function () {
  13463. if (this.attachedElement) {
  13464. this.detachElement(this.attachedElement);
  13465. }
  13466. this.attached = {};
  13467. this.attachedElement = null;
  13468. this.checkInputs = function () { };
  13469. };
  13470. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13471. var inputs = {};
  13472. for (var cam in this.attached) {
  13473. var input = this.attached[cam];
  13474. var res = BABYLON.SerializationHelper.Serialize(input);
  13475. inputs[input.getTypeName()] = res;
  13476. }
  13477. serializedCamera.inputsmgr = inputs;
  13478. };
  13479. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13480. var parsedInputs = parsedCamera.inputsmgr;
  13481. if (parsedInputs) {
  13482. this.clear();
  13483. for (var n in parsedInputs) {
  13484. var construct = BABYLON.CameraInputTypes[n];
  13485. if (construct) {
  13486. var parsedinput = parsedInputs[n];
  13487. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13488. this.add(input);
  13489. }
  13490. }
  13491. }
  13492. else {
  13493. //2016-03-08 this part is for managing backward compatibility
  13494. for (var n in this.attached) {
  13495. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13496. if (construct) {
  13497. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13498. this.remove(this.attached[n]);
  13499. this.add(input);
  13500. }
  13501. }
  13502. }
  13503. };
  13504. return CameraInputsManager;
  13505. }());
  13506. BABYLON.CameraInputsManager = CameraInputsManager;
  13507. })(BABYLON || (BABYLON = {}));
  13508. var BABYLON;
  13509. (function (BABYLON) {
  13510. var FreeCameraMouseInput = (function () {
  13511. function FreeCameraMouseInput(touchEnabled) {
  13512. if (touchEnabled === void 0) { touchEnabled = true; }
  13513. this.touchEnabled = touchEnabled;
  13514. this.buttons = [0, 1, 2];
  13515. this.angularSensibility = 2000.0;
  13516. }
  13517. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13518. var _this = this;
  13519. var engine = this.camera.getEngine();
  13520. if (!this._pointerInput) {
  13521. this._pointerInput = function (p, s) {
  13522. var evt = p.event;
  13523. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13524. return;
  13525. }
  13526. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  13527. return;
  13528. }
  13529. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13530. try {
  13531. evt.srcElement.setPointerCapture(evt.pointerId);
  13532. }
  13533. catch (e) {
  13534. }
  13535. _this.previousPosition = {
  13536. x: evt.clientX,
  13537. y: evt.clientY
  13538. };
  13539. if (!noPreventDefault) {
  13540. evt.preventDefault();
  13541. element.focus();
  13542. }
  13543. }
  13544. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13545. try {
  13546. evt.srcElement.releasePointerCapture(evt.pointerId);
  13547. }
  13548. catch (e) {
  13549. }
  13550. _this.previousPosition = null;
  13551. if (!noPreventDefault) {
  13552. evt.preventDefault();
  13553. }
  13554. }
  13555. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13556. if (!_this.previousPosition || engine.isPointerLock) {
  13557. return;
  13558. }
  13559. var offsetX = evt.clientX - _this.previousPosition.x;
  13560. var offsetY = evt.clientY - _this.previousPosition.y;
  13561. if (_this.camera.getScene().useRightHandedSystem) {
  13562. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13563. }
  13564. else {
  13565. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13566. }
  13567. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13568. _this.previousPosition = {
  13569. x: evt.clientX,
  13570. y: evt.clientY
  13571. };
  13572. if (!noPreventDefault) {
  13573. evt.preventDefault();
  13574. }
  13575. }
  13576. };
  13577. }
  13578. this._onMouseMove = function (evt) {
  13579. if (!engine.isPointerLock) {
  13580. return;
  13581. }
  13582. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13583. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13584. if (_this.camera.getScene().useRightHandedSystem) {
  13585. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13586. }
  13587. else {
  13588. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13589. }
  13590. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13591. _this.previousPosition = null;
  13592. if (!noPreventDefault) {
  13593. evt.preventDefault();
  13594. }
  13595. };
  13596. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13597. element.addEventListener("mousemove", this._onMouseMove, false);
  13598. };
  13599. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13600. if (this._observer && element) {
  13601. this.camera.getScene().onPointerObservable.remove(this._observer);
  13602. element.removeEventListener("mousemove", this._onMouseMove);
  13603. this._observer = null;
  13604. this._onMouseMove = null;
  13605. this.previousPosition = null;
  13606. }
  13607. };
  13608. FreeCameraMouseInput.prototype.getTypeName = function () {
  13609. return "FreeCameraMouseInput";
  13610. };
  13611. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13612. return "mouse";
  13613. };
  13614. __decorate([
  13615. BABYLON.serialize()
  13616. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  13617. __decorate([
  13618. BABYLON.serialize()
  13619. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13620. return FreeCameraMouseInput;
  13621. }());
  13622. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13623. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13624. })(BABYLON || (BABYLON = {}));
  13625. var BABYLON;
  13626. (function (BABYLON) {
  13627. var FreeCameraKeyboardMoveInput = (function () {
  13628. function FreeCameraKeyboardMoveInput() {
  13629. this._keys = [];
  13630. this.keysUp = [38];
  13631. this.keysDown = [40];
  13632. this.keysLeft = [37];
  13633. this.keysRight = [39];
  13634. }
  13635. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13636. var _this = this;
  13637. if (!this._onKeyDown) {
  13638. element.tabIndex = 1;
  13639. this._onKeyDown = function (evt) {
  13640. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13641. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13642. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13643. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13644. var index = _this._keys.indexOf(evt.keyCode);
  13645. if (index === -1) {
  13646. _this._keys.push(evt.keyCode);
  13647. }
  13648. if (!noPreventDefault) {
  13649. evt.preventDefault();
  13650. }
  13651. }
  13652. };
  13653. this._onKeyUp = function (evt) {
  13654. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13655. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13656. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13657. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13658. var index = _this._keys.indexOf(evt.keyCode);
  13659. if (index >= 0) {
  13660. _this._keys.splice(index, 1);
  13661. }
  13662. if (!noPreventDefault) {
  13663. evt.preventDefault();
  13664. }
  13665. }
  13666. };
  13667. element.addEventListener("keydown", this._onKeyDown, false);
  13668. element.addEventListener("keyup", this._onKeyUp, false);
  13669. BABYLON.Tools.RegisterTopRootEvents([
  13670. { name: "blur", handler: this._onLostFocus }
  13671. ]);
  13672. }
  13673. };
  13674. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13675. if (this._onKeyDown) {
  13676. element.removeEventListener("keydown", this._onKeyDown);
  13677. element.removeEventListener("keyup", this._onKeyUp);
  13678. BABYLON.Tools.UnregisterTopRootEvents([
  13679. { name: "blur", handler: this._onLostFocus }
  13680. ]);
  13681. this._keys = [];
  13682. this._onKeyDown = null;
  13683. this._onKeyUp = null;
  13684. }
  13685. };
  13686. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13687. if (this._onKeyDown) {
  13688. var camera = this.camera;
  13689. // Keyboard
  13690. for (var index = 0; index < this._keys.length; index++) {
  13691. var keyCode = this._keys[index];
  13692. var speed = camera._computeLocalCameraSpeed();
  13693. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13694. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13695. }
  13696. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13697. camera._localDirection.copyFromFloats(0, 0, speed);
  13698. }
  13699. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13700. camera._localDirection.copyFromFloats(speed, 0, 0);
  13701. }
  13702. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13703. camera._localDirection.copyFromFloats(0, 0, -speed);
  13704. }
  13705. if (camera.getScene().useRightHandedSystem) {
  13706. camera._localDirection.z *= -1;
  13707. }
  13708. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13709. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13710. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13711. }
  13712. }
  13713. };
  13714. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13715. return "FreeCameraKeyboardMoveInput";
  13716. };
  13717. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13718. this._keys = [];
  13719. };
  13720. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13721. return "keyboard";
  13722. };
  13723. __decorate([
  13724. BABYLON.serialize()
  13725. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13726. __decorate([
  13727. BABYLON.serialize()
  13728. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13729. __decorate([
  13730. BABYLON.serialize()
  13731. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13732. __decorate([
  13733. BABYLON.serialize()
  13734. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13735. return FreeCameraKeyboardMoveInput;
  13736. }());
  13737. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13738. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13739. })(BABYLON || (BABYLON = {}));
  13740. var BABYLON;
  13741. (function (BABYLON) {
  13742. var FreeCameraTouchInput = (function () {
  13743. function FreeCameraTouchInput() {
  13744. this._offsetX = null;
  13745. this._offsetY = null;
  13746. this._pointerCount = 0;
  13747. this._pointerPressed = [];
  13748. this.touchAngularSensibility = 200000.0;
  13749. this.touchMoveSensibility = 250.0;
  13750. }
  13751. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13752. var _this = this;
  13753. var previousPosition;
  13754. if (this._pointerInput === undefined) {
  13755. this._onLostFocus = function (evt) {
  13756. _this._offsetX = null;
  13757. _this._offsetY = null;
  13758. };
  13759. this._pointerInput = function (p, s) {
  13760. var evt = p.event;
  13761. if (evt.pointerType === "mouse") {
  13762. return;
  13763. }
  13764. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13765. if (!noPreventDefault) {
  13766. evt.preventDefault();
  13767. }
  13768. _this._pointerPressed.push(evt.pointerId);
  13769. if (_this._pointerPressed.length !== 1) {
  13770. return;
  13771. }
  13772. previousPosition = {
  13773. x: evt.clientX,
  13774. y: evt.clientY
  13775. };
  13776. }
  13777. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13778. if (!noPreventDefault) {
  13779. evt.preventDefault();
  13780. }
  13781. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13782. if (index === -1) {
  13783. return;
  13784. }
  13785. _this._pointerPressed.splice(index, 1);
  13786. if (index != 0) {
  13787. return;
  13788. }
  13789. previousPosition = null;
  13790. _this._offsetX = null;
  13791. _this._offsetY = null;
  13792. }
  13793. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13794. if (!noPreventDefault) {
  13795. evt.preventDefault();
  13796. }
  13797. if (!previousPosition) {
  13798. return;
  13799. }
  13800. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13801. if (index != 0) {
  13802. return;
  13803. }
  13804. _this._offsetX = evt.clientX - previousPosition.x;
  13805. _this._offsetY = -(evt.clientY - previousPosition.y);
  13806. }
  13807. };
  13808. }
  13809. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13810. element.addEventListener("blur", this._onLostFocus);
  13811. };
  13812. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13813. if (this._pointerInput && element) {
  13814. this.camera.getScene().onPointerObservable.remove(this._observer);
  13815. this._observer = null;
  13816. element.removeEventListener("blur", this._onLostFocus);
  13817. this._onLostFocus = null;
  13818. this._pointerPressed = [];
  13819. this._offsetX = null;
  13820. this._offsetY = null;
  13821. this._pointerCount = 0;
  13822. }
  13823. };
  13824. FreeCameraTouchInput.prototype.checkInputs = function () {
  13825. if (this._offsetX) {
  13826. var camera = this.camera;
  13827. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13828. if (this._pointerPressed.length > 1) {
  13829. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13830. }
  13831. else {
  13832. var speed = camera._computeLocalCameraSpeed();
  13833. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13834. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13835. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13836. }
  13837. }
  13838. };
  13839. FreeCameraTouchInput.prototype.getTypeName = function () {
  13840. return "FreeCameraTouchInput";
  13841. };
  13842. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13843. return "touch";
  13844. };
  13845. __decorate([
  13846. BABYLON.serialize()
  13847. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13848. __decorate([
  13849. BABYLON.serialize()
  13850. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13851. return FreeCameraTouchInput;
  13852. }());
  13853. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13854. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13855. })(BABYLON || (BABYLON = {}));
  13856. var BABYLON;
  13857. (function (BABYLON) {
  13858. var FreeCameraDeviceOrientationInput = (function () {
  13859. function FreeCameraDeviceOrientationInput() {
  13860. var _this = this;
  13861. this._screenOrientationAngle = 0;
  13862. this._screenQuaternion = new BABYLON.Quaternion();
  13863. this._alpha = 0;
  13864. this._beta = 0;
  13865. this._gamma = 0;
  13866. this._orientationChanged = function () {
  13867. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13868. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13869. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13870. };
  13871. this._deviceOrientation = function (evt) {
  13872. _this._alpha = evt.alpha;
  13873. _this._beta = evt.beta;
  13874. _this._gamma = evt.gamma;
  13875. };
  13876. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13877. this._orientationChanged();
  13878. }
  13879. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13880. get: function () {
  13881. return this._camera;
  13882. },
  13883. set: function (camera) {
  13884. this._camera = camera;
  13885. if (!this._camera.rotationQuaternion)
  13886. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13887. },
  13888. enumerable: true,
  13889. configurable: true
  13890. });
  13891. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13892. window.addEventListener("orientationchange", this._orientationChanged);
  13893. window.addEventListener("deviceorientation", this._deviceOrientation);
  13894. //In certain cases, the attach control is called AFTER orientation was changed,
  13895. //So this is needed.
  13896. this._orientationChanged();
  13897. };
  13898. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13899. window.removeEventListener("orientationchange", this._orientationChanged);
  13900. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13901. };
  13902. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13903. //if no device orientation provided, don't update the rotation.
  13904. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  13905. if (!this._alpha)
  13906. return;
  13907. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13908. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13909. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13910. //Mirror on XY Plane
  13911. this._camera.rotationQuaternion.z *= -1;
  13912. this._camera.rotationQuaternion.w *= -1;
  13913. };
  13914. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13915. return "FreeCameraDeviceOrientationInput";
  13916. };
  13917. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13918. return "deviceOrientation";
  13919. };
  13920. return FreeCameraDeviceOrientationInput;
  13921. }());
  13922. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13923. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13924. })(BABYLON || (BABYLON = {}));
  13925. var BABYLON;
  13926. (function (BABYLON) {
  13927. var FreeCameraGamepadInput = (function () {
  13928. function FreeCameraGamepadInput() {
  13929. this.gamepadAngularSensibility = 200;
  13930. this.gamepadMoveSensibility = 40;
  13931. }
  13932. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13933. var _this = this;
  13934. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13935. };
  13936. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13937. if (this._gamepads) {
  13938. this._gamepads.dispose();
  13939. }
  13940. this.gamepad = null;
  13941. };
  13942. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13943. if (this.gamepad) {
  13944. var camera = this.camera;
  13945. var LSValues = this.gamepad.leftStick;
  13946. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13947. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13948. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13949. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13950. var RSValues = this.gamepad.rightStick;
  13951. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13952. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13953. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13954. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13955. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13956. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13957. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13958. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13959. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13960. }
  13961. };
  13962. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13963. // Only the first gamepad can control the camera
  13964. if (gamepad.index === 0) {
  13965. this.gamepad = gamepad;
  13966. }
  13967. };
  13968. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13969. return "FreeCameraGamepadInput";
  13970. };
  13971. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13972. return "gamepad";
  13973. };
  13974. __decorate([
  13975. BABYLON.serialize()
  13976. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13977. __decorate([
  13978. BABYLON.serialize()
  13979. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13980. return FreeCameraGamepadInput;
  13981. }());
  13982. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13983. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13984. })(BABYLON || (BABYLON = {}));
  13985. var BABYLON;
  13986. (function (BABYLON) {
  13987. var ArcRotateCameraKeyboardMoveInput = (function () {
  13988. function ArcRotateCameraKeyboardMoveInput() {
  13989. this._keys = [];
  13990. this.keysUp = [38];
  13991. this.keysDown = [40];
  13992. this.keysLeft = [37];
  13993. this.keysRight = [39];
  13994. }
  13995. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13996. var _this = this;
  13997. element.tabIndex = 1;
  13998. this._onKeyDown = function (evt) {
  13999. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14000. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14001. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14002. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14003. var index = _this._keys.indexOf(evt.keyCode);
  14004. if (index === -1) {
  14005. _this._keys.push(evt.keyCode);
  14006. }
  14007. if (evt.preventDefault) {
  14008. if (!noPreventDefault) {
  14009. evt.preventDefault();
  14010. }
  14011. }
  14012. }
  14013. };
  14014. this._onKeyUp = function (evt) {
  14015. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14016. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14017. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14018. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14019. var index = _this._keys.indexOf(evt.keyCode);
  14020. if (index >= 0) {
  14021. _this._keys.splice(index, 1);
  14022. }
  14023. if (evt.preventDefault) {
  14024. if (!noPreventDefault) {
  14025. evt.preventDefault();
  14026. }
  14027. }
  14028. }
  14029. };
  14030. this._onLostFocus = function () {
  14031. _this._keys = [];
  14032. };
  14033. element.addEventListener("keydown", this._onKeyDown, false);
  14034. element.addEventListener("keyup", this._onKeyUp, false);
  14035. BABYLON.Tools.RegisterTopRootEvents([
  14036. { name: "blur", handler: this._onLostFocus }
  14037. ]);
  14038. };
  14039. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14040. if (element) {
  14041. element.removeEventListener("keydown", this._onKeyDown);
  14042. element.removeEventListener("keyup", this._onKeyUp);
  14043. }
  14044. BABYLON.Tools.UnregisterTopRootEvents([
  14045. { name: "blur", handler: this._onLostFocus }
  14046. ]);
  14047. this._keys = [];
  14048. this._onKeyDown = null;
  14049. this._onKeyUp = null;
  14050. this._onLostFocus = null;
  14051. };
  14052. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14053. if (this._onKeyDown) {
  14054. var camera = this.camera;
  14055. for (var index = 0; index < this._keys.length; index++) {
  14056. var keyCode = this._keys[index];
  14057. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14058. camera.inertialAlphaOffset -= 0.01;
  14059. }
  14060. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14061. camera.inertialBetaOffset -= 0.01;
  14062. }
  14063. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14064. camera.inertialAlphaOffset += 0.01;
  14065. }
  14066. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14067. camera.inertialBetaOffset += 0.01;
  14068. }
  14069. }
  14070. }
  14071. };
  14072. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14073. return "ArcRotateCameraKeyboardMoveInput";
  14074. };
  14075. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14076. return "keyboard";
  14077. };
  14078. __decorate([
  14079. BABYLON.serialize()
  14080. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14081. __decorate([
  14082. BABYLON.serialize()
  14083. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14084. __decorate([
  14085. BABYLON.serialize()
  14086. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14087. __decorate([
  14088. BABYLON.serialize()
  14089. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14090. return ArcRotateCameraKeyboardMoveInput;
  14091. }());
  14092. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14093. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14094. })(BABYLON || (BABYLON = {}));
  14095. var BABYLON;
  14096. (function (BABYLON) {
  14097. var ArcRotateCameraMouseWheelInput = (function () {
  14098. function ArcRotateCameraMouseWheelInput() {
  14099. this.wheelPrecision = 3.0;
  14100. }
  14101. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14102. var _this = this;
  14103. this._wheel = function (p, s) {
  14104. //sanity check - this should be a PointerWheel event.
  14105. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14106. return;
  14107. var event = p.event;
  14108. var delta = 0;
  14109. if (event.wheelDelta) {
  14110. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14111. }
  14112. else if (event.detail) {
  14113. delta = -event.detail / _this.wheelPrecision;
  14114. }
  14115. if (delta)
  14116. _this.camera.inertialRadiusOffset += delta;
  14117. if (event.preventDefault) {
  14118. if (!noPreventDefault) {
  14119. event.preventDefault();
  14120. }
  14121. }
  14122. };
  14123. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14124. };
  14125. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14126. if (this._observer && element) {
  14127. this.camera.getScene().onPointerObservable.remove(this._observer);
  14128. this._observer = null;
  14129. this._wheel = null;
  14130. }
  14131. };
  14132. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14133. return "ArcRotateCameraMouseWheelInput";
  14134. };
  14135. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14136. return "mousewheel";
  14137. };
  14138. __decorate([
  14139. BABYLON.serialize()
  14140. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14141. return ArcRotateCameraMouseWheelInput;
  14142. }());
  14143. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14144. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14145. })(BABYLON || (BABYLON = {}));
  14146. var BABYLON;
  14147. (function (BABYLON) {
  14148. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14149. var ArcRotateCameraPointersInput = (function () {
  14150. function ArcRotateCameraPointersInput() {
  14151. this.buttons = [0, 1, 2];
  14152. this.angularSensibilityX = 1000.0;
  14153. this.angularSensibilityY = 1000.0;
  14154. this.pinchPrecision = 6.0;
  14155. this.panningSensibility = 50.0;
  14156. this._isPanClick = false;
  14157. this.pinchInwards = true;
  14158. }
  14159. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14160. var _this = this;
  14161. var engine = this.camera.getEngine();
  14162. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14163. var pointA, pointB;
  14164. var previousPinchDistance = 0;
  14165. this._pointerInput = function (p, s) {
  14166. var evt = p.event;
  14167. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14168. return;
  14169. }
  14170. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14171. try {
  14172. evt.srcElement.setPointerCapture(evt.pointerId);
  14173. }
  14174. catch (e) {
  14175. }
  14176. // Manage panning with pan button click
  14177. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14178. // manage pointers
  14179. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14180. if (pointA === undefined) {
  14181. pointA = cacheSoloPointer;
  14182. }
  14183. else if (pointB === undefined) {
  14184. pointB = cacheSoloPointer;
  14185. }
  14186. if (!noPreventDefault) {
  14187. evt.preventDefault();
  14188. element.focus();
  14189. }
  14190. }
  14191. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14192. try {
  14193. evt.srcElement.releasePointerCapture(evt.pointerId);
  14194. }
  14195. catch (e) {
  14196. }
  14197. cacheSoloPointer = null;
  14198. previousPinchDistance = 0;
  14199. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14200. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14201. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14202. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14203. pointA = pointB = undefined;
  14204. if (!noPreventDefault) {
  14205. evt.preventDefault();
  14206. }
  14207. }
  14208. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14209. if (!noPreventDefault) {
  14210. evt.preventDefault();
  14211. }
  14212. // One button down
  14213. if (pointA && pointB === undefined) {
  14214. if (_this.panningSensibility !== 0 &&
  14215. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14216. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14217. _this.camera
  14218. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14219. _this.camera
  14220. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14221. }
  14222. else {
  14223. var offsetX = evt.clientX - cacheSoloPointer.x;
  14224. var offsetY = evt.clientY - cacheSoloPointer.y;
  14225. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14226. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14227. }
  14228. cacheSoloPointer.x = evt.clientX;
  14229. cacheSoloPointer.y = evt.clientY;
  14230. }
  14231. else if (pointA && pointB) {
  14232. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14233. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14234. ed.x = evt.clientX;
  14235. ed.y = evt.clientY;
  14236. var direction = _this.pinchInwards ? 1 : -1;
  14237. var distX = pointA.x - pointB.x;
  14238. var distY = pointA.y - pointB.y;
  14239. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14240. if (previousPinchDistance === 0) {
  14241. previousPinchDistance = pinchSquaredDistance;
  14242. return;
  14243. }
  14244. if (pinchSquaredDistance !== previousPinchDistance) {
  14245. _this.camera
  14246. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14247. (_this.pinchPrecision *
  14248. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14249. direction);
  14250. previousPinchDistance = pinchSquaredDistance;
  14251. }
  14252. }
  14253. }
  14254. };
  14255. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14256. this._onContextMenu = function (evt) {
  14257. evt.preventDefault();
  14258. };
  14259. if (!this.camera._useCtrlForPanning) {
  14260. element.addEventListener("contextmenu", this._onContextMenu, false);
  14261. }
  14262. this._onLostFocus = function () {
  14263. //this._keys = [];
  14264. pointA = pointB = undefined;
  14265. previousPinchDistance = 0;
  14266. cacheSoloPointer = null;
  14267. };
  14268. this._onMouseMove = function (evt) {
  14269. if (!engine.isPointerLock) {
  14270. return;
  14271. }
  14272. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14273. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14274. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14275. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14276. if (!noPreventDefault) {
  14277. evt.preventDefault();
  14278. }
  14279. };
  14280. this._onGestureStart = function (e) {
  14281. if (window.MSGesture === undefined) {
  14282. return;
  14283. }
  14284. if (!_this._MSGestureHandler) {
  14285. _this._MSGestureHandler = new MSGesture();
  14286. _this._MSGestureHandler.target = element;
  14287. }
  14288. _this._MSGestureHandler.addPointer(e.pointerId);
  14289. };
  14290. this._onGesture = function (e) {
  14291. _this.camera.radius *= e.scale;
  14292. if (e.preventDefault) {
  14293. if (!noPreventDefault) {
  14294. e.stopPropagation();
  14295. e.preventDefault();
  14296. }
  14297. }
  14298. };
  14299. element.addEventListener("mousemove", this._onMouseMove, false);
  14300. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14301. element.addEventListener("MSGestureChange", this._onGesture, false);
  14302. element.addEventListener("keydown", this._onKeyDown, false);
  14303. element.addEventListener("keyup", this._onKeyUp, false);
  14304. BABYLON.Tools.RegisterTopRootEvents([
  14305. { name: "blur", handler: this._onLostFocus }
  14306. ]);
  14307. };
  14308. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14309. if (element && this._observer) {
  14310. this.camera.getScene().onPointerObservable.remove(this._observer);
  14311. this._observer = null;
  14312. element.removeEventListener("contextmenu", this._onContextMenu);
  14313. element.removeEventListener("mousemove", this._onMouseMove);
  14314. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14315. element.removeEventListener("MSGestureChange", this._onGesture);
  14316. element.removeEventListener("keydown", this._onKeyDown);
  14317. element.removeEventListener("keyup", this._onKeyUp);
  14318. this._isPanClick = false;
  14319. this.pinchInwards = true;
  14320. this._onKeyDown = null;
  14321. this._onKeyUp = null;
  14322. this._onMouseMove = null;
  14323. this._onGestureStart = null;
  14324. this._onGesture = null;
  14325. this._MSGestureHandler = null;
  14326. this._onLostFocus = null;
  14327. this._onContextMenu = null;
  14328. }
  14329. BABYLON.Tools.UnregisterTopRootEvents([
  14330. { name: "blur", handler: this._onLostFocus }
  14331. ]);
  14332. };
  14333. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14334. return "ArcRotateCameraPointersInput";
  14335. };
  14336. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14337. return "pointers";
  14338. };
  14339. __decorate([
  14340. BABYLON.serialize()
  14341. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  14342. __decorate([
  14343. BABYLON.serialize()
  14344. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14345. __decorate([
  14346. BABYLON.serialize()
  14347. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14348. __decorate([
  14349. BABYLON.serialize()
  14350. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14351. __decorate([
  14352. BABYLON.serialize()
  14353. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14354. return ArcRotateCameraPointersInput;
  14355. }());
  14356. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14357. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14358. })(BABYLON || (BABYLON = {}));
  14359. var BABYLON;
  14360. (function (BABYLON) {
  14361. var ArcRotateCameraGamepadInput = (function () {
  14362. function ArcRotateCameraGamepadInput() {
  14363. this.gamepadRotationSensibility = 80;
  14364. this.gamepadMoveSensibility = 40;
  14365. }
  14366. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14367. var _this = this;
  14368. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14369. };
  14370. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14371. if (this._gamepads) {
  14372. this._gamepads.dispose();
  14373. }
  14374. this.gamepad = null;
  14375. };
  14376. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14377. if (this.gamepad) {
  14378. var camera = this.camera;
  14379. var RSValues = this.gamepad.rightStick;
  14380. if (RSValues.x != 0) {
  14381. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14382. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14383. camera.inertialAlphaOffset += normalizedRX;
  14384. }
  14385. }
  14386. if (RSValues.y != 0) {
  14387. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14388. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14389. camera.inertialBetaOffset += normalizedRY;
  14390. }
  14391. }
  14392. var LSValues = this.gamepad.leftStick;
  14393. if (LSValues.y != 0) {
  14394. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14395. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14396. this.camera.inertialRadiusOffset -= normalizedLY;
  14397. }
  14398. }
  14399. }
  14400. };
  14401. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14402. // Only the first gamepad can control the camera
  14403. if (gamepad.index === 0) {
  14404. this.gamepad = gamepad;
  14405. }
  14406. };
  14407. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14408. return "ArcRotateCameraGamepadInput";
  14409. };
  14410. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14411. return "gamepad";
  14412. };
  14413. __decorate([
  14414. BABYLON.serialize()
  14415. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14416. __decorate([
  14417. BABYLON.serialize()
  14418. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14419. return ArcRotateCameraGamepadInput;
  14420. }());
  14421. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14422. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14423. })(BABYLON || (BABYLON = {}));
  14424. var BABYLON;
  14425. (function (BABYLON) {
  14426. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14427. function ArcRotateCameraVRDeviceOrientationInput() {
  14428. this.alphaCorrection = 1;
  14429. this.betaCorrection = 1;
  14430. this.gammaCorrection = 1;
  14431. this._alpha = 0;
  14432. this._beta = 0;
  14433. this._gamma = 0;
  14434. this._dirty = false;
  14435. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14436. }
  14437. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14438. this.camera.attachControl(element, noPreventDefault);
  14439. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14440. };
  14441. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14442. var camera = this.camera;
  14443. this._alpha = +evt.alpha | 0;
  14444. this._beta = +evt.beta | 0;
  14445. this._gamma = +evt.gamma | 0;
  14446. this._dirty = true;
  14447. };
  14448. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14449. if (this._dirty) {
  14450. this._dirty = false;
  14451. if (this._gamma < 0) {
  14452. this._gamma = 180 + this._gamma;
  14453. }
  14454. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14455. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14456. }
  14457. };
  14458. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14459. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14460. };
  14461. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14462. return "ArcRotateCameraVRDeviceOrientationInput";
  14463. };
  14464. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14465. return "VRDeviceOrientation";
  14466. };
  14467. return ArcRotateCameraVRDeviceOrientationInput;
  14468. }());
  14469. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14470. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14471. })(BABYLON || (BABYLON = {}));
  14472. var BABYLON;
  14473. (function (BABYLON) {
  14474. var TargetCamera = (function (_super) {
  14475. __extends(TargetCamera, _super);
  14476. function TargetCamera(name, position, scene) {
  14477. _super.call(this, name, position, scene);
  14478. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14479. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14480. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14481. this.speed = 2.0;
  14482. this.noRotationConstraint = false;
  14483. this.lockedTarget = null;
  14484. this._currentTarget = BABYLON.Vector3.Zero();
  14485. this._viewMatrix = BABYLON.Matrix.Zero();
  14486. this._camMatrix = BABYLON.Matrix.Zero();
  14487. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14488. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14489. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14490. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14491. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14492. this._lookAtTemp = BABYLON.Matrix.Zero();
  14493. this._tempMatrix = BABYLON.Matrix.Zero();
  14494. }
  14495. TargetCamera.prototype.getFrontPosition = function (distance) {
  14496. var direction = this.getTarget().subtract(this.position);
  14497. direction.normalize();
  14498. direction.scaleInPlace(distance);
  14499. return this.globalPosition.add(direction);
  14500. };
  14501. TargetCamera.prototype._getLockedTargetPosition = function () {
  14502. if (!this.lockedTarget) {
  14503. return null;
  14504. }
  14505. return this.lockedTarget.position || this.lockedTarget;
  14506. };
  14507. // Cache
  14508. TargetCamera.prototype._initCache = function () {
  14509. _super.prototype._initCache.call(this);
  14510. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14511. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14512. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14513. };
  14514. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14515. if (!ignoreParentClass) {
  14516. _super.prototype._updateCache.call(this);
  14517. }
  14518. var lockedTargetPosition = this._getLockedTargetPosition();
  14519. if (!lockedTargetPosition) {
  14520. this._cache.lockedTarget = null;
  14521. }
  14522. else {
  14523. if (!this._cache.lockedTarget) {
  14524. this._cache.lockedTarget = lockedTargetPosition.clone();
  14525. }
  14526. else {
  14527. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14528. }
  14529. }
  14530. this._cache.rotation.copyFrom(this.rotation);
  14531. if (this.rotationQuaternion)
  14532. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14533. };
  14534. // Synchronized
  14535. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14536. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14537. return false;
  14538. }
  14539. var lockedTargetPosition = this._getLockedTargetPosition();
  14540. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14541. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14542. };
  14543. // Methods
  14544. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14545. var engine = this.getEngine();
  14546. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14547. };
  14548. // Target
  14549. TargetCamera.prototype.setTarget = function (target) {
  14550. this.upVector.normalize();
  14551. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14552. this._camMatrix.invert();
  14553. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14554. var vDir = target.subtract(this.position);
  14555. if (vDir.x >= 0.0) {
  14556. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14557. }
  14558. else {
  14559. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14560. }
  14561. this.rotation.z = 0;
  14562. if (isNaN(this.rotation.x)) {
  14563. this.rotation.x = 0;
  14564. }
  14565. if (isNaN(this.rotation.y)) {
  14566. this.rotation.y = 0;
  14567. }
  14568. if (isNaN(this.rotation.z)) {
  14569. this.rotation.z = 0;
  14570. }
  14571. if (this.rotationQuaternion) {
  14572. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14573. }
  14574. };
  14575. TargetCamera.prototype.getTarget = function () {
  14576. return this._currentTarget;
  14577. };
  14578. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14579. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14580. };
  14581. TargetCamera.prototype._updatePosition = function () {
  14582. this.position.addInPlace(this.cameraDirection);
  14583. };
  14584. TargetCamera.prototype._checkInputs = function () {
  14585. var needToMove = this._decideIfNeedsToMove();
  14586. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14587. // Move
  14588. if (needToMove) {
  14589. this._updatePosition();
  14590. }
  14591. // Rotate
  14592. if (needToRotate) {
  14593. this.rotation.x += this.cameraRotation.x;
  14594. this.rotation.y += this.cameraRotation.y;
  14595. if (!this.noRotationConstraint) {
  14596. var limit = (Math.PI / 2) * 0.95;
  14597. if (this.rotation.x > limit)
  14598. this.rotation.x = limit;
  14599. if (this.rotation.x < -limit)
  14600. this.rotation.x = -limit;
  14601. }
  14602. }
  14603. // Inertia
  14604. if (needToMove) {
  14605. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14606. this.cameraDirection.x = 0;
  14607. }
  14608. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14609. this.cameraDirection.y = 0;
  14610. }
  14611. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14612. this.cameraDirection.z = 0;
  14613. }
  14614. this.cameraDirection.scaleInPlace(this.inertia);
  14615. }
  14616. if (needToRotate) {
  14617. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14618. this.cameraRotation.x = 0;
  14619. }
  14620. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14621. this.cameraRotation.y = 0;
  14622. }
  14623. this.cameraRotation.scaleInPlace(this.inertia);
  14624. }
  14625. _super.prototype._checkInputs.call(this);
  14626. };
  14627. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14628. if (this.rotationQuaternion) {
  14629. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14630. //update the up vector!
  14631. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14632. }
  14633. else {
  14634. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14635. }
  14636. };
  14637. TargetCamera.prototype._getViewMatrix = function () {
  14638. if (!this.lockedTarget) {
  14639. // Compute
  14640. this._updateCameraRotationMatrix();
  14641. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14642. // Computing target and final matrix
  14643. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14644. }
  14645. else {
  14646. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14647. }
  14648. if (this.getScene().useRightHandedSystem) {
  14649. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14650. }
  14651. else {
  14652. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14653. }
  14654. return this._viewMatrix;
  14655. };
  14656. /**
  14657. * @override
  14658. * Override Camera.createRigCamera
  14659. */
  14660. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14661. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14662. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14663. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14664. if (!this.rotationQuaternion) {
  14665. this.rotationQuaternion = new BABYLON.Quaternion();
  14666. }
  14667. rigCamera._cameraRigParams = {};
  14668. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14669. }
  14670. return rigCamera;
  14671. }
  14672. return null;
  14673. };
  14674. /**
  14675. * @override
  14676. * Override Camera._updateRigCameras
  14677. */
  14678. TargetCamera.prototype._updateRigCameras = function () {
  14679. var camLeft = this._rigCameras[0];
  14680. var camRight = this._rigCameras[1];
  14681. switch (this.cameraRigMode) {
  14682. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14683. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14684. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14685. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14686. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14687. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14688. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14689. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14690. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14691. camLeft.setTarget(this.getTarget());
  14692. camRight.setTarget(this.getTarget());
  14693. break;
  14694. case BABYLON.Camera.RIG_MODE_VR:
  14695. case BABYLON.Camera.RIG_MODE_WEBVR:
  14696. if (camLeft.rotationQuaternion) {
  14697. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14698. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14699. }
  14700. else {
  14701. camLeft.rotation.copyFrom(this.rotation);
  14702. camRight.rotation.copyFrom(this.rotation);
  14703. }
  14704. camLeft.position.copyFrom(this.position);
  14705. camRight.position.copyFrom(this.position);
  14706. break;
  14707. }
  14708. _super.prototype._updateRigCameras.call(this);
  14709. };
  14710. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14711. if (!this._rigCamTransformMatrix) {
  14712. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14713. }
  14714. var target = this.getTarget();
  14715. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14716. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14717. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14718. };
  14719. TargetCamera.prototype.getTypeName = function () {
  14720. return "TargetCamera";
  14721. };
  14722. __decorate([
  14723. BABYLON.serializeAsVector3()
  14724. ], TargetCamera.prototype, "rotation", void 0);
  14725. __decorate([
  14726. BABYLON.serialize()
  14727. ], TargetCamera.prototype, "speed", void 0);
  14728. __decorate([
  14729. BABYLON.serializeAsMeshReference("lockedTargetId")
  14730. ], TargetCamera.prototype, "lockedTarget", void 0);
  14731. return TargetCamera;
  14732. }(BABYLON.Camera));
  14733. BABYLON.TargetCamera = TargetCamera;
  14734. })(BABYLON || (BABYLON = {}));
  14735. var BABYLON;
  14736. (function (BABYLON) {
  14737. var FreeCamera = (function (_super) {
  14738. __extends(FreeCamera, _super);
  14739. function FreeCamera(name, position, scene) {
  14740. var _this = this;
  14741. _super.call(this, name, position, scene);
  14742. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14743. this.checkCollisions = false;
  14744. this.applyGravity = false;
  14745. this._collider = new BABYLON.Collider();
  14746. this._needMoveForGravity = false;
  14747. this._oldPosition = BABYLON.Vector3.Zero();
  14748. this._diffPosition = BABYLON.Vector3.Zero();
  14749. this._newPosition = BABYLON.Vector3.Zero();
  14750. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14751. if (collidedMesh === void 0) { collidedMesh = null; }
  14752. //TODO move this to the collision coordinator!
  14753. if (_this.getScene().workerCollisions)
  14754. newPosition.multiplyInPlace(_this._collider.radius);
  14755. var updatePosition = function (newPos) {
  14756. _this._newPosition.copyFrom(newPos);
  14757. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14758. var oldPosition = _this.position.clone();
  14759. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14760. _this.position.addInPlace(_this._diffPosition);
  14761. if (_this.onCollide && collidedMesh) {
  14762. _this.onCollide(collidedMesh);
  14763. }
  14764. }
  14765. };
  14766. updatePosition(newPosition);
  14767. };
  14768. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14769. this.inputs.addKeyboard().addMouse();
  14770. }
  14771. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14772. //-- begin properties for backward compatibility for inputs
  14773. get: function () {
  14774. var mouse = this.inputs.attached["mouse"];
  14775. if (mouse)
  14776. return mouse.angularSensibility;
  14777. },
  14778. set: function (value) {
  14779. var mouse = this.inputs.attached["mouse"];
  14780. if (mouse)
  14781. mouse.angularSensibility = value;
  14782. },
  14783. enumerable: true,
  14784. configurable: true
  14785. });
  14786. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14787. get: function () {
  14788. var keyboard = this.inputs.attached["keyboard"];
  14789. if (keyboard)
  14790. return keyboard.keysUp;
  14791. },
  14792. set: function (value) {
  14793. var keyboard = this.inputs.attached["keyboard"];
  14794. if (keyboard)
  14795. keyboard.keysUp = value;
  14796. },
  14797. enumerable: true,
  14798. configurable: true
  14799. });
  14800. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14801. get: function () {
  14802. var keyboard = this.inputs.attached["keyboard"];
  14803. if (keyboard)
  14804. return keyboard.keysDown;
  14805. },
  14806. set: function (value) {
  14807. var keyboard = this.inputs.attached["keyboard"];
  14808. if (keyboard)
  14809. keyboard.keysDown = value;
  14810. },
  14811. enumerable: true,
  14812. configurable: true
  14813. });
  14814. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14815. get: function () {
  14816. var keyboard = this.inputs.attached["keyboard"];
  14817. if (keyboard)
  14818. return keyboard.keysLeft;
  14819. },
  14820. set: function (value) {
  14821. var keyboard = this.inputs.attached["keyboard"];
  14822. if (keyboard)
  14823. keyboard.keysLeft = value;
  14824. },
  14825. enumerable: true,
  14826. configurable: true
  14827. });
  14828. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14829. get: function () {
  14830. var keyboard = this.inputs.attached["keyboard"];
  14831. if (keyboard)
  14832. return keyboard.keysRight;
  14833. },
  14834. set: function (value) {
  14835. var keyboard = this.inputs.attached["keyboard"];
  14836. if (keyboard)
  14837. keyboard.keysRight = value;
  14838. },
  14839. enumerable: true,
  14840. configurable: true
  14841. });
  14842. // Controls
  14843. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14844. this.inputs.attachElement(element, noPreventDefault);
  14845. };
  14846. FreeCamera.prototype.detachControl = function (element) {
  14847. this.inputs.detachElement(element);
  14848. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14849. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14850. };
  14851. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14852. var globalPosition;
  14853. if (this.parent) {
  14854. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14855. }
  14856. else {
  14857. globalPosition = this.position;
  14858. }
  14859. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14860. this._collider.radius = this.ellipsoid;
  14861. //no need for clone, as long as gravity is not on.
  14862. var actualVelocity = velocity;
  14863. //add gravity to the velocity to prevent the dual-collision checking
  14864. if (this.applyGravity) {
  14865. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14866. actualVelocity = velocity.add(this.getScene().gravity);
  14867. }
  14868. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14869. };
  14870. FreeCamera.prototype._checkInputs = function () {
  14871. if (!this._localDirection) {
  14872. this._localDirection = BABYLON.Vector3.Zero();
  14873. this._transformedDirection = BABYLON.Vector3.Zero();
  14874. }
  14875. this.inputs.checkInputs();
  14876. _super.prototype._checkInputs.call(this);
  14877. };
  14878. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14879. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14880. };
  14881. FreeCamera.prototype._updatePosition = function () {
  14882. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14883. this._collideWithWorld(this.cameraDirection);
  14884. }
  14885. else {
  14886. this.position.addInPlace(this.cameraDirection);
  14887. }
  14888. };
  14889. FreeCamera.prototype.dispose = function () {
  14890. this.inputs.clear();
  14891. _super.prototype.dispose.call(this);
  14892. };
  14893. FreeCamera.prototype.getTypeName = function () {
  14894. return "FreeCamera";
  14895. };
  14896. __decorate([
  14897. BABYLON.serializeAsVector3()
  14898. ], FreeCamera.prototype, "ellipsoid", void 0);
  14899. __decorate([
  14900. BABYLON.serialize()
  14901. ], FreeCamera.prototype, "checkCollisions", void 0);
  14902. __decorate([
  14903. BABYLON.serialize()
  14904. ], FreeCamera.prototype, "applyGravity", void 0);
  14905. return FreeCamera;
  14906. }(BABYLON.TargetCamera));
  14907. BABYLON.FreeCamera = FreeCamera;
  14908. })(BABYLON || (BABYLON = {}));
  14909. var BABYLON;
  14910. (function (BABYLON) {
  14911. var FreeCameraInputsManager = (function (_super) {
  14912. __extends(FreeCameraInputsManager, _super);
  14913. function FreeCameraInputsManager(camera) {
  14914. _super.call(this, camera);
  14915. }
  14916. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14917. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14918. return this;
  14919. };
  14920. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14921. if (touchEnabled === void 0) { touchEnabled = true; }
  14922. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14923. return this;
  14924. };
  14925. FreeCameraInputsManager.prototype.addGamepad = function () {
  14926. this.add(new BABYLON.FreeCameraGamepadInput());
  14927. return this;
  14928. };
  14929. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14930. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14931. return this;
  14932. };
  14933. FreeCameraInputsManager.prototype.addTouch = function () {
  14934. this.add(new BABYLON.FreeCameraTouchInput());
  14935. return this;
  14936. };
  14937. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14938. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14939. return this;
  14940. };
  14941. return FreeCameraInputsManager;
  14942. }(BABYLON.CameraInputsManager));
  14943. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14944. })(BABYLON || (BABYLON = {}));
  14945. var BABYLON;
  14946. (function (BABYLON) {
  14947. var FollowCamera = (function (_super) {
  14948. __extends(FollowCamera, _super);
  14949. function FollowCamera(name, position, scene, target) {
  14950. _super.call(this, name, position, scene);
  14951. this.radius = 12;
  14952. this.rotationOffset = 0;
  14953. this.heightOffset = 4;
  14954. this.cameraAcceleration = 0.05;
  14955. this.maxCameraSpeed = 20;
  14956. this.target = target;
  14957. }
  14958. FollowCamera.prototype.getRadians = function (degrees) {
  14959. return degrees * Math.PI / 180;
  14960. };
  14961. FollowCamera.prototype.follow = function (cameraTarget) {
  14962. if (!cameraTarget)
  14963. return;
  14964. var yRotation;
  14965. if (cameraTarget.rotationQuaternion) {
  14966. var rotMatrix = new BABYLON.Matrix();
  14967. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14968. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14969. }
  14970. else {
  14971. yRotation = cameraTarget.rotation.y;
  14972. }
  14973. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14974. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14975. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14976. var dx = targetX - this.position.x;
  14977. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14978. var dz = (targetZ) - this.position.z;
  14979. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14980. var vy = dy * this.cameraAcceleration;
  14981. var vz = dz * this.cameraAcceleration * 2;
  14982. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14983. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14984. }
  14985. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14986. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14987. }
  14988. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14989. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14990. }
  14991. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14992. this.setTarget(cameraTarget.position);
  14993. };
  14994. FollowCamera.prototype._checkInputs = function () {
  14995. _super.prototype._checkInputs.call(this);
  14996. this.follow(this.target);
  14997. };
  14998. FollowCamera.prototype.getTypeName = function () {
  14999. return "FollowCamera";
  15000. };
  15001. __decorate([
  15002. BABYLON.serialize()
  15003. ], FollowCamera.prototype, "radius", void 0);
  15004. __decorate([
  15005. BABYLON.serialize()
  15006. ], FollowCamera.prototype, "rotationOffset", void 0);
  15007. __decorate([
  15008. BABYLON.serialize()
  15009. ], FollowCamera.prototype, "heightOffset", void 0);
  15010. __decorate([
  15011. BABYLON.serialize()
  15012. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15013. __decorate([
  15014. BABYLON.serialize()
  15015. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15016. __decorate([
  15017. BABYLON.serializeAsMeshReference("lockedTargetId")
  15018. ], FollowCamera.prototype, "target", void 0);
  15019. return FollowCamera;
  15020. }(BABYLON.TargetCamera));
  15021. BABYLON.FollowCamera = FollowCamera;
  15022. var ArcFollowCamera = (function (_super) {
  15023. __extends(ArcFollowCamera, _super);
  15024. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15025. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15026. this.alpha = alpha;
  15027. this.beta = beta;
  15028. this.radius = radius;
  15029. this.target = target;
  15030. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15031. this.follow();
  15032. }
  15033. ArcFollowCamera.prototype.follow = function () {
  15034. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15035. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15036. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15037. this.position = this.target.position.add(this._cartesianCoordinates);
  15038. this.setTarget(this.target.position);
  15039. };
  15040. ArcFollowCamera.prototype._checkInputs = function () {
  15041. _super.prototype._checkInputs.call(this);
  15042. this.follow();
  15043. };
  15044. ArcFollowCamera.prototype.getTypeName = function () {
  15045. return "ArcFollowCamera";
  15046. };
  15047. return ArcFollowCamera;
  15048. }(BABYLON.TargetCamera));
  15049. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15050. })(BABYLON || (BABYLON = {}));
  15051. var BABYLON;
  15052. (function (BABYLON) {
  15053. // We're mainly based on the logic defined into the FreeCamera code
  15054. var TouchCamera = (function (_super) {
  15055. __extends(TouchCamera, _super);
  15056. //-- end properties for backward compatibility for inputs
  15057. function TouchCamera(name, position, scene) {
  15058. _super.call(this, name, position, scene);
  15059. this.inputs.addTouch();
  15060. this._setupInputs();
  15061. }
  15062. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15063. //-- Begin properties for backward compatibility for inputs
  15064. get: function () {
  15065. var touch = this.inputs.attached["touch"];
  15066. if (touch)
  15067. return touch.touchAngularSensibility;
  15068. },
  15069. set: function (value) {
  15070. var touch = this.inputs.attached["touch"];
  15071. if (touch)
  15072. touch.touchAngularSensibility = value;
  15073. },
  15074. enumerable: true,
  15075. configurable: true
  15076. });
  15077. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15078. get: function () {
  15079. var touch = this.inputs.attached["touch"];
  15080. if (touch)
  15081. return touch.touchMoveSensibility;
  15082. },
  15083. set: function (value) {
  15084. var touch = this.inputs.attached["touch"];
  15085. if (touch)
  15086. touch.touchMoveSensibility = value;
  15087. },
  15088. enumerable: true,
  15089. configurable: true
  15090. });
  15091. TouchCamera.prototype.getTypeName = function () {
  15092. return "TouchCamera";
  15093. };
  15094. TouchCamera.prototype._setupInputs = function () {
  15095. var mouse = this.inputs.attached["mouse"];
  15096. if (mouse) {
  15097. mouse.touchEnabled = false;
  15098. }
  15099. };
  15100. return TouchCamera;
  15101. }(BABYLON.FreeCamera));
  15102. BABYLON.TouchCamera = TouchCamera;
  15103. })(BABYLON || (BABYLON = {}));
  15104. var BABYLON;
  15105. (function (BABYLON) {
  15106. var ArcRotateCamera = (function (_super) {
  15107. __extends(ArcRotateCamera, _super);
  15108. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15109. var _this = this;
  15110. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15111. this.inertialAlphaOffset = 0;
  15112. this.inertialBetaOffset = 0;
  15113. this.inertialRadiusOffset = 0;
  15114. this.lowerAlphaLimit = null;
  15115. this.upperAlphaLimit = null;
  15116. this.lowerBetaLimit = 0.01;
  15117. this.upperBetaLimit = Math.PI;
  15118. this.lowerRadiusLimit = null;
  15119. this.upperRadiusLimit = null;
  15120. this.inertialPanningX = 0;
  15121. this.inertialPanningY = 0;
  15122. //-- end properties for backward compatibility for inputs
  15123. this.zoomOnFactor = 1;
  15124. this.targetScreenOffset = BABYLON.Vector2.Zero();
  15125. this.allowUpsideDown = true;
  15126. this._viewMatrix = new BABYLON.Matrix();
  15127. // Panning
  15128. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15129. this.checkCollisions = false;
  15130. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15131. this._collider = new BABYLON.Collider();
  15132. this._previousPosition = BABYLON.Vector3.Zero();
  15133. this._collisionVelocity = BABYLON.Vector3.Zero();
  15134. this._newPosition = BABYLON.Vector3.Zero();
  15135. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15136. if (collidedMesh === void 0) { collidedMesh = null; }
  15137. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15138. newPosition.multiplyInPlace(_this._collider.radius);
  15139. }
  15140. if (!collidedMesh) {
  15141. _this._previousPosition.copyFrom(_this.position);
  15142. }
  15143. else {
  15144. _this.setPosition(newPosition);
  15145. if (_this.onCollide) {
  15146. _this.onCollide(collidedMesh);
  15147. }
  15148. }
  15149. // Recompute because of constraints
  15150. var cosa = Math.cos(_this.alpha);
  15151. var sina = Math.sin(_this.alpha);
  15152. var cosb = Math.cos(_this.beta);
  15153. var sinb = Math.sin(_this.beta);
  15154. if (sinb === 0) {
  15155. sinb = 0.0001;
  15156. }
  15157. var target = _this._getTargetPosition();
  15158. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15159. _this.position.copyFrom(_this._newPosition);
  15160. var up = _this.upVector;
  15161. if (_this.allowUpsideDown && _this.beta < 0) {
  15162. up = up.clone();
  15163. up = up.negate();
  15164. }
  15165. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15166. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15167. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15168. _this._collisionTriggered = false;
  15169. };
  15170. if (!target) {
  15171. this.target = BABYLON.Vector3.Zero();
  15172. }
  15173. else {
  15174. this.target = target;
  15175. }
  15176. this.alpha = alpha;
  15177. this.beta = beta;
  15178. this.radius = radius;
  15179. this.getViewMatrix();
  15180. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15181. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15182. }
  15183. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15184. //-- begin properties for backward compatibility for inputs
  15185. get: function () {
  15186. var pointers = this.inputs.attached["pointers"];
  15187. if (pointers)
  15188. return pointers.angularSensibilityX;
  15189. },
  15190. set: function (value) {
  15191. var pointers = this.inputs.attached["pointers"];
  15192. if (pointers) {
  15193. pointers.angularSensibilityX = value;
  15194. }
  15195. },
  15196. enumerable: true,
  15197. configurable: true
  15198. });
  15199. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15200. get: function () {
  15201. var pointers = this.inputs.attached["pointers"];
  15202. if (pointers)
  15203. return pointers.angularSensibilityY;
  15204. },
  15205. set: function (value) {
  15206. var pointers = this.inputs.attached["pointers"];
  15207. if (pointers) {
  15208. pointers.angularSensibilityY = value;
  15209. }
  15210. },
  15211. enumerable: true,
  15212. configurable: true
  15213. });
  15214. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15215. get: function () {
  15216. var pointers = this.inputs.attached["pointers"];
  15217. if (pointers)
  15218. return pointers.pinchPrecision;
  15219. },
  15220. set: function (value) {
  15221. var pointers = this.inputs.attached["pointers"];
  15222. if (pointers) {
  15223. pointers.pinchPrecision = value;
  15224. }
  15225. },
  15226. enumerable: true,
  15227. configurable: true
  15228. });
  15229. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15230. get: function () {
  15231. var pointers = this.inputs.attached["pointers"];
  15232. if (pointers)
  15233. return pointers.panningSensibility;
  15234. },
  15235. set: function (value) {
  15236. var pointers = this.inputs.attached["pointers"];
  15237. if (pointers) {
  15238. pointers.panningSensibility = value;
  15239. }
  15240. },
  15241. enumerable: true,
  15242. configurable: true
  15243. });
  15244. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15245. get: function () {
  15246. var keyboard = this.inputs.attached["keyboard"];
  15247. if (keyboard)
  15248. return keyboard.keysUp;
  15249. },
  15250. set: function (value) {
  15251. var keyboard = this.inputs.attached["keyboard"];
  15252. if (keyboard)
  15253. keyboard.keysUp = value;
  15254. },
  15255. enumerable: true,
  15256. configurable: true
  15257. });
  15258. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15259. get: function () {
  15260. var keyboard = this.inputs.attached["keyboard"];
  15261. if (keyboard)
  15262. return keyboard.keysDown;
  15263. },
  15264. set: function (value) {
  15265. var keyboard = this.inputs.attached["keyboard"];
  15266. if (keyboard)
  15267. keyboard.keysDown = value;
  15268. },
  15269. enumerable: true,
  15270. configurable: true
  15271. });
  15272. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15273. get: function () {
  15274. var keyboard = this.inputs.attached["keyboard"];
  15275. if (keyboard)
  15276. return keyboard.keysLeft;
  15277. },
  15278. set: function (value) {
  15279. var keyboard = this.inputs.attached["keyboard"];
  15280. if (keyboard)
  15281. keyboard.keysLeft = value;
  15282. },
  15283. enumerable: true,
  15284. configurable: true
  15285. });
  15286. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15287. get: function () {
  15288. var keyboard = this.inputs.attached["keyboard"];
  15289. if (keyboard)
  15290. return keyboard.keysRight;
  15291. },
  15292. set: function (value) {
  15293. var keyboard = this.inputs.attached["keyboard"];
  15294. if (keyboard)
  15295. keyboard.keysRight = value;
  15296. },
  15297. enumerable: true,
  15298. configurable: true
  15299. });
  15300. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15301. get: function () {
  15302. var mousewheel = this.inputs.attached["mousewheel"];
  15303. if (mousewheel)
  15304. return mousewheel.wheelPrecision;
  15305. },
  15306. set: function (value) {
  15307. var mousewheel = this.inputs.attached["mousewheel"];
  15308. if (mousewheel)
  15309. mousewheel.wheelPrecision = value;
  15310. },
  15311. enumerable: true,
  15312. configurable: true
  15313. });
  15314. // Cache
  15315. ArcRotateCamera.prototype._initCache = function () {
  15316. _super.prototype._initCache.call(this);
  15317. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15318. this._cache.alpha = undefined;
  15319. this._cache.beta = undefined;
  15320. this._cache.radius = undefined;
  15321. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15322. };
  15323. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15324. if (!ignoreParentClass) {
  15325. _super.prototype._updateCache.call(this);
  15326. }
  15327. this._cache.target.copyFrom(this._getTargetPosition());
  15328. this._cache.alpha = this.alpha;
  15329. this._cache.beta = this.beta;
  15330. this._cache.radius = this.radius;
  15331. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15332. };
  15333. ArcRotateCamera.prototype._getTargetPosition = function () {
  15334. if (this.target.getAbsolutePosition) {
  15335. var pos = this.target.getAbsolutePosition();
  15336. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15337. }
  15338. return this.target;
  15339. };
  15340. // Synchronized
  15341. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15342. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15343. return false;
  15344. return this._cache.target.equals(this.target)
  15345. && this._cache.alpha === this.alpha
  15346. && this._cache.beta === this.beta
  15347. && this._cache.radius === this.radius
  15348. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15349. };
  15350. // Methods
  15351. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15352. var _this = this;
  15353. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15354. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15355. this._useCtrlForPanning = useCtrlForPanning;
  15356. this._panningMouseButton = panningMouseButton;
  15357. this.inputs.attachElement(element, noPreventDefault);
  15358. this._reset = function () {
  15359. _this.inertialAlphaOffset = 0;
  15360. _this.inertialBetaOffset = 0;
  15361. _this.inertialRadiusOffset = 0;
  15362. };
  15363. };
  15364. ArcRotateCamera.prototype.detachControl = function (element) {
  15365. this.inputs.detachElement(element);
  15366. if (this._reset) {
  15367. this._reset();
  15368. }
  15369. };
  15370. ArcRotateCamera.prototype._checkInputs = function () {
  15371. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15372. if (this._collisionTriggered) {
  15373. return;
  15374. }
  15375. this.inputs.checkInputs();
  15376. // Inertia
  15377. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15378. this.beta += this.inertialBetaOffset;
  15379. if (this.getScene().useRightHandedSystem) {
  15380. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15381. }
  15382. else {
  15383. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15384. }
  15385. this.radius -= this.inertialRadiusOffset;
  15386. this.inertialAlphaOffset *= this.inertia;
  15387. this.inertialBetaOffset *= this.inertia;
  15388. this.inertialRadiusOffset *= this.inertia;
  15389. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15390. this.inertialAlphaOffset = 0;
  15391. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15392. this.inertialBetaOffset = 0;
  15393. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15394. this.inertialRadiusOffset = 0;
  15395. }
  15396. // Panning inertia
  15397. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15398. if (!this._localDirection) {
  15399. this._localDirection = BABYLON.Vector3.Zero();
  15400. this._transformedDirection = BABYLON.Vector3.Zero();
  15401. }
  15402. this.inertialPanningX *= this.inertia;
  15403. this.inertialPanningY *= this.inertia;
  15404. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15405. this.inertialPanningX = 0;
  15406. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15407. this.inertialPanningY = 0;
  15408. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15409. this._localDirection.multiplyInPlace(this.panningAxis);
  15410. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15411. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15412. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15413. if (!this.panningAxis.y) {
  15414. this._transformedDirection.y = 0;
  15415. }
  15416. if (!this.target.getAbsolutePosition) {
  15417. this.target.addInPlace(this._transformedDirection);
  15418. }
  15419. }
  15420. // Limits
  15421. this._checkLimits();
  15422. _super.prototype._checkInputs.call(this);
  15423. };
  15424. ArcRotateCamera.prototype._checkLimits = function () {
  15425. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15426. if (this.allowUpsideDown && this.beta > Math.PI) {
  15427. this.beta = this.beta - (2 * Math.PI);
  15428. }
  15429. }
  15430. else {
  15431. if (this.beta < this.lowerBetaLimit) {
  15432. this.beta = this.lowerBetaLimit;
  15433. }
  15434. }
  15435. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15436. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15437. this.beta = this.beta + (2 * Math.PI);
  15438. }
  15439. }
  15440. else {
  15441. if (this.beta > this.upperBetaLimit) {
  15442. this.beta = this.upperBetaLimit;
  15443. }
  15444. }
  15445. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15446. this.alpha = this.lowerAlphaLimit;
  15447. }
  15448. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15449. this.alpha = this.upperAlphaLimit;
  15450. }
  15451. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15452. this.radius = this.lowerRadiusLimit;
  15453. }
  15454. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15455. this.radius = this.upperRadiusLimit;
  15456. }
  15457. };
  15458. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15459. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15460. this.radius = radiusv3.length();
  15461. // Alpha
  15462. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15463. if (radiusv3.z < 0) {
  15464. this.alpha = 2 * Math.PI - this.alpha;
  15465. }
  15466. // Beta
  15467. this.beta = Math.acos(radiusv3.y / this.radius);
  15468. this._checkLimits();
  15469. };
  15470. ArcRotateCamera.prototype.setPosition = function (position) {
  15471. if (this.position.equals(position)) {
  15472. return;
  15473. }
  15474. this.position.copyFrom(position);
  15475. this.rebuildAnglesAndRadius();
  15476. };
  15477. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15478. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15479. if (this._getTargetPosition().equals(target)) {
  15480. return;
  15481. }
  15482. if (toBoundingCenter && target.getBoundingInfo) {
  15483. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15484. }
  15485. else {
  15486. this._targetBoundingCenter = null;
  15487. }
  15488. this.target = target;
  15489. this.rebuildAnglesAndRadius();
  15490. };
  15491. ArcRotateCamera.prototype._getViewMatrix = function () {
  15492. // Compute
  15493. var cosa = Math.cos(this.alpha);
  15494. var sina = Math.sin(this.alpha);
  15495. var cosb = Math.cos(this.beta);
  15496. var sinb = Math.sin(this.beta);
  15497. if (sinb === 0) {
  15498. sinb = 0.0001;
  15499. }
  15500. var target = this._getTargetPosition();
  15501. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15502. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15503. this._collider.radius = this.collisionRadius;
  15504. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15505. this._collisionTriggered = true;
  15506. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15507. }
  15508. else {
  15509. this.position.copyFrom(this._newPosition);
  15510. var up = this.upVector;
  15511. if (this.allowUpsideDown && this.beta < 0) {
  15512. up = up.clone();
  15513. up = up.negate();
  15514. }
  15515. if (this.getScene().useRightHandedSystem) {
  15516. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15517. }
  15518. else {
  15519. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15520. }
  15521. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15522. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15523. }
  15524. return this._viewMatrix;
  15525. };
  15526. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15527. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15528. meshes = meshes || this.getScene().meshes;
  15529. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15530. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15531. this.radius = distance * this.zoomOnFactor;
  15532. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15533. };
  15534. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15535. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15536. var meshesOrMinMaxVector;
  15537. var distance;
  15538. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15539. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15540. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15541. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15542. }
  15543. else {
  15544. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15545. distance = meshesOrMinMaxVectorAndDistance.distance;
  15546. }
  15547. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15548. if (!doNotUpdateMaxZ) {
  15549. this.maxZ = distance * 2;
  15550. }
  15551. };
  15552. /**
  15553. * @override
  15554. * Override Camera.createRigCamera
  15555. */
  15556. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15557. var alphaShift;
  15558. switch (this.cameraRigMode) {
  15559. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15560. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15561. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15562. case BABYLON.Camera.RIG_MODE_VR:
  15563. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15564. break;
  15565. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15566. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15567. break;
  15568. }
  15569. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15570. rigCam._cameraRigParams = {};
  15571. return rigCam;
  15572. };
  15573. /**
  15574. * @override
  15575. * Override Camera._updateRigCameras
  15576. */
  15577. ArcRotateCamera.prototype._updateRigCameras = function () {
  15578. var camLeft = this._rigCameras[0];
  15579. var camRight = this._rigCameras[1];
  15580. camLeft.beta = camRight.beta = this.beta;
  15581. camLeft.radius = camRight.radius = this.radius;
  15582. switch (this.cameraRigMode) {
  15583. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15584. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15585. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15586. case BABYLON.Camera.RIG_MODE_VR:
  15587. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15588. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15589. break;
  15590. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15591. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15592. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15593. break;
  15594. }
  15595. _super.prototype._updateRigCameras.call(this);
  15596. };
  15597. ArcRotateCamera.prototype.dispose = function () {
  15598. this.inputs.clear();
  15599. _super.prototype.dispose.call(this);
  15600. };
  15601. ArcRotateCamera.prototype.getTypeName = function () {
  15602. return "ArcRotateCamera";
  15603. };
  15604. __decorate([
  15605. BABYLON.serialize()
  15606. ], ArcRotateCamera.prototype, "alpha", void 0);
  15607. __decorate([
  15608. BABYLON.serialize()
  15609. ], ArcRotateCamera.prototype, "beta", void 0);
  15610. __decorate([
  15611. BABYLON.serialize()
  15612. ], ArcRotateCamera.prototype, "radius", void 0);
  15613. __decorate([
  15614. BABYLON.serializeAsVector3()
  15615. ], ArcRotateCamera.prototype, "target", void 0);
  15616. __decorate([
  15617. BABYLON.serialize()
  15618. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15619. __decorate([
  15620. BABYLON.serialize()
  15621. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15622. __decorate([
  15623. BABYLON.serialize()
  15624. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15625. __decorate([
  15626. BABYLON.serialize()
  15627. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15628. __decorate([
  15629. BABYLON.serialize()
  15630. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15631. __decorate([
  15632. BABYLON.serialize()
  15633. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15634. __decorate([
  15635. BABYLON.serialize()
  15636. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15637. __decorate([
  15638. BABYLON.serialize()
  15639. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15640. __decorate([
  15641. BABYLON.serialize()
  15642. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15643. __decorate([
  15644. BABYLON.serialize()
  15645. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15646. __decorate([
  15647. BABYLON.serialize()
  15648. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15649. __decorate([
  15650. BABYLON.serialize()
  15651. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15652. __decorate([
  15653. BABYLON.serialize()
  15654. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15655. return ArcRotateCamera;
  15656. }(BABYLON.TargetCamera));
  15657. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15658. })(BABYLON || (BABYLON = {}));
  15659. var BABYLON;
  15660. (function (BABYLON) {
  15661. var ArcRotateCameraInputsManager = (function (_super) {
  15662. __extends(ArcRotateCameraInputsManager, _super);
  15663. function ArcRotateCameraInputsManager(camera) {
  15664. _super.call(this, camera);
  15665. }
  15666. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15667. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15668. return this;
  15669. };
  15670. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15671. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15672. return this;
  15673. };
  15674. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15675. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15676. return this;
  15677. };
  15678. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15679. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15680. return this;
  15681. };
  15682. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15683. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15684. return this;
  15685. };
  15686. return ArcRotateCameraInputsManager;
  15687. }(BABYLON.CameraInputsManager));
  15688. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15689. })(BABYLON || (BABYLON = {}));
  15690. var BABYLON;
  15691. (function (BABYLON) {
  15692. var RenderingManager = (function () {
  15693. function RenderingManager(scene) {
  15694. this._renderingGroups = new Array();
  15695. this._autoClearDepthStencil = {};
  15696. this._customOpaqueSortCompareFn = {};
  15697. this._customAlphaTestSortCompareFn = {};
  15698. this._customTransparentSortCompareFn = {};
  15699. this._renderinGroupInfo = null;
  15700. this._scene = scene;
  15701. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15702. this._autoClearDepthStencil[i] = true;
  15703. }
  15704. }
  15705. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15706. if (this._scene._activeParticleSystems.length === 0) {
  15707. return;
  15708. }
  15709. // Particles
  15710. var activeCamera = this._scene.activeCamera;
  15711. this._scene._particlesDuration.beginMonitoring();
  15712. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15713. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15714. if (particleSystem.renderingGroupId !== index) {
  15715. continue;
  15716. }
  15717. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15718. continue;
  15719. }
  15720. this._clearDepthStencilBuffer();
  15721. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15722. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15723. }
  15724. }
  15725. this._scene._particlesDuration.endMonitoring(false);
  15726. };
  15727. RenderingManager.prototype._renderSprites = function (index) {
  15728. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15729. return;
  15730. }
  15731. // Sprites
  15732. var activeCamera = this._scene.activeCamera;
  15733. this._scene._spritesDuration.beginMonitoring();
  15734. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15735. var spriteManager = this._scene.spriteManagers[id];
  15736. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15737. this._clearDepthStencilBuffer();
  15738. spriteManager.render();
  15739. }
  15740. }
  15741. this._scene._spritesDuration.endMonitoring(false);
  15742. };
  15743. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15744. if (this._depthStencilBufferAlreadyCleaned) {
  15745. return;
  15746. }
  15747. this._scene.getEngine().clear(0, false, true, true);
  15748. this._depthStencilBufferAlreadyCleaned = true;
  15749. };
  15750. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15751. if (this._currentRenderSprites) {
  15752. this._renderSprites(this._currentIndex);
  15753. }
  15754. if (this._currentRenderParticles) {
  15755. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15756. }
  15757. };
  15758. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15759. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15760. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15761. var info = null;
  15762. if (observable) {
  15763. if (!this._renderinGroupInfo) {
  15764. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15765. }
  15766. info = this._renderinGroupInfo;
  15767. info.scene = this._scene;
  15768. info.camera = this._scene.activeCamera;
  15769. }
  15770. this._currentActiveMeshes = activeMeshes;
  15771. this._currentRenderParticles = renderParticles;
  15772. this._currentRenderSprites = renderSprites;
  15773. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15774. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15775. var renderingGroup = this._renderingGroups[index];
  15776. var needToStepBack = false;
  15777. this._currentIndex = index;
  15778. if (renderingGroup) {
  15779. var renderingGroupMask = 0;
  15780. // Fire PRECLEAR stage
  15781. if (observable) {
  15782. renderingGroupMask = Math.pow(2, index);
  15783. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15784. info.renderingGroupId = index;
  15785. observable.notifyObservers(info, renderingGroupMask);
  15786. }
  15787. // Clear depth/stencil if needed
  15788. if (this._autoClearDepthStencil[index]) {
  15789. this._clearDepthStencilBuffer();
  15790. }
  15791. // Fire PREOPAQUE stage
  15792. if (observable) {
  15793. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15794. observable.notifyObservers(info, renderingGroupMask);
  15795. }
  15796. if (!renderingGroup.onBeforeTransparentRendering) {
  15797. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15798. }
  15799. // Fire PRETRANSPARENT stage
  15800. if (observable) {
  15801. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15802. observable.notifyObservers(info, renderingGroupMask);
  15803. }
  15804. if (!renderingGroup.render(customRenderFunction)) {
  15805. this._renderingGroups.splice(index, 1);
  15806. needToStepBack = true;
  15807. this._renderSpritesAndParticles();
  15808. }
  15809. // Fire POSTTRANSPARENT stage
  15810. if (observable) {
  15811. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15812. observable.notifyObservers(info, renderingGroupMask);
  15813. }
  15814. }
  15815. else {
  15816. this._renderSpritesAndParticles();
  15817. if (observable) {
  15818. var renderingGroupMask = Math.pow(2, index);
  15819. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15820. info.renderingGroupId = index;
  15821. observable.notifyObservers(info, renderingGroupMask);
  15822. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15823. observable.notifyObservers(info, renderingGroupMask);
  15824. }
  15825. }
  15826. if (needToStepBack) {
  15827. index--;
  15828. }
  15829. }
  15830. };
  15831. RenderingManager.prototype.reset = function () {
  15832. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15833. var renderingGroup = this._renderingGroups[index];
  15834. if (renderingGroup) {
  15835. renderingGroup.prepare();
  15836. }
  15837. }
  15838. };
  15839. RenderingManager.prototype.dispatch = function (subMesh) {
  15840. var mesh = subMesh.getMesh();
  15841. var renderingGroupId = mesh.renderingGroupId || 0;
  15842. if (!this._renderingGroups[renderingGroupId]) {
  15843. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15844. }
  15845. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15846. };
  15847. /**
  15848. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15849. * This allowed control for front to back rendering or reversly depending of the special needs.
  15850. *
  15851. * @param renderingGroupId The rendering group id corresponding to its index
  15852. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15853. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15854. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15855. */
  15856. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15857. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15858. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15859. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15860. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15861. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15862. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15863. if (this._renderingGroups[renderingGroupId]) {
  15864. var group = this._renderingGroups[renderingGroupId];
  15865. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15866. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15867. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15868. }
  15869. };
  15870. /**
  15871. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15872. *
  15873. * @param renderingGroupId The rendering group id corresponding to its index
  15874. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15875. */
  15876. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15877. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15878. };
  15879. /**
  15880. * The max id used for rendering groups (not included)
  15881. */
  15882. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15883. /**
  15884. * The min id used for rendering groups (included)
  15885. */
  15886. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15887. return RenderingManager;
  15888. }());
  15889. BABYLON.RenderingManager = RenderingManager;
  15890. })(BABYLON || (BABYLON = {}));
  15891. var BABYLON;
  15892. (function (BABYLON) {
  15893. var RenderingGroup = (function () {
  15894. /**
  15895. * Creates a new rendering group.
  15896. * @param index The rendering group index
  15897. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15898. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15899. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15900. */
  15901. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15902. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15903. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15904. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15905. this.index = index;
  15906. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15907. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15908. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15909. this._scene = scene;
  15910. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15911. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15912. this.transparentSortCompareFn = transparentSortCompareFn;
  15913. }
  15914. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15915. /**
  15916. * Set the opaque sort comparison function.
  15917. * If null the sub meshes will be render in the order they were created
  15918. */
  15919. set: function (value) {
  15920. this._opaqueSortCompareFn = value;
  15921. if (value) {
  15922. this._renderOpaque = this.renderOpaqueSorted;
  15923. }
  15924. else {
  15925. this._renderOpaque = RenderingGroup.renderUnsorted;
  15926. }
  15927. },
  15928. enumerable: true,
  15929. configurable: true
  15930. });
  15931. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15932. /**
  15933. * Set the alpha test sort comparison function.
  15934. * If null the sub meshes will be render in the order they were created
  15935. */
  15936. set: function (value) {
  15937. this._alphaTestSortCompareFn = value;
  15938. if (value) {
  15939. this._renderAlphaTest = this.renderAlphaTestSorted;
  15940. }
  15941. else {
  15942. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15943. }
  15944. },
  15945. enumerable: true,
  15946. configurable: true
  15947. });
  15948. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15949. /**
  15950. * Set the transparent sort comparison function.
  15951. * If null the sub meshes will be render in the order they were created
  15952. */
  15953. set: function (value) {
  15954. if (value) {
  15955. this._transparentSortCompareFn = value;
  15956. }
  15957. else {
  15958. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15959. }
  15960. this._renderTransparent = this.renderTransparentSorted;
  15961. },
  15962. enumerable: true,
  15963. configurable: true
  15964. });
  15965. /**
  15966. * Render all the sub meshes contained in the group.
  15967. * @param customRenderFunction Used to override the default render behaviour of the group.
  15968. * @returns true if rendered some submeshes.
  15969. */
  15970. RenderingGroup.prototype.render = function (customRenderFunction) {
  15971. if (customRenderFunction) {
  15972. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15973. return true;
  15974. }
  15975. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15976. if (this.onBeforeTransparentRendering) {
  15977. this.onBeforeTransparentRendering();
  15978. }
  15979. return false;
  15980. }
  15981. var engine = this._scene.getEngine();
  15982. // Opaque
  15983. this._renderOpaque(this._opaqueSubMeshes);
  15984. // Alpha test
  15985. engine.setAlphaTesting(true);
  15986. this._renderAlphaTest(this._alphaTestSubMeshes);
  15987. engine.setAlphaTesting(false);
  15988. if (this.onBeforeTransparentRendering) {
  15989. this.onBeforeTransparentRendering();
  15990. }
  15991. // Transparent
  15992. this._renderTransparent(this._transparentSubMeshes);
  15993. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15994. return true;
  15995. };
  15996. /**
  15997. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15998. * @param subMeshes The submeshes to render
  15999. */
  16000. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16001. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16002. };
  16003. /**
  16004. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16005. * @param subMeshes The submeshes to render
  16006. */
  16007. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16008. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16009. };
  16010. /**
  16011. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16012. * @param subMeshes The submeshes to render
  16013. */
  16014. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16015. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16016. };
  16017. /**
  16018. * Renders the submeshes in a specified order.
  16019. * @param subMeshes The submeshes to sort before render
  16020. * @param sortCompareFn The comparison function use to sort
  16021. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16022. * @param transparent Specifies to activate blending if true
  16023. */
  16024. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16025. var subIndex = 0;
  16026. var subMesh;
  16027. for (; subIndex < subMeshes.length; subIndex++) {
  16028. subMesh = subMeshes.data[subIndex];
  16029. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16030. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16031. }
  16032. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16033. sortedArray.sort(sortCompareFn);
  16034. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16035. subMesh = sortedArray[subIndex];
  16036. subMesh.render(transparent);
  16037. }
  16038. };
  16039. /**
  16040. * Renders the submeshes in the order they were dispatched (no sort applied).
  16041. * @param subMeshes The submeshes to render
  16042. */
  16043. RenderingGroup.renderUnsorted = function (subMeshes) {
  16044. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16045. var submesh = subMeshes.data[subIndex];
  16046. submesh.render(false);
  16047. }
  16048. };
  16049. /**
  16050. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16051. * are rendered back to front if in the same alpha index.
  16052. *
  16053. * @param a The first submesh
  16054. * @param b The second submesh
  16055. * @returns The result of the comparison
  16056. */
  16057. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16058. // Alpha index first
  16059. if (a._alphaIndex > b._alphaIndex) {
  16060. return 1;
  16061. }
  16062. if (a._alphaIndex < b._alphaIndex) {
  16063. return -1;
  16064. }
  16065. // Then distance to camera
  16066. return RenderingGroup.backToFrontSortCompare(a, b);
  16067. };
  16068. /**
  16069. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16070. * are rendered back to front.
  16071. *
  16072. * @param a The first submesh
  16073. * @param b The second submesh
  16074. * @returns The result of the comparison
  16075. */
  16076. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16077. // Then distance to camera
  16078. if (a._distanceToCamera < b._distanceToCamera) {
  16079. return 1;
  16080. }
  16081. if (a._distanceToCamera > b._distanceToCamera) {
  16082. return -1;
  16083. }
  16084. return 0;
  16085. };
  16086. /**
  16087. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16088. * are rendered front to back (prevent overdraw).
  16089. *
  16090. * @param a The first submesh
  16091. * @param b The second submesh
  16092. * @returns The result of the comparison
  16093. */
  16094. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16095. // Then distance to camera
  16096. if (a._distanceToCamera < b._distanceToCamera) {
  16097. return -1;
  16098. }
  16099. if (a._distanceToCamera > b._distanceToCamera) {
  16100. return 1;
  16101. }
  16102. return 0;
  16103. };
  16104. /**
  16105. * Resets the different lists of submeshes to prepare a new frame.
  16106. */
  16107. RenderingGroup.prototype.prepare = function () {
  16108. this._opaqueSubMeshes.reset();
  16109. this._transparentSubMeshes.reset();
  16110. this._alphaTestSubMeshes.reset();
  16111. };
  16112. /**
  16113. * Inserts the submesh in its correct queue depending on its material.
  16114. * @param subMesh The submesh to dispatch
  16115. */
  16116. RenderingGroup.prototype.dispatch = function (subMesh) {
  16117. var material = subMesh.getMaterial();
  16118. var mesh = subMesh.getMesh();
  16119. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16120. this._transparentSubMeshes.push(subMesh);
  16121. }
  16122. else if (material.needAlphaTesting()) {
  16123. this._alphaTestSubMeshes.push(subMesh);
  16124. }
  16125. else {
  16126. this._opaqueSubMeshes.push(subMesh); // Opaque
  16127. }
  16128. };
  16129. return RenderingGroup;
  16130. }());
  16131. BABYLON.RenderingGroup = RenderingGroup;
  16132. })(BABYLON || (BABYLON = {}));
  16133. var BABYLON;
  16134. (function (BABYLON) {
  16135. var PointerEventTypes = (function () {
  16136. function PointerEventTypes() {
  16137. }
  16138. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16139. get: function () {
  16140. return PointerEventTypes._POINTERDOWN;
  16141. },
  16142. enumerable: true,
  16143. configurable: true
  16144. });
  16145. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16146. get: function () {
  16147. return PointerEventTypes._POINTERUP;
  16148. },
  16149. enumerable: true,
  16150. configurable: true
  16151. });
  16152. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16153. get: function () {
  16154. return PointerEventTypes._POINTERMOVE;
  16155. },
  16156. enumerable: true,
  16157. configurable: true
  16158. });
  16159. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16160. get: function () {
  16161. return PointerEventTypes._POINTERWHEEL;
  16162. },
  16163. enumerable: true,
  16164. configurable: true
  16165. });
  16166. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16167. get: function () {
  16168. return PointerEventTypes._POINTERPICK;
  16169. },
  16170. enumerable: true,
  16171. configurable: true
  16172. });
  16173. PointerEventTypes._POINTERDOWN = 0x01;
  16174. PointerEventTypes._POINTERUP = 0x02;
  16175. PointerEventTypes._POINTERMOVE = 0x04;
  16176. PointerEventTypes._POINTERWHEEL = 0x08;
  16177. PointerEventTypes._POINTERPICK = 0x10;
  16178. return PointerEventTypes;
  16179. }());
  16180. BABYLON.PointerEventTypes = PointerEventTypes;
  16181. var PointerInfoBase = (function () {
  16182. function PointerInfoBase(type, event) {
  16183. this.type = type;
  16184. this.event = event;
  16185. }
  16186. return PointerInfoBase;
  16187. }());
  16188. BABYLON.PointerInfoBase = PointerInfoBase;
  16189. /**
  16190. * This class is used to store pointer related info for the onPrePointerObservable event.
  16191. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16192. */
  16193. var PointerInfoPre = (function (_super) {
  16194. __extends(PointerInfoPre, _super);
  16195. function PointerInfoPre(type, event, localX, localY) {
  16196. _super.call(this, type, event);
  16197. this.skipOnPointerObservable = false;
  16198. this.localPosition = new BABYLON.Vector2(localX, localY);
  16199. }
  16200. return PointerInfoPre;
  16201. }(PointerInfoBase));
  16202. BABYLON.PointerInfoPre = PointerInfoPre;
  16203. /**
  16204. * This type contains all the data related to a pointer event in Babylon.js.
  16205. * 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.
  16206. */
  16207. var PointerInfo = (function (_super) {
  16208. __extends(PointerInfo, _super);
  16209. function PointerInfo(type, event, pickInfo) {
  16210. _super.call(this, type, event);
  16211. this.pickInfo = pickInfo;
  16212. }
  16213. return PointerInfo;
  16214. }(PointerInfoBase));
  16215. BABYLON.PointerInfo = PointerInfo;
  16216. /**
  16217. * This class is used by the onRenderingGroupObservable
  16218. */
  16219. var RenderingGroupInfo = (function () {
  16220. function RenderingGroupInfo() {
  16221. }
  16222. /**
  16223. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16224. * This stage will be fired no matter what
  16225. */
  16226. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16227. /**
  16228. * Called before opaque object are rendered.
  16229. * This stage will be fired only if there's 3D Opaque content to render
  16230. */
  16231. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16232. /**
  16233. * Called after the opaque objects are rendered and before the transparent ones
  16234. * This stage will be fired only if there's 3D transparent content to render
  16235. */
  16236. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16237. /**
  16238. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16239. * This stage will be fired no matter what
  16240. */
  16241. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16242. return RenderingGroupInfo;
  16243. }());
  16244. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16245. /**
  16246. * Represents a scene to be rendered by the engine.
  16247. * @see http://doc.babylonjs.com/page.php?p=21911
  16248. */
  16249. var Scene = (function () {
  16250. /**
  16251. * @constructor
  16252. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16253. */
  16254. function Scene(engine) {
  16255. // Members
  16256. this.autoClear = true;
  16257. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16258. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16259. this.forceWireframe = false;
  16260. this.forcePointsCloud = false;
  16261. this.forceShowBoundingBoxes = false;
  16262. this.animationsEnabled = true;
  16263. this.constantlyUpdateMeshUnderPointer = false;
  16264. this.useRightHandedSystem = false;
  16265. this.hoverCursor = "pointer";
  16266. // Events
  16267. /**
  16268. * An event triggered when the scene is disposed.
  16269. * @type {BABYLON.Observable}
  16270. */
  16271. this.onDisposeObservable = new BABYLON.Observable();
  16272. /**
  16273. * An event triggered before rendering the scene
  16274. * @type {BABYLON.Observable}
  16275. */
  16276. this.onBeforeRenderObservable = new BABYLON.Observable();
  16277. /**
  16278. * An event triggered after rendering the scene
  16279. * @type {BABYLON.Observable}
  16280. */
  16281. this.onAfterRenderObservable = new BABYLON.Observable();
  16282. /**
  16283. * An event triggered when the scene is ready
  16284. * @type {BABYLON.Observable}
  16285. */
  16286. this.onReadyObservable = new BABYLON.Observable();
  16287. /**
  16288. * An event triggered before rendering a camera
  16289. * @type {BABYLON.Observable}
  16290. */
  16291. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16292. /**
  16293. * An event triggered after rendering a camera
  16294. * @type {BABYLON.Observable}
  16295. */
  16296. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16297. /**
  16298. * An event triggered when a camera is created
  16299. * @type {BABYLON.Observable}
  16300. */
  16301. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16302. /**
  16303. * An event triggered when a camera is removed
  16304. * @type {BABYLON.Observable}
  16305. */
  16306. this.onCameraRemovedObservable = new BABYLON.Observable();
  16307. /**
  16308. * An event triggered when a light is created
  16309. * @type {BABYLON.Observable}
  16310. */
  16311. this.onNewLightAddedObservable = new BABYLON.Observable();
  16312. /**
  16313. * An event triggered when a light is removed
  16314. * @type {BABYLON.Observable}
  16315. */
  16316. this.onLightRemovedObservable = new BABYLON.Observable();
  16317. /**
  16318. * An event triggered when a geometry is created
  16319. * @type {BABYLON.Observable}
  16320. */
  16321. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16322. /**
  16323. * An event triggered when a geometry is removed
  16324. * @type {BABYLON.Observable}
  16325. */
  16326. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16327. /**
  16328. * An event triggered when a mesh is created
  16329. * @type {BABYLON.Observable}
  16330. */
  16331. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16332. /**
  16333. * An event triggered when a mesh is removed
  16334. * @type {BABYLON.Observable}
  16335. */
  16336. this.onMeshRemovedObservable = new BABYLON.Observable();
  16337. /**
  16338. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16339. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16340. * 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)
  16341. */
  16342. this.onRenderingGroupObservable = new BABYLON.Observable();
  16343. // Animations
  16344. this.animations = [];
  16345. /**
  16346. * 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).
  16347. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16348. */
  16349. this.onPrePointerObservable = new BABYLON.Observable();
  16350. /**
  16351. * Observable event triggered each time an input event is received from the rendering canvas
  16352. */
  16353. this.onPointerObservable = new BABYLON.Observable();
  16354. 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
  16355. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16356. this._startingPointerTime = 0;
  16357. // Fog
  16358. /**
  16359. * is fog enabled on this scene.
  16360. * @type {boolean}
  16361. */
  16362. this.fogEnabled = true;
  16363. this.fogMode = Scene.FOGMODE_NONE;
  16364. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16365. this.fogDensity = 0.1;
  16366. this.fogStart = 0;
  16367. this.fogEnd = 1000.0;
  16368. // Lights
  16369. /**
  16370. * is shadow enabled on this scene.
  16371. * @type {boolean}
  16372. */
  16373. this.shadowsEnabled = true;
  16374. /**
  16375. * is light enabled on this scene.
  16376. * @type {boolean}
  16377. */
  16378. this.lightsEnabled = true;
  16379. /**
  16380. * All of the lights added to this scene.
  16381. * @see BABYLON.Light
  16382. * @type {BABYLON.Light[]}
  16383. */
  16384. this.lights = new Array();
  16385. // Cameras
  16386. /**
  16387. * All of the cameras added to this scene.
  16388. * @see BABYLON.Camera
  16389. * @type {BABYLON.Camera[]}
  16390. */
  16391. this.cameras = new Array();
  16392. this.activeCameras = new Array();
  16393. // Meshes
  16394. /**
  16395. * All of the (abstract) meshes added to this scene.
  16396. * @see BABYLON.AbstractMesh
  16397. * @type {BABYLON.AbstractMesh[]}
  16398. */
  16399. this.meshes = new Array();
  16400. // Geometries
  16401. this._geometries = new Array();
  16402. this.materials = new Array();
  16403. this.multiMaterials = new Array();
  16404. // Textures
  16405. this.texturesEnabled = true;
  16406. this.textures = new Array();
  16407. // Particles
  16408. this.particlesEnabled = true;
  16409. this.particleSystems = new Array();
  16410. // Sprites
  16411. this.spritesEnabled = true;
  16412. this.spriteManagers = new Array();
  16413. // Layers
  16414. this.layers = new Array();
  16415. this.highlightLayers = new Array();
  16416. // Skeletons
  16417. this.skeletonsEnabled = true;
  16418. this.skeletons = new Array();
  16419. // Lens flares
  16420. this.lensFlaresEnabled = true;
  16421. this.lensFlareSystems = new Array();
  16422. // Collisions
  16423. this.collisionsEnabled = true;
  16424. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16425. // Postprocesses
  16426. this.postProcessesEnabled = true;
  16427. // Customs render targets
  16428. this.renderTargetsEnabled = true;
  16429. this.dumpNextRenderTargets = false;
  16430. this.customRenderTargets = new Array();
  16431. // Imported meshes
  16432. this.importedMeshesFiles = new Array();
  16433. // Probes
  16434. this.probesEnabled = true;
  16435. this.reflectionProbes = new Array();
  16436. this._actionManagers = new Array();
  16437. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16438. // Procedural textures
  16439. this.proceduralTexturesEnabled = true;
  16440. this._proceduralTextures = new Array();
  16441. this.soundTracks = new Array();
  16442. this._audioEnabled = true;
  16443. this._headphone = false;
  16444. // Performance counters
  16445. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16446. this._totalLightsCounter = new BABYLON.PerfCounter();
  16447. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16448. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16449. this._totalVertices = new BABYLON.PerfCounter();
  16450. this._activeIndices = new BABYLON.PerfCounter();
  16451. this._activeParticles = new BABYLON.PerfCounter();
  16452. this._lastFrameDuration = new BABYLON.PerfCounter();
  16453. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16454. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16455. this._particlesDuration = new BABYLON.PerfCounter();
  16456. this._renderDuration = new BABYLON.PerfCounter();
  16457. this._spritesDuration = new BABYLON.PerfCounter();
  16458. this._activeBones = new BABYLON.PerfCounter();
  16459. this._renderId = 0;
  16460. this._executeWhenReadyTimeoutId = -1;
  16461. this._intermediateRendering = false;
  16462. this._toBeDisposed = new BABYLON.SmartArray(256);
  16463. this._pendingData = []; //ANY
  16464. this._activeMeshes = new BABYLON.SmartArray(256);
  16465. this._processedMaterials = new BABYLON.SmartArray(256);
  16466. this._renderTargets = new BABYLON.SmartArray(256);
  16467. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16468. this._activeSkeletons = new BABYLON.SmartArray(32);
  16469. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16470. this._activeAnimatables = new Array();
  16471. this._transformMatrix = BABYLON.Matrix.Zero();
  16472. this._edgesRenderers = new BABYLON.SmartArray(16);
  16473. this._uniqueIdCounter = 0;
  16474. this._engine = engine;
  16475. engine.scenes.push(this);
  16476. this._externalData = new BABYLON.StringDictionary();
  16477. this._uid = null;
  16478. this._renderingManager = new BABYLON.RenderingManager(this);
  16479. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16480. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16481. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16482. if (BABYLON.OutlineRenderer) {
  16483. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16484. }
  16485. this.attachControl();
  16486. if (BABYLON.SoundTrack) {
  16487. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16488. }
  16489. //simplification queue
  16490. if (BABYLON.SimplificationQueue) {
  16491. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16492. }
  16493. //collision coordinator initialization. For now legacy per default.
  16494. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16495. }
  16496. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16497. get: function () {
  16498. return Scene._FOGMODE_NONE;
  16499. },
  16500. enumerable: true,
  16501. configurable: true
  16502. });
  16503. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16504. get: function () {
  16505. return Scene._FOGMODE_EXP;
  16506. },
  16507. enumerable: true,
  16508. configurable: true
  16509. });
  16510. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16511. get: function () {
  16512. return Scene._FOGMODE_EXP2;
  16513. },
  16514. enumerable: true,
  16515. configurable: true
  16516. });
  16517. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16518. get: function () {
  16519. return Scene._FOGMODE_LINEAR;
  16520. },
  16521. enumerable: true,
  16522. configurable: true
  16523. });
  16524. Object.defineProperty(Scene.prototype, "onDispose", {
  16525. set: function (callback) {
  16526. if (this._onDisposeObserver) {
  16527. this.onDisposeObservable.remove(this._onDisposeObserver);
  16528. }
  16529. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16530. },
  16531. enumerable: true,
  16532. configurable: true
  16533. });
  16534. Object.defineProperty(Scene.prototype, "beforeRender", {
  16535. set: function (callback) {
  16536. if (this._onBeforeRenderObserver) {
  16537. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16538. }
  16539. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16540. },
  16541. enumerable: true,
  16542. configurable: true
  16543. });
  16544. Object.defineProperty(Scene.prototype, "afterRender", {
  16545. set: function (callback) {
  16546. if (this._onAfterRenderObserver) {
  16547. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16548. }
  16549. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16550. },
  16551. enumerable: true,
  16552. configurable: true
  16553. });
  16554. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16555. set: function (callback) {
  16556. if (this._onBeforeCameraRenderObserver) {
  16557. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16558. }
  16559. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16560. },
  16561. enumerable: true,
  16562. configurable: true
  16563. });
  16564. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16565. set: function (callback) {
  16566. if (this._onAfterCameraRenderObserver) {
  16567. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16568. }
  16569. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16570. },
  16571. enumerable: true,
  16572. configurable: true
  16573. });
  16574. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16575. get: function () {
  16576. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16577. },
  16578. enumerable: true,
  16579. configurable: true
  16580. });
  16581. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16582. get: function () {
  16583. if (!this._defaultMaterial) {
  16584. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16585. }
  16586. return this._defaultMaterial;
  16587. },
  16588. enumerable: true,
  16589. configurable: true
  16590. });
  16591. Object.defineProperty(Scene.prototype, "debugLayer", {
  16592. // Properties
  16593. get: function () {
  16594. if (!this._debugLayer) {
  16595. this._debugLayer = new BABYLON.DebugLayer(this);
  16596. }
  16597. return this._debugLayer;
  16598. },
  16599. enumerable: true,
  16600. configurable: true
  16601. });
  16602. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16603. get: function () {
  16604. return this._workerCollisions;
  16605. },
  16606. set: function (enabled) {
  16607. enabled = (enabled && !!Worker);
  16608. this._workerCollisions = enabled;
  16609. if (this.collisionCoordinator) {
  16610. this.collisionCoordinator.destroy();
  16611. }
  16612. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16613. this.collisionCoordinator.init(this);
  16614. },
  16615. enumerable: true,
  16616. configurable: true
  16617. });
  16618. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16619. get: function () {
  16620. return this._selectionOctree;
  16621. },
  16622. enumerable: true,
  16623. configurable: true
  16624. });
  16625. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16626. /**
  16627. * The mesh that is currently under the pointer.
  16628. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16629. */
  16630. get: function () {
  16631. return this._pointerOverMesh;
  16632. },
  16633. enumerable: true,
  16634. configurable: true
  16635. });
  16636. Object.defineProperty(Scene.prototype, "pointerX", {
  16637. /**
  16638. * Current on-screen X position of the pointer
  16639. * @return {number} X position of the pointer
  16640. */
  16641. get: function () {
  16642. return this._pointerX;
  16643. },
  16644. enumerable: true,
  16645. configurable: true
  16646. });
  16647. Object.defineProperty(Scene.prototype, "pointerY", {
  16648. /**
  16649. * Current on-screen Y position of the pointer
  16650. * @return {number} Y position of the pointer
  16651. */
  16652. get: function () {
  16653. return this._pointerY;
  16654. },
  16655. enumerable: true,
  16656. configurable: true
  16657. });
  16658. Scene.prototype.getCachedMaterial = function () {
  16659. return this._cachedMaterial;
  16660. };
  16661. Scene.prototype.getBoundingBoxRenderer = function () {
  16662. return this._boundingBoxRenderer;
  16663. };
  16664. Scene.prototype.getOutlineRenderer = function () {
  16665. return this._outlineRenderer;
  16666. };
  16667. Scene.prototype.getEngine = function () {
  16668. return this._engine;
  16669. };
  16670. Scene.prototype.getTotalVertices = function () {
  16671. return this._totalVertices.current;
  16672. };
  16673. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16674. get: function () {
  16675. return this._totalVertices;
  16676. },
  16677. enumerable: true,
  16678. configurable: true
  16679. });
  16680. Scene.prototype.getActiveIndices = function () {
  16681. return this._activeIndices.current;
  16682. };
  16683. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16684. get: function () {
  16685. return this._activeIndices;
  16686. },
  16687. enumerable: true,
  16688. configurable: true
  16689. });
  16690. Scene.prototype.getActiveParticles = function () {
  16691. return this._activeParticles.current;
  16692. };
  16693. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16694. get: function () {
  16695. return this._activeParticles;
  16696. },
  16697. enumerable: true,
  16698. configurable: true
  16699. });
  16700. Scene.prototype.getActiveBones = function () {
  16701. return this._activeBones.current;
  16702. };
  16703. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16704. get: function () {
  16705. return this._activeBones;
  16706. },
  16707. enumerable: true,
  16708. configurable: true
  16709. });
  16710. // Stats
  16711. Scene.prototype.getLastFrameDuration = function () {
  16712. return this._lastFrameDuration.current;
  16713. };
  16714. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16715. get: function () {
  16716. return this._lastFrameDuration;
  16717. },
  16718. enumerable: true,
  16719. configurable: true
  16720. });
  16721. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16722. return this._evaluateActiveMeshesDuration.current;
  16723. };
  16724. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16725. get: function () {
  16726. return this._evaluateActiveMeshesDuration;
  16727. },
  16728. enumerable: true,
  16729. configurable: true
  16730. });
  16731. Scene.prototype.getActiveMeshes = function () {
  16732. return this._activeMeshes;
  16733. };
  16734. Scene.prototype.getRenderTargetsDuration = function () {
  16735. return this._renderTargetsDuration.current;
  16736. };
  16737. Scene.prototype.getRenderDuration = function () {
  16738. return this._renderDuration.current;
  16739. };
  16740. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16741. get: function () {
  16742. return this._renderDuration;
  16743. },
  16744. enumerable: true,
  16745. configurable: true
  16746. });
  16747. Scene.prototype.getParticlesDuration = function () {
  16748. return this._particlesDuration.current;
  16749. };
  16750. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16751. get: function () {
  16752. return this._particlesDuration;
  16753. },
  16754. enumerable: true,
  16755. configurable: true
  16756. });
  16757. Scene.prototype.getSpritesDuration = function () {
  16758. return this._spritesDuration.current;
  16759. };
  16760. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16761. get: function () {
  16762. return this._spritesDuration;
  16763. },
  16764. enumerable: true,
  16765. configurable: true
  16766. });
  16767. Scene.prototype.getAnimationRatio = function () {
  16768. return this._animationRatio;
  16769. };
  16770. Scene.prototype.getRenderId = function () {
  16771. return this._renderId;
  16772. };
  16773. Scene.prototype.incrementRenderId = function () {
  16774. this._renderId++;
  16775. };
  16776. Scene.prototype._updatePointerPosition = function (evt) {
  16777. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16778. this._pointerX = evt.clientX - canvasRect.left;
  16779. this._pointerY = evt.clientY - canvasRect.top;
  16780. this._unTranslatedPointerX = this._pointerX;
  16781. this._unTranslatedPointerY = this._pointerY;
  16782. if (this.cameraToUseForPointers) {
  16783. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16784. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16785. }
  16786. };
  16787. // Pointers handling
  16788. /**
  16789. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16790. * @param attachUp defines if you want to attach events to pointerup
  16791. * @param attachDown defines if you want to attach events to pointerdown
  16792. * @param attachMove defines if you want to attach events to pointermove
  16793. */
  16794. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16795. var _this = this;
  16796. if (attachUp === void 0) { attachUp = true; }
  16797. if (attachDown === void 0) { attachDown = true; }
  16798. if (attachMove === void 0) { attachMove = true; }
  16799. var spritePredicate = function (sprite) {
  16800. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16801. };
  16802. this._onPointerMove = function (evt) {
  16803. _this._updatePointerPosition(evt);
  16804. // PreObservable support
  16805. if (_this.onPrePointerObservable.hasObservers()) {
  16806. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16807. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16808. _this.onPrePointerObservable.notifyObservers(pi, type);
  16809. if (pi.skipOnPointerObservable) {
  16810. return;
  16811. }
  16812. }
  16813. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16814. return;
  16815. }
  16816. var canvas = _this._engine.getRenderingCanvas();
  16817. if (!_this.pointerMovePredicate) {
  16818. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16819. }
  16820. // Meshes
  16821. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16822. if (pickResult.hit && pickResult.pickedMesh) {
  16823. _this.setPointerOverSprite(null);
  16824. _this.setPointerOverMesh(pickResult.pickedMesh);
  16825. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16826. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16827. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16828. }
  16829. else {
  16830. canvas.style.cursor = _this.hoverCursor;
  16831. }
  16832. }
  16833. else {
  16834. canvas.style.cursor = "";
  16835. }
  16836. }
  16837. else {
  16838. _this.setPointerOverMesh(null);
  16839. // Sprites
  16840. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16841. if (pickResult.hit && pickResult.pickedSprite) {
  16842. _this.setPointerOverSprite(pickResult.pickedSprite);
  16843. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16844. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16845. }
  16846. else {
  16847. canvas.style.cursor = _this.hoverCursor;
  16848. }
  16849. }
  16850. else {
  16851. _this.setPointerOverSprite(null);
  16852. // Restore pointer
  16853. canvas.style.cursor = "";
  16854. }
  16855. }
  16856. if (_this.onPointerMove) {
  16857. _this.onPointerMove(evt, pickResult);
  16858. }
  16859. if (_this.onPointerObservable.hasObservers()) {
  16860. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16861. var pi = new PointerInfo(type, evt, pickResult);
  16862. _this.onPointerObservable.notifyObservers(pi, type);
  16863. }
  16864. };
  16865. this._onPointerDown = function (evt) {
  16866. _this._updatePointerPosition(evt);
  16867. // PreObservable support
  16868. if (_this.onPrePointerObservable.hasObservers()) {
  16869. var type = PointerEventTypes.POINTERDOWN;
  16870. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16871. _this.onPrePointerObservable.notifyObservers(pi, type);
  16872. if (pi.skipOnPointerObservable) {
  16873. return;
  16874. }
  16875. }
  16876. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16877. return;
  16878. }
  16879. _this._startingPointerPosition.x = _this._pointerX;
  16880. _this._startingPointerPosition.y = _this._pointerY;
  16881. _this._startingPointerTime = new Date().getTime();
  16882. if (!_this.pointerDownPredicate) {
  16883. _this.pointerDownPredicate = function (mesh) {
  16884. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16885. };
  16886. }
  16887. // Meshes
  16888. _this._pickedDownMesh = null;
  16889. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16890. if (pickResult.hit && pickResult.pickedMesh) {
  16891. if (pickResult.pickedMesh.actionManager) {
  16892. _this._pickedDownMesh = pickResult.pickedMesh;
  16893. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16894. switch (evt.button) {
  16895. case 0:
  16896. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16897. break;
  16898. case 1:
  16899. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16900. break;
  16901. case 2:
  16902. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16903. break;
  16904. }
  16905. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16906. }
  16907. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16908. var that = _this;
  16909. window.setTimeout(function () {
  16910. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  16911. if (pickResult.hit && pickResult.pickedMesh) {
  16912. if (pickResult.pickedMesh.actionManager) {
  16913. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  16914. that._startingPointerTime = 0;
  16915. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16916. }
  16917. }
  16918. }
  16919. }, BABYLON.ActionManager.LongPressDelay);
  16920. }
  16921. }
  16922. }
  16923. if (_this.onPointerDown) {
  16924. _this.onPointerDown(evt, pickResult);
  16925. }
  16926. if (_this.onPointerObservable.hasObservers()) {
  16927. var type = PointerEventTypes.POINTERDOWN;
  16928. var pi = new PointerInfo(type, evt, pickResult);
  16929. _this.onPointerObservable.notifyObservers(pi, type);
  16930. }
  16931. // Sprites
  16932. _this._pickedDownSprite = null;
  16933. if (_this.spriteManagers.length > 0) {
  16934. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16935. if (pickResult.hit && pickResult.pickedSprite) {
  16936. if (pickResult.pickedSprite.actionManager) {
  16937. _this._pickedDownSprite = pickResult.pickedSprite;
  16938. switch (evt.button) {
  16939. case 0:
  16940. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16941. break;
  16942. case 1:
  16943. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16944. break;
  16945. case 2:
  16946. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16947. break;
  16948. }
  16949. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16950. }
  16951. }
  16952. }
  16953. };
  16954. this._onPointerUp = function (evt) {
  16955. _this._updatePointerPosition(evt);
  16956. // PreObservable support
  16957. if (_this.onPrePointerObservable.hasObservers()) {
  16958. var type = PointerEventTypes.POINTERUP;
  16959. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16960. _this.onPrePointerObservable.notifyObservers(pi, type);
  16961. if (pi.skipOnPointerObservable) {
  16962. return;
  16963. }
  16964. }
  16965. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16966. return;
  16967. }
  16968. if (!_this.pointerUpPredicate) {
  16969. _this.pointerUpPredicate = function (mesh) {
  16970. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16971. };
  16972. }
  16973. // Meshes
  16974. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16975. if (pickResult.hit && pickResult.pickedMesh) {
  16976. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16977. if (_this.onPointerPick) {
  16978. _this.onPointerPick(evt, pickResult);
  16979. }
  16980. if (_this.onPointerObservable.hasObservers()) {
  16981. var type = PointerEventTypes.POINTERPICK;
  16982. var pi = new PointerInfo(type, evt, pickResult);
  16983. _this.onPointerObservable.notifyObservers(pi, type);
  16984. }
  16985. }
  16986. if (pickResult.pickedMesh.actionManager) {
  16987. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16988. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16989. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16990. }
  16991. }
  16992. }
  16993. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16994. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16995. }
  16996. if (_this.onPointerUp) {
  16997. _this.onPointerUp(evt, pickResult);
  16998. }
  16999. if (_this.onPointerObservable.hasObservers()) {
  17000. var type = PointerEventTypes.POINTERUP;
  17001. var pi = new PointerInfo(type, evt, pickResult);
  17002. _this.onPointerObservable.notifyObservers(pi, type);
  17003. }
  17004. _this._startingPointerTime = 0;
  17005. // Sprites
  17006. if (_this.spriteManagers.length > 0) {
  17007. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17008. if (pickResult.hit && pickResult.pickedSprite) {
  17009. if (pickResult.pickedSprite.actionManager) {
  17010. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17011. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17012. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17013. }
  17014. }
  17015. }
  17016. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17017. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17018. }
  17019. }
  17020. };
  17021. this._onKeyDown = function (evt) {
  17022. if (_this.actionManager) {
  17023. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17024. }
  17025. };
  17026. this._onKeyUp = function (evt) {
  17027. if (_this.actionManager) {
  17028. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17029. }
  17030. };
  17031. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17032. var canvas = this._engine.getRenderingCanvas();
  17033. if (attachMove) {
  17034. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17035. // Wheel
  17036. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17037. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17038. }
  17039. if (attachDown) {
  17040. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17041. }
  17042. if (attachUp) {
  17043. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17044. }
  17045. canvas.tabIndex = 1;
  17046. canvas.addEventListener("keydown", this._onKeyDown, false);
  17047. canvas.addEventListener("keyup", this._onKeyUp, false);
  17048. };
  17049. Scene.prototype.detachControl = function () {
  17050. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17051. var canvas = this._engine.getRenderingCanvas();
  17052. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17053. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17054. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17055. // Wheel
  17056. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17057. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17058. canvas.removeEventListener("keydown", this._onKeyDown);
  17059. canvas.removeEventListener("keyup", this._onKeyUp);
  17060. };
  17061. // Ready
  17062. Scene.prototype.isReady = function () {
  17063. if (this._pendingData.length > 0) {
  17064. return false;
  17065. }
  17066. var index;
  17067. for (index = 0; index < this._geometries.length; index++) {
  17068. var geometry = this._geometries[index];
  17069. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17070. return false;
  17071. }
  17072. }
  17073. for (index = 0; index < this.meshes.length; index++) {
  17074. var mesh = this.meshes[index];
  17075. if (!mesh.isReady()) {
  17076. return false;
  17077. }
  17078. var mat = mesh.material;
  17079. if (mat) {
  17080. if (!mat.isReady(mesh)) {
  17081. return false;
  17082. }
  17083. }
  17084. }
  17085. return true;
  17086. };
  17087. Scene.prototype.resetCachedMaterial = function () {
  17088. this._cachedMaterial = null;
  17089. };
  17090. Scene.prototype.registerBeforeRender = function (func) {
  17091. this.onBeforeRenderObservable.add(func);
  17092. };
  17093. Scene.prototype.unregisterBeforeRender = function (func) {
  17094. this.onBeforeRenderObservable.removeCallback(func);
  17095. };
  17096. Scene.prototype.registerAfterRender = function (func) {
  17097. this.onAfterRenderObservable.add(func);
  17098. };
  17099. Scene.prototype.unregisterAfterRender = function (func) {
  17100. this.onAfterRenderObservable.removeCallback(func);
  17101. };
  17102. Scene.prototype._addPendingData = function (data) {
  17103. this._pendingData.push(data);
  17104. };
  17105. Scene.prototype._removePendingData = function (data) {
  17106. var index = this._pendingData.indexOf(data);
  17107. if (index !== -1) {
  17108. this._pendingData.splice(index, 1);
  17109. }
  17110. };
  17111. Scene.prototype.getWaitingItemsCount = function () {
  17112. return this._pendingData.length;
  17113. };
  17114. /**
  17115. * Registers a function to be executed when the scene is ready.
  17116. * @param {Function} func - the function to be executed.
  17117. */
  17118. Scene.prototype.executeWhenReady = function (func) {
  17119. var _this = this;
  17120. this.onReadyObservable.add(func);
  17121. if (this._executeWhenReadyTimeoutId !== -1) {
  17122. return;
  17123. }
  17124. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17125. _this._checkIsReady();
  17126. }, 150);
  17127. };
  17128. Scene.prototype._checkIsReady = function () {
  17129. var _this = this;
  17130. if (this.isReady()) {
  17131. this.onReadyObservable.notifyObservers(this);
  17132. this.onReadyObservable.clear();
  17133. this._executeWhenReadyTimeoutId = -1;
  17134. return;
  17135. }
  17136. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17137. _this._checkIsReady();
  17138. }, 150);
  17139. };
  17140. // Animations
  17141. /**
  17142. * Will start the animation sequence of a given target
  17143. * @param target - the target
  17144. * @param {number} from - from which frame should animation start
  17145. * @param {number} to - till which frame should animation run.
  17146. * @param {boolean} [loop] - should the animation loop
  17147. * @param {number} [speedRatio] - the speed in which to run the animation
  17148. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17149. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17150. * @return {BABYLON.Animatable} the animatable object created for this animation
  17151. * @see BABYLON.Animatable
  17152. * @see http://doc.babylonjs.com/page.php?p=22081
  17153. */
  17154. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17155. if (speedRatio === void 0) { speedRatio = 1.0; }
  17156. this.stopAnimation(target);
  17157. if (!animatable) {
  17158. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17159. }
  17160. // Local animations
  17161. if (target.animations) {
  17162. animatable.appendAnimations(target, target.animations);
  17163. }
  17164. // Children animations
  17165. if (target.getAnimatables) {
  17166. var animatables = target.getAnimatables();
  17167. for (var index = 0; index < animatables.length; index++) {
  17168. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17169. }
  17170. }
  17171. animatable.reset();
  17172. return animatable;
  17173. };
  17174. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17175. if (speedRatio === undefined) {
  17176. speedRatio = 1.0;
  17177. }
  17178. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17179. return animatable;
  17180. };
  17181. Scene.prototype.getAnimatableByTarget = function (target) {
  17182. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17183. if (this._activeAnimatables[index].target === target) {
  17184. return this._activeAnimatables[index];
  17185. }
  17186. }
  17187. return null;
  17188. };
  17189. Object.defineProperty(Scene.prototype, "Animatables", {
  17190. get: function () {
  17191. return this._activeAnimatables;
  17192. },
  17193. enumerable: true,
  17194. configurable: true
  17195. });
  17196. /**
  17197. * Will stop the animation of the given target
  17198. * @param target - the target
  17199. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17200. * @see beginAnimation
  17201. */
  17202. Scene.prototype.stopAnimation = function (target, animationName) {
  17203. var animatable = this.getAnimatableByTarget(target);
  17204. if (animatable) {
  17205. animatable.stop(animationName);
  17206. }
  17207. };
  17208. Scene.prototype._animate = function () {
  17209. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17210. return;
  17211. }
  17212. if (!this._animationStartDate) {
  17213. if (this._pendingData.length > 0) {
  17214. return;
  17215. }
  17216. this._animationStartDate = BABYLON.Tools.Now;
  17217. }
  17218. // Getting time
  17219. var now = BABYLON.Tools.Now;
  17220. var delay = now - this._animationStartDate;
  17221. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17222. this._activeAnimatables[index]._animate(delay);
  17223. }
  17224. };
  17225. // Matrix
  17226. Scene.prototype.getViewMatrix = function () {
  17227. return this._viewMatrix;
  17228. };
  17229. Scene.prototype.getProjectionMatrix = function () {
  17230. return this._projectionMatrix;
  17231. };
  17232. Scene.prototype.getTransformMatrix = function () {
  17233. return this._transformMatrix;
  17234. };
  17235. Scene.prototype.setTransformMatrix = function (view, projection) {
  17236. this._viewMatrix = view;
  17237. this._projectionMatrix = projection;
  17238. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17239. // Update frustum
  17240. if (!this._frustumPlanes) {
  17241. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17242. }
  17243. else {
  17244. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17245. }
  17246. };
  17247. // Methods
  17248. Scene.prototype.addMesh = function (newMesh) {
  17249. newMesh.uniqueId = this._uniqueIdCounter++;
  17250. var position = this.meshes.push(newMesh);
  17251. //notify the collision coordinator
  17252. this.collisionCoordinator.onMeshAdded(newMesh);
  17253. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17254. };
  17255. Scene.prototype.removeMesh = function (toRemove) {
  17256. var index = this.meshes.indexOf(toRemove);
  17257. if (index !== -1) {
  17258. // Remove from the scene if mesh found
  17259. this.meshes.splice(index, 1);
  17260. }
  17261. //notify the collision coordinator
  17262. this.collisionCoordinator.onMeshRemoved(toRemove);
  17263. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17264. return index;
  17265. };
  17266. Scene.prototype.removeSkeleton = function (toRemove) {
  17267. var index = this.skeletons.indexOf(toRemove);
  17268. if (index !== -1) {
  17269. // Remove from the scene if mesh found
  17270. this.skeletons.splice(index, 1);
  17271. }
  17272. return index;
  17273. };
  17274. Scene.prototype.removeLight = function (toRemove) {
  17275. var index = this.lights.indexOf(toRemove);
  17276. if (index !== -1) {
  17277. // Remove from the scene if mesh found
  17278. this.lights.splice(index, 1);
  17279. }
  17280. this.onLightRemovedObservable.notifyObservers(toRemove);
  17281. return index;
  17282. };
  17283. Scene.prototype.removeCamera = function (toRemove) {
  17284. var index = this.cameras.indexOf(toRemove);
  17285. if (index !== -1) {
  17286. // Remove from the scene if mesh found
  17287. this.cameras.splice(index, 1);
  17288. }
  17289. // Remove from activeCameras
  17290. var index2 = this.activeCameras.indexOf(toRemove);
  17291. if (index2 !== -1) {
  17292. // Remove from the scene if mesh found
  17293. this.activeCameras.splice(index2, 1);
  17294. }
  17295. // Reset the activeCamera
  17296. if (this.activeCamera === toRemove) {
  17297. if (this.cameras.length > 0) {
  17298. this.activeCamera = this.cameras[0];
  17299. }
  17300. else {
  17301. this.activeCamera = null;
  17302. }
  17303. }
  17304. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17305. return index;
  17306. };
  17307. Scene.prototype.addLight = function (newLight) {
  17308. newLight.uniqueId = this._uniqueIdCounter++;
  17309. var position = this.lights.push(newLight);
  17310. this.onNewLightAddedObservable.notifyObservers(newLight);
  17311. };
  17312. Scene.prototype.addCamera = function (newCamera) {
  17313. newCamera.uniqueId = this._uniqueIdCounter++;
  17314. var position = this.cameras.push(newCamera);
  17315. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17316. };
  17317. /**
  17318. * Switch active camera
  17319. * @param {Camera} newCamera - new active camera
  17320. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17321. */
  17322. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17323. if (attachControl === void 0) { attachControl = true; }
  17324. var canvas = this._engine.getRenderingCanvas();
  17325. this.activeCamera.detachControl(canvas);
  17326. this.activeCamera = newCamera;
  17327. if (attachControl) {
  17328. newCamera.attachControl(canvas);
  17329. }
  17330. };
  17331. /**
  17332. * sets the active camera of the scene using its ID
  17333. * @param {string} id - the camera's ID
  17334. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17335. * @see activeCamera
  17336. */
  17337. Scene.prototype.setActiveCameraByID = function (id) {
  17338. var camera = this.getCameraByID(id);
  17339. if (camera) {
  17340. this.activeCamera = camera;
  17341. return camera;
  17342. }
  17343. return null;
  17344. };
  17345. /**
  17346. * sets the active camera of the scene using its name
  17347. * @param {string} name - the camera's name
  17348. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17349. * @see activeCamera
  17350. */
  17351. Scene.prototype.setActiveCameraByName = function (name) {
  17352. var camera = this.getCameraByName(name);
  17353. if (camera) {
  17354. this.activeCamera = camera;
  17355. return camera;
  17356. }
  17357. return null;
  17358. };
  17359. /**
  17360. * get a material using its id
  17361. * @param {string} the material's ID
  17362. * @return {BABYLON.Material|null} the material or null if none found.
  17363. */
  17364. Scene.prototype.getMaterialByID = function (id) {
  17365. for (var index = 0; index < this.materials.length; index++) {
  17366. if (this.materials[index].id === id) {
  17367. return this.materials[index];
  17368. }
  17369. }
  17370. return null;
  17371. };
  17372. /**
  17373. * get a material using its name
  17374. * @param {string} the material's name
  17375. * @return {BABYLON.Material|null} the material or null if none found.
  17376. */
  17377. Scene.prototype.getMaterialByName = function (name) {
  17378. for (var index = 0; index < this.materials.length; index++) {
  17379. if (this.materials[index].name === name) {
  17380. return this.materials[index];
  17381. }
  17382. }
  17383. return null;
  17384. };
  17385. Scene.prototype.getLensFlareSystemByName = function (name) {
  17386. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17387. if (this.lensFlareSystems[index].name === name) {
  17388. return this.lensFlareSystems[index];
  17389. }
  17390. }
  17391. return null;
  17392. };
  17393. Scene.prototype.getLensFlareSystemByID = function (id) {
  17394. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17395. if (this.lensFlareSystems[index].id === id) {
  17396. return this.lensFlareSystems[index];
  17397. }
  17398. }
  17399. return null;
  17400. };
  17401. Scene.prototype.getCameraByID = function (id) {
  17402. for (var index = 0; index < this.cameras.length; index++) {
  17403. if (this.cameras[index].id === id) {
  17404. return this.cameras[index];
  17405. }
  17406. }
  17407. return null;
  17408. };
  17409. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17410. for (var index = 0; index < this.cameras.length; index++) {
  17411. if (this.cameras[index].uniqueId === uniqueId) {
  17412. return this.cameras[index];
  17413. }
  17414. }
  17415. return null;
  17416. };
  17417. /**
  17418. * get a camera using its name
  17419. * @param {string} the camera's name
  17420. * @return {BABYLON.Camera|null} the camera or null if none found.
  17421. */
  17422. Scene.prototype.getCameraByName = function (name) {
  17423. for (var index = 0; index < this.cameras.length; index++) {
  17424. if (this.cameras[index].name === name) {
  17425. return this.cameras[index];
  17426. }
  17427. }
  17428. return null;
  17429. };
  17430. /**
  17431. * get a bone using its id
  17432. * @param {string} the bone's id
  17433. * @return {BABYLON.Bone|null} the bone or null if not found
  17434. */
  17435. Scene.prototype.getBoneByID = function (id) {
  17436. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17437. var skeleton = this.skeletons[skeletonIndex];
  17438. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17439. if (skeleton.bones[boneIndex].id === id) {
  17440. return skeleton.bones[boneIndex];
  17441. }
  17442. }
  17443. }
  17444. return null;
  17445. };
  17446. /**
  17447. * get a bone using its id
  17448. * @param {string} the bone's name
  17449. * @return {BABYLON.Bone|null} the bone or null if not found
  17450. */
  17451. Scene.prototype.getBoneByName = function (name) {
  17452. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17453. var skeleton = this.skeletons[skeletonIndex];
  17454. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17455. if (skeleton.bones[boneIndex].name === name) {
  17456. return skeleton.bones[boneIndex];
  17457. }
  17458. }
  17459. }
  17460. return null;
  17461. };
  17462. /**
  17463. * get a light node using its name
  17464. * @param {string} the light's name
  17465. * @return {BABYLON.Light|null} the light or null if none found.
  17466. */
  17467. Scene.prototype.getLightByName = function (name) {
  17468. for (var index = 0; index < this.lights.length; index++) {
  17469. if (this.lights[index].name === name) {
  17470. return this.lights[index];
  17471. }
  17472. }
  17473. return null;
  17474. };
  17475. /**
  17476. * get a light node using its ID
  17477. * @param {string} the light's id
  17478. * @return {BABYLON.Light|null} the light or null if none found.
  17479. */
  17480. Scene.prototype.getLightByID = function (id) {
  17481. for (var index = 0; index < this.lights.length; index++) {
  17482. if (this.lights[index].id === id) {
  17483. return this.lights[index];
  17484. }
  17485. }
  17486. return null;
  17487. };
  17488. /**
  17489. * get a light node using its scene-generated unique ID
  17490. * @param {number} the light's unique id
  17491. * @return {BABYLON.Light|null} the light or null if none found.
  17492. */
  17493. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17494. for (var index = 0; index < this.lights.length; index++) {
  17495. if (this.lights[index].uniqueId === uniqueId) {
  17496. return this.lights[index];
  17497. }
  17498. }
  17499. return null;
  17500. };
  17501. /**
  17502. * get a particle system by id
  17503. * @param id {number} the particle system id
  17504. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17505. */
  17506. Scene.prototype.getParticleSystemByID = function (id) {
  17507. for (var index = 0; index < this.particleSystems.length; index++) {
  17508. if (this.particleSystems[index].id === id) {
  17509. return this.particleSystems[index];
  17510. }
  17511. }
  17512. return null;
  17513. };
  17514. /**
  17515. * get a geometry using its ID
  17516. * @param {string} the geometry's id
  17517. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17518. */
  17519. Scene.prototype.getGeometryByID = function (id) {
  17520. for (var index = 0; index < this._geometries.length; index++) {
  17521. if (this._geometries[index].id === id) {
  17522. return this._geometries[index];
  17523. }
  17524. }
  17525. return null;
  17526. };
  17527. /**
  17528. * add a new geometry to this scene.
  17529. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17530. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17531. * @return {boolean} was the geometry added or not
  17532. */
  17533. Scene.prototype.pushGeometry = function (geometry, force) {
  17534. if (!force && this.getGeometryByID(geometry.id)) {
  17535. return false;
  17536. }
  17537. this._geometries.push(geometry);
  17538. //notify the collision coordinator
  17539. this.collisionCoordinator.onGeometryAdded(geometry);
  17540. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17541. return true;
  17542. };
  17543. /**
  17544. * Removes an existing geometry
  17545. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17546. * @return {boolean} was the geometry removed or not
  17547. */
  17548. Scene.prototype.removeGeometry = function (geometry) {
  17549. var index = this._geometries.indexOf(geometry);
  17550. if (index > -1) {
  17551. this._geometries.splice(index, 1);
  17552. //notify the collision coordinator
  17553. this.collisionCoordinator.onGeometryDeleted(geometry);
  17554. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17555. return true;
  17556. }
  17557. return false;
  17558. };
  17559. Scene.prototype.getGeometries = function () {
  17560. return this._geometries;
  17561. };
  17562. /**
  17563. * Get the first added mesh found of a given ID
  17564. * @param {string} id - the id to search for
  17565. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17566. */
  17567. Scene.prototype.getMeshByID = function (id) {
  17568. for (var index = 0; index < this.meshes.length; index++) {
  17569. if (this.meshes[index].id === id) {
  17570. return this.meshes[index];
  17571. }
  17572. }
  17573. return null;
  17574. };
  17575. Scene.prototype.getMeshesByID = function (id) {
  17576. return this.meshes.filter(function (m) {
  17577. return m.id === id;
  17578. });
  17579. };
  17580. /**
  17581. * Get a mesh with its auto-generated unique id
  17582. * @param {number} uniqueId - the unique id to search for
  17583. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17584. */
  17585. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17586. for (var index = 0; index < this.meshes.length; index++) {
  17587. if (this.meshes[index].uniqueId === uniqueId) {
  17588. return this.meshes[index];
  17589. }
  17590. }
  17591. return null;
  17592. };
  17593. /**
  17594. * Get a the last added mesh found of a given ID
  17595. * @param {string} id - the id to search for
  17596. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17597. */
  17598. Scene.prototype.getLastMeshByID = function (id) {
  17599. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17600. if (this.meshes[index].id === id) {
  17601. return this.meshes[index];
  17602. }
  17603. }
  17604. return null;
  17605. };
  17606. /**
  17607. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17608. * @param {string} id - the id to search for
  17609. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17610. */
  17611. Scene.prototype.getLastEntryByID = function (id) {
  17612. var index;
  17613. for (index = this.meshes.length - 1; index >= 0; index--) {
  17614. if (this.meshes[index].id === id) {
  17615. return this.meshes[index];
  17616. }
  17617. }
  17618. for (index = this.cameras.length - 1; index >= 0; index--) {
  17619. if (this.cameras[index].id === id) {
  17620. return this.cameras[index];
  17621. }
  17622. }
  17623. for (index = this.lights.length - 1; index >= 0; index--) {
  17624. if (this.lights[index].id === id) {
  17625. return this.lights[index];
  17626. }
  17627. }
  17628. return null;
  17629. };
  17630. Scene.prototype.getNodeByID = function (id) {
  17631. var mesh = this.getMeshByID(id);
  17632. if (mesh) {
  17633. return mesh;
  17634. }
  17635. var light = this.getLightByID(id);
  17636. if (light) {
  17637. return light;
  17638. }
  17639. var camera = this.getCameraByID(id);
  17640. if (camera) {
  17641. return camera;
  17642. }
  17643. var bone = this.getBoneByID(id);
  17644. return bone;
  17645. };
  17646. Scene.prototype.getNodeByName = function (name) {
  17647. var mesh = this.getMeshByName(name);
  17648. if (mesh) {
  17649. return mesh;
  17650. }
  17651. var light = this.getLightByName(name);
  17652. if (light) {
  17653. return light;
  17654. }
  17655. var camera = this.getCameraByName(name);
  17656. if (camera) {
  17657. return camera;
  17658. }
  17659. var bone = this.getBoneByName(name);
  17660. return bone;
  17661. };
  17662. Scene.prototype.getMeshByName = function (name) {
  17663. for (var index = 0; index < this.meshes.length; index++) {
  17664. if (this.meshes[index].name === name) {
  17665. return this.meshes[index];
  17666. }
  17667. }
  17668. return null;
  17669. };
  17670. Scene.prototype.getSoundByName = function (name) {
  17671. var index;
  17672. if (BABYLON.AudioEngine) {
  17673. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17674. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17675. return this.mainSoundTrack.soundCollection[index];
  17676. }
  17677. }
  17678. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17679. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17680. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17681. return this.soundTracks[sdIndex].soundCollection[index];
  17682. }
  17683. }
  17684. }
  17685. }
  17686. return null;
  17687. };
  17688. Scene.prototype.getLastSkeletonByID = function (id) {
  17689. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17690. if (this.skeletons[index].id === id) {
  17691. return this.skeletons[index];
  17692. }
  17693. }
  17694. return null;
  17695. };
  17696. Scene.prototype.getSkeletonById = function (id) {
  17697. for (var index = 0; index < this.skeletons.length; index++) {
  17698. if (this.skeletons[index].id === id) {
  17699. return this.skeletons[index];
  17700. }
  17701. }
  17702. return null;
  17703. };
  17704. Scene.prototype.getSkeletonByName = function (name) {
  17705. for (var index = 0; index < this.skeletons.length; index++) {
  17706. if (this.skeletons[index].name === name) {
  17707. return this.skeletons[index];
  17708. }
  17709. }
  17710. return null;
  17711. };
  17712. Scene.prototype.isActiveMesh = function (mesh) {
  17713. return (this._activeMeshes.indexOf(mesh) !== -1);
  17714. };
  17715. Object.defineProperty(Scene.prototype, "uid", {
  17716. /**
  17717. * Return a unique id as a string which can serve as an identifier for the scene
  17718. */
  17719. get: function () {
  17720. if (!this._uid) {
  17721. this._uid = BABYLON.Tools.RandomId();
  17722. }
  17723. return this._uid;
  17724. },
  17725. enumerable: true,
  17726. configurable: true
  17727. });
  17728. /**
  17729. * Add an externaly attached data from its key.
  17730. * This method call will fail and return false, if such key already exists.
  17731. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17732. * @param key the unique key that identifies the data
  17733. * @param data the data object to associate to the key for this Engine instance
  17734. * @return true if no such key were already present and the data was added successfully, false otherwise
  17735. */
  17736. Scene.prototype.addExternalData = function (key, data) {
  17737. return this._externalData.add(key, data);
  17738. };
  17739. /**
  17740. * Get an externaly attached data from its key
  17741. * @param key the unique key that identifies the data
  17742. * @return the associated data, if present (can be null), or undefined if not present
  17743. */
  17744. Scene.prototype.getExternalData = function (key) {
  17745. return this._externalData.get(key);
  17746. };
  17747. /**
  17748. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17749. * @param key the unique key that identifies the data
  17750. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17751. * @return the associated data, can be null if the factory returned null.
  17752. */
  17753. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17754. return this._externalData.getOrAddWithFactory(key, factory);
  17755. };
  17756. /**
  17757. * Remove an externaly attached data from the Engine instance
  17758. * @param key the unique key that identifies the data
  17759. * @return true if the data was successfully removed, false if it doesn't exist
  17760. */
  17761. Scene.prototype.removeExternalData = function (key) {
  17762. return this._externalData.remove(key);
  17763. };
  17764. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17765. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17766. var material = subMesh.getMaterial();
  17767. if (mesh.showSubMeshesBoundingBox) {
  17768. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17769. }
  17770. if (material) {
  17771. // Render targets
  17772. if (material.getRenderTargetTextures) {
  17773. if (this._processedMaterials.indexOf(material) === -1) {
  17774. this._processedMaterials.push(material);
  17775. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17776. }
  17777. }
  17778. // Dispatch
  17779. this._activeIndices.addCount(subMesh.indexCount, false);
  17780. this._renderingManager.dispatch(subMesh);
  17781. }
  17782. }
  17783. };
  17784. Scene.prototype._isInIntermediateRendering = function () {
  17785. return this._intermediateRendering;
  17786. };
  17787. Scene.prototype._evaluateActiveMeshes = function () {
  17788. this.activeCamera._activeMeshes.reset();
  17789. this._activeMeshes.reset();
  17790. this._renderingManager.reset();
  17791. this._processedMaterials.reset();
  17792. this._activeParticleSystems.reset();
  17793. this._activeSkeletons.reset();
  17794. this._softwareSkinnedMeshes.reset();
  17795. this._boundingBoxRenderer.reset();
  17796. this._edgesRenderers.reset();
  17797. // Meshes
  17798. var meshes;
  17799. var len;
  17800. if (this._selectionOctree) {
  17801. var selection = this._selectionOctree.select(this._frustumPlanes);
  17802. meshes = selection.data;
  17803. len = selection.length;
  17804. }
  17805. else {
  17806. len = this.meshes.length;
  17807. meshes = this.meshes;
  17808. }
  17809. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17810. var mesh = meshes[meshIndex];
  17811. if (mesh.isBlocked) {
  17812. continue;
  17813. }
  17814. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17815. if (!mesh.isReady() || !mesh.isEnabled()) {
  17816. continue;
  17817. }
  17818. mesh.computeWorldMatrix();
  17819. // Intersections
  17820. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17821. this._meshesForIntersections.pushNoDuplicate(mesh);
  17822. }
  17823. // Switch to current LOD
  17824. var meshLOD = mesh.getLOD(this.activeCamera);
  17825. if (!meshLOD) {
  17826. continue;
  17827. }
  17828. mesh._preActivate();
  17829. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17830. this._activeMeshes.push(mesh);
  17831. this.activeCamera._activeMeshes.push(mesh);
  17832. mesh._activate(this._renderId);
  17833. this._activeMesh(mesh, meshLOD);
  17834. }
  17835. }
  17836. // Particle systems
  17837. this._particlesDuration.beginMonitoring();
  17838. var beforeParticlesDate = BABYLON.Tools.Now;
  17839. if (this.particlesEnabled) {
  17840. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17841. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17842. var particleSystem = this.particleSystems[particleIndex];
  17843. if (!particleSystem.isStarted()) {
  17844. continue;
  17845. }
  17846. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17847. this._activeParticleSystems.push(particleSystem);
  17848. particleSystem.animate();
  17849. }
  17850. }
  17851. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17852. }
  17853. this._particlesDuration.endMonitoring(false);
  17854. };
  17855. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17856. if (mesh.skeleton && this.skeletonsEnabled) {
  17857. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17858. mesh.skeleton.prepare();
  17859. }
  17860. if (!mesh.computeBonesUsingShaders) {
  17861. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17862. }
  17863. }
  17864. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17865. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17866. }
  17867. if (sourceMesh._edgesRenderer) {
  17868. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17869. }
  17870. if (mesh && mesh.subMeshes) {
  17871. // Submeshes Octrees
  17872. var len;
  17873. var subMeshes;
  17874. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17875. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17876. len = intersections.length;
  17877. subMeshes = intersections.data;
  17878. }
  17879. else {
  17880. subMeshes = mesh.subMeshes;
  17881. len = subMeshes.length;
  17882. }
  17883. for (var subIndex = 0; subIndex < len; subIndex++) {
  17884. var subMesh = subMeshes[subIndex];
  17885. this._evaluateSubMesh(subMesh, mesh);
  17886. }
  17887. }
  17888. };
  17889. Scene.prototype.updateTransformMatrix = function (force) {
  17890. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17891. };
  17892. Scene.prototype._renderForCamera = function (camera) {
  17893. var engine = this._engine;
  17894. var startTime = BABYLON.Tools.Now;
  17895. this.activeCamera = camera;
  17896. if (!this.activeCamera)
  17897. throw new Error("Active camera not set");
  17898. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17899. // Viewport
  17900. engine.setViewport(this.activeCamera.viewport);
  17901. // Camera
  17902. this.resetCachedMaterial();
  17903. this._renderId++;
  17904. this.updateTransformMatrix();
  17905. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17906. // Meshes
  17907. this._evaluateActiveMeshesDuration.beginMonitoring();
  17908. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17909. this._evaluateActiveMeshes();
  17910. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17911. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17912. // Software skinning
  17913. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17914. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17915. mesh.applySkeleton(mesh.skeleton);
  17916. }
  17917. // Render targets
  17918. this._renderTargetsDuration.beginMonitoring();
  17919. var needsRestoreFrameBuffer = false;
  17920. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17921. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17922. this._intermediateRendering = true;
  17923. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17924. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17925. var renderTarget = this._renderTargets.data[renderIndex];
  17926. if (renderTarget._shouldRender()) {
  17927. this._renderId++;
  17928. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17929. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17930. }
  17931. }
  17932. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17933. this._intermediateRendering = false;
  17934. this._renderId++;
  17935. needsRestoreFrameBuffer = true; // Restore back buffer
  17936. }
  17937. // Render HighlightLayer Texture
  17938. var stencilState = this._engine.getStencilBuffer();
  17939. var renderhighlights = false;
  17940. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17941. this._intermediateRendering = true;
  17942. for (var i = 0; i < this.highlightLayers.length; i++) {
  17943. var highlightLayer = this.highlightLayers[i];
  17944. if (highlightLayer.shouldRender() &&
  17945. (!highlightLayer.camera ||
  17946. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17947. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17948. renderhighlights = true;
  17949. var renderTarget = highlightLayer._mainTexture;
  17950. if (renderTarget._shouldRender()) {
  17951. this._renderId++;
  17952. renderTarget.render(false, false);
  17953. needsRestoreFrameBuffer = true;
  17954. }
  17955. }
  17956. }
  17957. this._intermediateRendering = false;
  17958. this._renderId++;
  17959. }
  17960. if (needsRestoreFrameBuffer) {
  17961. engine.restoreDefaultFramebuffer();
  17962. }
  17963. this._renderTargetsDuration.endMonitoring(false);
  17964. // Prepare Frame
  17965. this.postProcessManager._prepareFrame();
  17966. this._renderDuration.beginMonitoring();
  17967. // Backgrounds
  17968. var layerIndex;
  17969. var layer;
  17970. if (this.layers.length) {
  17971. engine.setDepthBuffer(false);
  17972. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17973. layer = this.layers[layerIndex];
  17974. if (layer.isBackground) {
  17975. layer.render();
  17976. }
  17977. }
  17978. engine.setDepthBuffer(true);
  17979. }
  17980. // Render
  17981. BABYLON.Tools.StartPerformanceCounter("Main render");
  17982. // Activate HighlightLayer stencil
  17983. if (renderhighlights) {
  17984. this._engine.setStencilBuffer(true);
  17985. }
  17986. this._renderingManager.render(null, null, true, true);
  17987. // Restore HighlightLayer stencil
  17988. if (renderhighlights) {
  17989. this._engine.setStencilBuffer(stencilState);
  17990. }
  17991. BABYLON.Tools.EndPerformanceCounter("Main render");
  17992. // Bounding boxes
  17993. this._boundingBoxRenderer.render();
  17994. // Edges
  17995. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17996. this._edgesRenderers.data[edgesRendererIndex].render();
  17997. }
  17998. // Lens flares
  17999. if (this.lensFlaresEnabled) {
  18000. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18001. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18002. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18003. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18004. lensFlareSystem.render();
  18005. }
  18006. }
  18007. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18008. }
  18009. // Foregrounds
  18010. if (this.layers.length) {
  18011. engine.setDepthBuffer(false);
  18012. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18013. layer = this.layers[layerIndex];
  18014. if (!layer.isBackground) {
  18015. layer.render();
  18016. }
  18017. }
  18018. engine.setDepthBuffer(true);
  18019. }
  18020. // Highlight Layer
  18021. if (renderhighlights) {
  18022. engine.setDepthBuffer(false);
  18023. for (var i = 0; i < this.highlightLayers.length; i++) {
  18024. if (this.highlightLayers[i].shouldRender()) {
  18025. this.highlightLayers[i].render();
  18026. }
  18027. }
  18028. engine.setDepthBuffer(true);
  18029. }
  18030. this._renderDuration.endMonitoring(false);
  18031. // Finalize frame
  18032. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18033. // Update camera
  18034. this.activeCamera._updateFromScene();
  18035. // Reset some special arrays
  18036. this._renderTargets.reset();
  18037. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18038. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18039. };
  18040. Scene.prototype._processSubCameras = function (camera) {
  18041. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18042. this._renderForCamera(camera);
  18043. return;
  18044. }
  18045. // rig cameras
  18046. for (var index = 0; index < camera._rigCameras.length; index++) {
  18047. this._renderForCamera(camera._rigCameras[index]);
  18048. }
  18049. this.activeCamera = camera;
  18050. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18051. // Update camera
  18052. this.activeCamera._updateFromScene();
  18053. };
  18054. Scene.prototype._checkIntersections = function () {
  18055. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18056. var sourceMesh = this._meshesForIntersections.data[index];
  18057. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18058. var action = sourceMesh.actionManager.actions[actionIndex];
  18059. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18060. var parameters = action.getTriggerParameter();
  18061. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18062. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18063. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18064. if (areIntersecting && currentIntersectionInProgress === -1) {
  18065. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18066. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18067. sourceMesh._intersectionsInProgress.push(otherMesh);
  18068. }
  18069. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18070. sourceMesh._intersectionsInProgress.push(otherMesh);
  18071. }
  18072. }
  18073. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18074. //They intersected, and now they don't.
  18075. //is this trigger an exit trigger? execute an event.
  18076. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18077. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18078. }
  18079. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18080. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18081. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18082. }
  18083. }
  18084. }
  18085. }
  18086. }
  18087. };
  18088. Scene.prototype.render = function () {
  18089. this._lastFrameDuration.beginMonitoring();
  18090. this._particlesDuration.fetchNewFrame();
  18091. this._spritesDuration.fetchNewFrame();
  18092. this._activeParticles.fetchNewFrame();
  18093. this._renderDuration.fetchNewFrame();
  18094. this._renderTargetsDuration.fetchNewFrame();
  18095. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18096. this._totalVertices.fetchNewFrame();
  18097. this._activeIndices.fetchNewFrame();
  18098. this._activeBones.fetchNewFrame();
  18099. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18100. this._meshesForIntersections.reset();
  18101. this.resetCachedMaterial();
  18102. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18103. // Actions
  18104. if (this.actionManager) {
  18105. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18106. }
  18107. //Simplification Queue
  18108. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18109. this.simplificationQueue.executeNext();
  18110. }
  18111. // Animations
  18112. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18113. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18114. this._animate();
  18115. // Physics
  18116. if (this._physicsEngine) {
  18117. BABYLON.Tools.StartPerformanceCounter("Physics");
  18118. this._physicsEngine._step(deltaTime / 1000.0);
  18119. BABYLON.Tools.EndPerformanceCounter("Physics");
  18120. }
  18121. // Before render
  18122. this.onBeforeRenderObservable.notifyObservers(this);
  18123. // Customs render targets
  18124. this._renderTargetsDuration.beginMonitoring();
  18125. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18126. var engine = this.getEngine();
  18127. var currentActiveCamera = this.activeCamera;
  18128. if (this.renderTargetsEnabled) {
  18129. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18130. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18131. var renderTarget = this.customRenderTargets[customIndex];
  18132. if (renderTarget._shouldRender()) {
  18133. this._renderId++;
  18134. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18135. if (!this.activeCamera)
  18136. throw new Error("Active camera not set");
  18137. // Viewport
  18138. engine.setViewport(this.activeCamera.viewport);
  18139. // Camera
  18140. this.updateTransformMatrix();
  18141. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18142. }
  18143. }
  18144. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18145. this._renderId++;
  18146. }
  18147. if (this.customRenderTargets.length > 0) {
  18148. engine.restoreDefaultFramebuffer();
  18149. }
  18150. this._renderTargetsDuration.endMonitoring();
  18151. this.activeCamera = currentActiveCamera;
  18152. // Procedural textures
  18153. if (this.proceduralTexturesEnabled) {
  18154. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18155. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18156. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18157. if (proceduralTexture._shouldRender()) {
  18158. proceduralTexture.render();
  18159. }
  18160. }
  18161. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18162. }
  18163. // Clear
  18164. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18165. // Shadows
  18166. if (this.shadowsEnabled) {
  18167. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18168. var light = this.lights[lightIndex];
  18169. var shadowGenerator = light.getShadowGenerator();
  18170. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18171. this._renderTargets.push(shadowGenerator.getShadowMap());
  18172. }
  18173. }
  18174. }
  18175. // Depth renderer
  18176. if (this._depthRenderer) {
  18177. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18178. }
  18179. // RenderPipeline
  18180. this.postProcessRenderPipelineManager.update();
  18181. // Multi-cameras?
  18182. if (this.activeCameras.length > 0) {
  18183. var currentRenderId = this._renderId;
  18184. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18185. this._renderId = currentRenderId;
  18186. if (cameraIndex > 0) {
  18187. this._engine.clear(0, false, true, true);
  18188. }
  18189. this._processSubCameras(this.activeCameras[cameraIndex]);
  18190. }
  18191. }
  18192. else {
  18193. if (!this.activeCamera) {
  18194. throw new Error("No camera defined");
  18195. }
  18196. this._processSubCameras(this.activeCamera);
  18197. }
  18198. // Intersection checks
  18199. this._checkIntersections();
  18200. // Update the audio listener attached to the camera
  18201. if (BABYLON.AudioEngine) {
  18202. this._updateAudioParameters();
  18203. }
  18204. // After render
  18205. if (this.afterRender) {
  18206. this.afterRender();
  18207. }
  18208. this.onAfterRenderObservable.notifyObservers(this);
  18209. // Cleaning
  18210. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18211. this._toBeDisposed.data[index].dispose();
  18212. this._toBeDisposed[index] = null;
  18213. }
  18214. this._toBeDisposed.reset();
  18215. if (this.dumpNextRenderTargets) {
  18216. this.dumpNextRenderTargets = false;
  18217. }
  18218. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18219. this._lastFrameDuration.endMonitoring();
  18220. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18221. this._totalLightsCounter.addCount(this.lights.length, true);
  18222. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18223. this._totalTexturesCounter.addCount(this.textures.length, true);
  18224. this._activeBones.addCount(0, true);
  18225. this._activeIndices.addCount(0, true);
  18226. this._activeParticles.addCount(0, true);
  18227. };
  18228. Scene.prototype._updateAudioParameters = function () {
  18229. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18230. return;
  18231. }
  18232. var listeningCamera;
  18233. var audioEngine = BABYLON.Engine.audioEngine;
  18234. if (this.activeCameras.length > 0) {
  18235. listeningCamera = this.activeCameras[0];
  18236. }
  18237. else {
  18238. listeningCamera = this.activeCamera;
  18239. }
  18240. if (listeningCamera && audioEngine.canUseWebAudio) {
  18241. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18242. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18243. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18244. cameraDirection.normalize();
  18245. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18246. var i;
  18247. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18248. var sound = this.mainSoundTrack.soundCollection[i];
  18249. if (sound.useCustomAttenuation) {
  18250. sound.updateDistanceFromListener();
  18251. }
  18252. }
  18253. for (i = 0; i < this.soundTracks.length; i++) {
  18254. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18255. sound = this.soundTracks[i].soundCollection[j];
  18256. if (sound.useCustomAttenuation) {
  18257. sound.updateDistanceFromListener();
  18258. }
  18259. }
  18260. }
  18261. }
  18262. };
  18263. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18264. // Audio
  18265. get: function () {
  18266. return this._audioEnabled;
  18267. },
  18268. set: function (value) {
  18269. this._audioEnabled = value;
  18270. if (BABYLON.AudioEngine) {
  18271. if (this._audioEnabled) {
  18272. this._enableAudio();
  18273. }
  18274. else {
  18275. this._disableAudio();
  18276. }
  18277. }
  18278. },
  18279. enumerable: true,
  18280. configurable: true
  18281. });
  18282. Scene.prototype._disableAudio = function () {
  18283. var i;
  18284. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18285. this.mainSoundTrack.soundCollection[i].pause();
  18286. }
  18287. for (i = 0; i < this.soundTracks.length; i++) {
  18288. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18289. this.soundTracks[i].soundCollection[j].pause();
  18290. }
  18291. }
  18292. };
  18293. Scene.prototype._enableAudio = function () {
  18294. var i;
  18295. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18296. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18297. this.mainSoundTrack.soundCollection[i].play();
  18298. }
  18299. }
  18300. for (i = 0; i < this.soundTracks.length; i++) {
  18301. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18302. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18303. this.soundTracks[i].soundCollection[j].play();
  18304. }
  18305. }
  18306. }
  18307. };
  18308. Object.defineProperty(Scene.prototype, "headphone", {
  18309. get: function () {
  18310. return this._headphone;
  18311. },
  18312. set: function (value) {
  18313. this._headphone = value;
  18314. if (BABYLON.AudioEngine) {
  18315. if (this._headphone) {
  18316. this._switchAudioModeForHeadphones();
  18317. }
  18318. else {
  18319. this._switchAudioModeForNormalSpeakers();
  18320. }
  18321. }
  18322. },
  18323. enumerable: true,
  18324. configurable: true
  18325. });
  18326. Scene.prototype._switchAudioModeForHeadphones = function () {
  18327. this.mainSoundTrack.switchPanningModelToHRTF();
  18328. for (var i = 0; i < this.soundTracks.length; i++) {
  18329. this.soundTracks[i].switchPanningModelToHRTF();
  18330. }
  18331. };
  18332. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18333. this.mainSoundTrack.switchPanningModelToEqualPower();
  18334. for (var i = 0; i < this.soundTracks.length; i++) {
  18335. this.soundTracks[i].switchPanningModelToEqualPower();
  18336. }
  18337. };
  18338. Scene.prototype.enableDepthRenderer = function () {
  18339. if (this._depthRenderer) {
  18340. return this._depthRenderer;
  18341. }
  18342. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18343. return this._depthRenderer;
  18344. };
  18345. Scene.prototype.disableDepthRenderer = function () {
  18346. if (!this._depthRenderer) {
  18347. return;
  18348. }
  18349. this._depthRenderer.dispose();
  18350. this._depthRenderer = null;
  18351. };
  18352. Scene.prototype.freezeMaterials = function () {
  18353. for (var i = 0; i < this.materials.length; i++) {
  18354. this.materials[i].freeze();
  18355. }
  18356. };
  18357. Scene.prototype.unfreezeMaterials = function () {
  18358. for (var i = 0; i < this.materials.length; i++) {
  18359. this.materials[i].unfreeze();
  18360. }
  18361. };
  18362. Scene.prototype.dispose = function () {
  18363. this.beforeRender = null;
  18364. this.afterRender = null;
  18365. this.skeletons = [];
  18366. this._boundingBoxRenderer.dispose();
  18367. if (this._depthRenderer) {
  18368. this._depthRenderer.dispose();
  18369. }
  18370. // Debug layer
  18371. if (this._debugLayer) {
  18372. this._debugLayer.hide();
  18373. }
  18374. // Events
  18375. this.onDisposeObservable.notifyObservers(this);
  18376. this.onDisposeObservable.clear();
  18377. this.onBeforeRenderObservable.clear();
  18378. this.onAfterRenderObservable.clear();
  18379. this.detachControl();
  18380. // Release sounds & sounds tracks
  18381. if (BABYLON.AudioEngine) {
  18382. this.disposeSounds();
  18383. }
  18384. // Detach cameras
  18385. var canvas = this._engine.getRenderingCanvas();
  18386. var index;
  18387. for (index = 0; index < this.cameras.length; index++) {
  18388. this.cameras[index].detachControl(canvas);
  18389. }
  18390. // Release lights
  18391. while (this.lights.length) {
  18392. this.lights[0].dispose();
  18393. }
  18394. // Release meshes
  18395. while (this.meshes.length) {
  18396. this.meshes[0].dispose(true);
  18397. }
  18398. // Release cameras
  18399. while (this.cameras.length) {
  18400. this.cameras[0].dispose();
  18401. }
  18402. // Release materials
  18403. while (this.materials.length) {
  18404. this.materials[0].dispose();
  18405. }
  18406. // Release particles
  18407. while (this.particleSystems.length) {
  18408. this.particleSystems[0].dispose();
  18409. }
  18410. // Release sprites
  18411. while (this.spriteManagers.length) {
  18412. this.spriteManagers[0].dispose();
  18413. }
  18414. // Release layers
  18415. while (this.layers.length) {
  18416. this.layers[0].dispose();
  18417. }
  18418. while (this.highlightLayers.length) {
  18419. this.highlightLayers[0].dispose();
  18420. }
  18421. // Release textures
  18422. while (this.textures.length) {
  18423. this.textures[0].dispose();
  18424. }
  18425. // Post-processes
  18426. this.postProcessManager.dispose();
  18427. // Physics
  18428. if (this._physicsEngine) {
  18429. this.disablePhysicsEngine();
  18430. }
  18431. // Remove from engine
  18432. index = this._engine.scenes.indexOf(this);
  18433. if (index > -1) {
  18434. this._engine.scenes.splice(index, 1);
  18435. }
  18436. this._engine.wipeCaches();
  18437. };
  18438. // Release sounds & sounds tracks
  18439. Scene.prototype.disposeSounds = function () {
  18440. this.mainSoundTrack.dispose();
  18441. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18442. this.soundTracks[scIndex].dispose();
  18443. }
  18444. };
  18445. // Octrees
  18446. Scene.prototype.getWorldExtends = function () {
  18447. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18448. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18449. for (var index = 0; index < this.meshes.length; index++) {
  18450. var mesh = this.meshes[index];
  18451. mesh.computeWorldMatrix(true);
  18452. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18453. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18454. BABYLON.Tools.CheckExtends(minBox, min, max);
  18455. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18456. }
  18457. return {
  18458. min: min,
  18459. max: max
  18460. };
  18461. };
  18462. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18463. if (maxCapacity === void 0) { maxCapacity = 64; }
  18464. if (maxDepth === void 0) { maxDepth = 2; }
  18465. if (!this._selectionOctree) {
  18466. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18467. }
  18468. var worldExtends = this.getWorldExtends();
  18469. // Update octree
  18470. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18471. return this._selectionOctree;
  18472. };
  18473. // Picking
  18474. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18475. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18476. var engine = this._engine;
  18477. if (!camera) {
  18478. if (!this.activeCamera)
  18479. throw new Error("Active camera not set");
  18480. camera = this.activeCamera;
  18481. }
  18482. var cameraViewport = camera.viewport;
  18483. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18484. // Moving coordinates to local viewport world
  18485. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18486. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18487. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18488. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18489. };
  18490. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18491. var engine = this._engine;
  18492. if (!camera) {
  18493. if (!this.activeCamera)
  18494. throw new Error("Active camera not set");
  18495. camera = this.activeCamera;
  18496. }
  18497. var cameraViewport = camera.viewport;
  18498. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18499. var identity = BABYLON.Matrix.Identity();
  18500. // Moving coordinates to local viewport world
  18501. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18502. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18503. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18504. };
  18505. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18506. var pickingInfo = null;
  18507. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18508. var mesh = this.meshes[meshIndex];
  18509. if (predicate) {
  18510. if (!predicate(mesh)) {
  18511. continue;
  18512. }
  18513. }
  18514. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18515. continue;
  18516. }
  18517. var world = mesh.getWorldMatrix();
  18518. var ray = rayFunction(world);
  18519. var result = mesh.intersects(ray, fastCheck);
  18520. if (!result || !result.hit)
  18521. continue;
  18522. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18523. continue;
  18524. pickingInfo = result;
  18525. if (fastCheck) {
  18526. break;
  18527. }
  18528. }
  18529. return pickingInfo || new BABYLON.PickingInfo();
  18530. };
  18531. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18532. var pickingInfo = null;
  18533. camera = camera || this.activeCamera;
  18534. if (this.spriteManagers.length > 0) {
  18535. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18536. var spriteManager = this.spriteManagers[spriteIndex];
  18537. if (!spriteManager.isPickable) {
  18538. continue;
  18539. }
  18540. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18541. if (!result || !result.hit)
  18542. continue;
  18543. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18544. continue;
  18545. pickingInfo = result;
  18546. if (fastCheck) {
  18547. break;
  18548. }
  18549. }
  18550. }
  18551. return pickingInfo || new BABYLON.PickingInfo();
  18552. };
  18553. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18554. var _this = this;
  18555. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18556. /// <param name="x">X position on screen</param>
  18557. /// <param name="y">Y position on screen</param>
  18558. /// <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>
  18559. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18560. /// <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>
  18561. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18562. };
  18563. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18564. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18565. /// <param name="x">X position on screen</param>
  18566. /// <param name="y">Y position on screen</param>
  18567. /// <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>
  18568. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18569. /// <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>
  18570. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18571. };
  18572. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18573. var _this = this;
  18574. return this._internalPick(function (world) {
  18575. if (!_this._pickWithRayInverseMatrix) {
  18576. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18577. }
  18578. world.invertToRef(_this._pickWithRayInverseMatrix);
  18579. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18580. }, predicate, fastCheck);
  18581. };
  18582. Scene.prototype.setPointerOverMesh = function (mesh) {
  18583. if (this._pointerOverMesh === mesh) {
  18584. return;
  18585. }
  18586. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18587. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18588. }
  18589. this._pointerOverMesh = mesh;
  18590. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18591. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18592. }
  18593. };
  18594. Scene.prototype.getPointerOverMesh = function () {
  18595. return this._pointerOverMesh;
  18596. };
  18597. Scene.prototype.setPointerOverSprite = function (sprite) {
  18598. if (this._pointerOverSprite === sprite) {
  18599. return;
  18600. }
  18601. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18602. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18603. }
  18604. this._pointerOverSprite = sprite;
  18605. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18606. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18607. }
  18608. };
  18609. Scene.prototype.getPointerOverSprite = function () {
  18610. return this._pointerOverSprite;
  18611. };
  18612. // Physics
  18613. Scene.prototype.getPhysicsEngine = function () {
  18614. return this._physicsEngine;
  18615. };
  18616. /**
  18617. * Enables physics to the current scene
  18618. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18619. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18620. * @return {boolean} was the physics engine initialized
  18621. */
  18622. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18623. if (this._physicsEngine) {
  18624. return true;
  18625. }
  18626. try {
  18627. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18628. return true;
  18629. }
  18630. catch (e) {
  18631. BABYLON.Tools.Error(e.message);
  18632. return false;
  18633. }
  18634. };
  18635. Scene.prototype.disablePhysicsEngine = function () {
  18636. if (!this._physicsEngine) {
  18637. return;
  18638. }
  18639. this._physicsEngine.dispose();
  18640. this._physicsEngine = undefined;
  18641. };
  18642. Scene.prototype.isPhysicsEnabled = function () {
  18643. return this._physicsEngine !== undefined;
  18644. };
  18645. /**
  18646. *
  18647. * Sets the gravity of the physics engine (and NOT of the scene)
  18648. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  18649. */
  18650. Scene.prototype.setGravity = function (gravity) {
  18651. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  18652. if (!this._physicsEngine) {
  18653. return;
  18654. }
  18655. this._physicsEngine.setGravity(gravity);
  18656. };
  18657. /**
  18658. * Legacy support, using the new API
  18659. * @Deprecated
  18660. */
  18661. Scene.prototype.createCompoundImpostor = function (parts, options) {
  18662. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  18663. if (parts.parts) {
  18664. options = parts;
  18665. parts = parts.parts;
  18666. }
  18667. var mainMesh = parts[0].mesh;
  18668. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  18669. for (var index = 1; index < parts.length; index++) {
  18670. var mesh = parts[index].mesh;
  18671. if (mesh.parent !== mainMesh) {
  18672. mesh.position = mesh.position.subtract(mainMesh.position);
  18673. mesh.parent = mainMesh;
  18674. }
  18675. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  18676. }
  18677. mainMesh.physicsImpostor.forceUpdate();
  18678. };
  18679. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18680. var mesh = compound.parts[0].mesh;
  18681. mesh.physicsImpostor.dispose();
  18682. mesh.physicsImpostor = null;
  18683. };
  18684. // Misc.
  18685. Scene.prototype.createDefaultCameraOrLight = function () {
  18686. // Light
  18687. if (this.lights.length === 0) {
  18688. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18689. }
  18690. // Camera
  18691. if (!this.activeCamera) {
  18692. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  18693. // Compute position
  18694. var worldExtends = this.getWorldExtends();
  18695. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  18696. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  18697. camera.setTarget(worldCenter);
  18698. this.activeCamera = camera;
  18699. }
  18700. };
  18701. // Tags
  18702. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18703. if (tagsQuery === undefined) {
  18704. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18705. return list;
  18706. }
  18707. var listByTags = [];
  18708. forEach = forEach || (function (item) { return; });
  18709. for (var i in list) {
  18710. var item = list[i];
  18711. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18712. listByTags.push(item);
  18713. forEach(item);
  18714. }
  18715. }
  18716. return listByTags;
  18717. };
  18718. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18719. return this._getByTags(this.meshes, tagsQuery, forEach);
  18720. };
  18721. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18722. return this._getByTags(this.cameras, tagsQuery, forEach);
  18723. };
  18724. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18725. return this._getByTags(this.lights, tagsQuery, forEach);
  18726. };
  18727. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18728. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18729. };
  18730. /**
  18731. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18732. * This allowed control for front to back rendering or reversly depending of the special needs.
  18733. *
  18734. * @param renderingGroupId The rendering group id corresponding to its index
  18735. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18736. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18737. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18738. */
  18739. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18740. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18741. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18742. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18743. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18744. };
  18745. /**
  18746. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18747. *
  18748. * @param renderingGroupId The rendering group id corresponding to its index
  18749. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18750. */
  18751. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18752. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18753. };
  18754. // Statics
  18755. Scene._FOGMODE_NONE = 0;
  18756. Scene._FOGMODE_EXP = 1;
  18757. Scene._FOGMODE_EXP2 = 2;
  18758. Scene._FOGMODE_LINEAR = 3;
  18759. Scene.MinDeltaTime = 1.0;
  18760. Scene.MaxDeltaTime = 1000.0;
  18761. return Scene;
  18762. }());
  18763. BABYLON.Scene = Scene;
  18764. })(BABYLON || (BABYLON = {}));
  18765. var BABYLON;
  18766. (function (BABYLON) {
  18767. var Buffer = (function () {
  18768. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18769. if (engine instanceof BABYLON.Mesh) {
  18770. this._engine = engine.getScene().getEngine();
  18771. }
  18772. else {
  18773. this._engine = engine;
  18774. }
  18775. this._updatable = updatable;
  18776. this._data = data;
  18777. this._strideSize = stride;
  18778. if (!postponeInternalCreation) {
  18779. this.create();
  18780. }
  18781. this._instanced = instanced;
  18782. }
  18783. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18784. // a lot of these parameters are ignored as they are overriden by the buffer
  18785. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18786. };
  18787. // Properties
  18788. Buffer.prototype.isUpdatable = function () {
  18789. return this._updatable;
  18790. };
  18791. Buffer.prototype.getData = function () {
  18792. return this._data;
  18793. };
  18794. Buffer.prototype.getBuffer = function () {
  18795. return this._buffer;
  18796. };
  18797. Buffer.prototype.getStrideSize = function () {
  18798. return this._strideSize;
  18799. };
  18800. Buffer.prototype.getIsInstanced = function () {
  18801. return this._instanced;
  18802. };
  18803. // Methods
  18804. Buffer.prototype.create = function (data) {
  18805. if (!data && this._buffer) {
  18806. return; // nothing to do
  18807. }
  18808. data = data || this._data;
  18809. if (!this._buffer) {
  18810. if (this._updatable) {
  18811. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18812. this._data = data;
  18813. }
  18814. else {
  18815. this._buffer = this._engine.createVertexBuffer(data);
  18816. }
  18817. }
  18818. else if (this._updatable) {
  18819. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18820. this._data = data;
  18821. }
  18822. };
  18823. Buffer.prototype.update = function (data) {
  18824. this.create(data);
  18825. };
  18826. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18827. if (!this._buffer) {
  18828. return;
  18829. }
  18830. if (this._updatable) {
  18831. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18832. this._data = null;
  18833. }
  18834. };
  18835. Buffer.prototype.dispose = function () {
  18836. if (!this._buffer) {
  18837. return;
  18838. }
  18839. if (this._engine._releaseBuffer(this._buffer)) {
  18840. this._buffer = null;
  18841. }
  18842. };
  18843. return Buffer;
  18844. }());
  18845. BABYLON.Buffer = Buffer;
  18846. })(BABYLON || (BABYLON = {}));
  18847. var BABYLON;
  18848. (function (BABYLON) {
  18849. var VertexBuffer = (function () {
  18850. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18851. if (!stride) {
  18852. // Deduce stride from kind
  18853. switch (kind) {
  18854. case VertexBuffer.PositionKind:
  18855. stride = 3;
  18856. break;
  18857. case VertexBuffer.NormalKind:
  18858. stride = 3;
  18859. break;
  18860. case VertexBuffer.UVKind:
  18861. case VertexBuffer.UV2Kind:
  18862. case VertexBuffer.UV3Kind:
  18863. case VertexBuffer.UV4Kind:
  18864. case VertexBuffer.UV5Kind:
  18865. case VertexBuffer.UV6Kind:
  18866. stride = 2;
  18867. break;
  18868. case VertexBuffer.ColorKind:
  18869. stride = 4;
  18870. break;
  18871. case VertexBuffer.MatricesIndicesKind:
  18872. case VertexBuffer.MatricesIndicesExtraKind:
  18873. stride = 4;
  18874. break;
  18875. case VertexBuffer.MatricesWeightsKind:
  18876. case VertexBuffer.MatricesWeightsExtraKind:
  18877. stride = 4;
  18878. break;
  18879. }
  18880. }
  18881. if (data instanceof BABYLON.Buffer) {
  18882. if (!stride) {
  18883. stride = data.getStrideSize();
  18884. }
  18885. this._buffer = data;
  18886. this._ownsBuffer = false;
  18887. }
  18888. else {
  18889. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18890. this._ownsBuffer = true;
  18891. }
  18892. this._stride = stride;
  18893. this._offset = offset ? offset : 0;
  18894. this._size = size ? size : stride;
  18895. this._kind = kind;
  18896. }
  18897. VertexBuffer.prototype.getKind = function () {
  18898. return this._kind;
  18899. };
  18900. // Properties
  18901. VertexBuffer.prototype.isUpdatable = function () {
  18902. return this._buffer.isUpdatable();
  18903. };
  18904. VertexBuffer.prototype.getData = function () {
  18905. return this._buffer.getData();
  18906. };
  18907. VertexBuffer.prototype.getBuffer = function () {
  18908. return this._buffer.getBuffer();
  18909. };
  18910. VertexBuffer.prototype.getStrideSize = function () {
  18911. return this._stride;
  18912. };
  18913. VertexBuffer.prototype.getOffset = function () {
  18914. return this._offset;
  18915. };
  18916. VertexBuffer.prototype.getSize = function () {
  18917. return this._size;
  18918. };
  18919. VertexBuffer.prototype.getIsInstanced = function () {
  18920. return this._buffer.getIsInstanced();
  18921. };
  18922. // Methods
  18923. VertexBuffer.prototype.create = function (data) {
  18924. return this._buffer.create(data);
  18925. };
  18926. VertexBuffer.prototype.update = function (data) {
  18927. return this._buffer.update(data);
  18928. };
  18929. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18930. return this._buffer.updateDirectly(data, offset);
  18931. };
  18932. VertexBuffer.prototype.dispose = function () {
  18933. if (this._ownsBuffer) {
  18934. this._buffer.dispose();
  18935. }
  18936. };
  18937. Object.defineProperty(VertexBuffer, "PositionKind", {
  18938. get: function () {
  18939. return VertexBuffer._PositionKind;
  18940. },
  18941. enumerable: true,
  18942. configurable: true
  18943. });
  18944. Object.defineProperty(VertexBuffer, "NormalKind", {
  18945. get: function () {
  18946. return VertexBuffer._NormalKind;
  18947. },
  18948. enumerable: true,
  18949. configurable: true
  18950. });
  18951. Object.defineProperty(VertexBuffer, "UVKind", {
  18952. get: function () {
  18953. return VertexBuffer._UVKind;
  18954. },
  18955. enumerable: true,
  18956. configurable: true
  18957. });
  18958. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18959. get: function () {
  18960. return VertexBuffer._UV2Kind;
  18961. },
  18962. enumerable: true,
  18963. configurable: true
  18964. });
  18965. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18966. get: function () {
  18967. return VertexBuffer._UV3Kind;
  18968. },
  18969. enumerable: true,
  18970. configurable: true
  18971. });
  18972. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18973. get: function () {
  18974. return VertexBuffer._UV4Kind;
  18975. },
  18976. enumerable: true,
  18977. configurable: true
  18978. });
  18979. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18980. get: function () {
  18981. return VertexBuffer._UV5Kind;
  18982. },
  18983. enumerable: true,
  18984. configurable: true
  18985. });
  18986. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18987. get: function () {
  18988. return VertexBuffer._UV6Kind;
  18989. },
  18990. enumerable: true,
  18991. configurable: true
  18992. });
  18993. Object.defineProperty(VertexBuffer, "ColorKind", {
  18994. get: function () {
  18995. return VertexBuffer._ColorKind;
  18996. },
  18997. enumerable: true,
  18998. configurable: true
  18999. });
  19000. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19001. get: function () {
  19002. return VertexBuffer._MatricesIndicesKind;
  19003. },
  19004. enumerable: true,
  19005. configurable: true
  19006. });
  19007. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19008. get: function () {
  19009. return VertexBuffer._MatricesWeightsKind;
  19010. },
  19011. enumerable: true,
  19012. configurable: true
  19013. });
  19014. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19015. get: function () {
  19016. return VertexBuffer._MatricesIndicesExtraKind;
  19017. },
  19018. enumerable: true,
  19019. configurable: true
  19020. });
  19021. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19022. get: function () {
  19023. return VertexBuffer._MatricesWeightsExtraKind;
  19024. },
  19025. enumerable: true,
  19026. configurable: true
  19027. });
  19028. // Enums
  19029. VertexBuffer._PositionKind = "position";
  19030. VertexBuffer._NormalKind = "normal";
  19031. VertexBuffer._UVKind = "uv";
  19032. VertexBuffer._UV2Kind = "uv2";
  19033. VertexBuffer._UV3Kind = "uv3";
  19034. VertexBuffer._UV4Kind = "uv4";
  19035. VertexBuffer._UV5Kind = "uv5";
  19036. VertexBuffer._UV6Kind = "uv6";
  19037. VertexBuffer._ColorKind = "color";
  19038. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19039. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19040. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19041. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19042. return VertexBuffer;
  19043. }());
  19044. BABYLON.VertexBuffer = VertexBuffer;
  19045. })(BABYLON || (BABYLON = {}));
  19046. var BABYLON;
  19047. (function (BABYLON) {
  19048. /**
  19049. * Creates an instance based on a source mesh.
  19050. */
  19051. var InstancedMesh = (function (_super) {
  19052. __extends(InstancedMesh, _super);
  19053. function InstancedMesh(name, source) {
  19054. _super.call(this, name, source.getScene());
  19055. source.instances.push(this);
  19056. this._sourceMesh = source;
  19057. this.position.copyFrom(source.position);
  19058. this.rotation.copyFrom(source.rotation);
  19059. this.scaling.copyFrom(source.scaling);
  19060. if (source.rotationQuaternion) {
  19061. this.rotationQuaternion = source.rotationQuaternion.clone();
  19062. }
  19063. this.infiniteDistance = source.infiniteDistance;
  19064. this.setPivotMatrix(source.getPivotMatrix());
  19065. this.refreshBoundingInfo();
  19066. this._syncSubMeshes();
  19067. }
  19068. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19069. // Methods
  19070. get: function () {
  19071. return this._sourceMesh.receiveShadows;
  19072. },
  19073. enumerable: true,
  19074. configurable: true
  19075. });
  19076. Object.defineProperty(InstancedMesh.prototype, "material", {
  19077. get: function () {
  19078. return this._sourceMesh.material;
  19079. },
  19080. enumerable: true,
  19081. configurable: true
  19082. });
  19083. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19084. get: function () {
  19085. return this._sourceMesh.visibility;
  19086. },
  19087. enumerable: true,
  19088. configurable: true
  19089. });
  19090. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19091. get: function () {
  19092. return this._sourceMesh.skeleton;
  19093. },
  19094. enumerable: true,
  19095. configurable: true
  19096. });
  19097. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19098. get: function () {
  19099. return this._sourceMesh.renderingGroupId;
  19100. },
  19101. enumerable: true,
  19102. configurable: true
  19103. });
  19104. InstancedMesh.prototype.getTotalVertices = function () {
  19105. return this._sourceMesh.getTotalVertices();
  19106. };
  19107. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19108. get: function () {
  19109. return this._sourceMesh;
  19110. },
  19111. enumerable: true,
  19112. configurable: true
  19113. });
  19114. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19115. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19116. };
  19117. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19118. return this._sourceMesh.isVerticesDataPresent(kind);
  19119. };
  19120. InstancedMesh.prototype.getIndices = function () {
  19121. return this._sourceMesh.getIndices();
  19122. };
  19123. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19124. get: function () {
  19125. return this._sourceMesh._positions;
  19126. },
  19127. enumerable: true,
  19128. configurable: true
  19129. });
  19130. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19131. var meshBB = this._sourceMesh.getBoundingInfo();
  19132. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19133. this._updateBoundingInfo();
  19134. };
  19135. InstancedMesh.prototype._preActivate = function () {
  19136. if (this._currentLOD) {
  19137. this._currentLOD._preActivate();
  19138. }
  19139. };
  19140. InstancedMesh.prototype._activate = function (renderId) {
  19141. if (this._currentLOD) {
  19142. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19143. }
  19144. };
  19145. InstancedMesh.prototype.getLOD = function (camera) {
  19146. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19147. if (this._currentLOD === this.sourceMesh) {
  19148. return this;
  19149. }
  19150. return this._currentLOD;
  19151. };
  19152. InstancedMesh.prototype._syncSubMeshes = function () {
  19153. this.releaseSubMeshes();
  19154. if (this._sourceMesh.subMeshes) {
  19155. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19156. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19157. }
  19158. }
  19159. };
  19160. InstancedMesh.prototype._generatePointsArray = function () {
  19161. return this._sourceMesh._generatePointsArray();
  19162. };
  19163. // Clone
  19164. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19165. var result = this._sourceMesh.createInstance(name);
  19166. // Deep copy
  19167. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19168. // Bounding info
  19169. this.refreshBoundingInfo();
  19170. // Parent
  19171. if (newParent) {
  19172. result.parent = newParent;
  19173. }
  19174. if (!doNotCloneChildren) {
  19175. // Children
  19176. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19177. var mesh = this.getScene().meshes[index];
  19178. if (mesh.parent === this) {
  19179. mesh.clone(mesh.name, result);
  19180. }
  19181. }
  19182. }
  19183. result.computeWorldMatrix(true);
  19184. return result;
  19185. };
  19186. // Dispoe
  19187. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19188. // Remove from mesh
  19189. var index = this._sourceMesh.instances.indexOf(this);
  19190. this._sourceMesh.instances.splice(index, 1);
  19191. _super.prototype.dispose.call(this, doNotRecurse);
  19192. };
  19193. return InstancedMesh;
  19194. }(BABYLON.AbstractMesh));
  19195. BABYLON.InstancedMesh = InstancedMesh;
  19196. })(BABYLON || (BABYLON = {}));
  19197. var BABYLON;
  19198. (function (BABYLON) {
  19199. var _InstancesBatch = (function () {
  19200. function _InstancesBatch() {
  19201. this.mustReturn = false;
  19202. this.visibleInstances = new Array();
  19203. this.renderSelf = new Array();
  19204. }
  19205. return _InstancesBatch;
  19206. }());
  19207. BABYLON._InstancesBatch = _InstancesBatch;
  19208. var Mesh = (function (_super) {
  19209. __extends(Mesh, _super);
  19210. /**
  19211. * @constructor
  19212. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19213. * @param {Scene} scene The scene to add this mesh to.
  19214. * @param {Node} parent The parent of this mesh, if it has one
  19215. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19216. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19217. * When false, achieved by calling a clone(), also passing False.
  19218. * This will make creation of children, recursive.
  19219. */
  19220. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19221. if (parent === void 0) { parent = null; }
  19222. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19223. _super.call(this, name, scene);
  19224. // Events
  19225. /**
  19226. * An event triggered before rendering the mesh
  19227. * @type {BABYLON.Observable}
  19228. */
  19229. this.onBeforeRenderObservable = new BABYLON.Observable();
  19230. /**
  19231. * An event triggered after rendering the mesh
  19232. * @type {BABYLON.Observable}
  19233. */
  19234. this.onAfterRenderObservable = new BABYLON.Observable();
  19235. /**
  19236. * An event triggered before drawing the mesh
  19237. * @type {BABYLON.Observable}
  19238. */
  19239. this.onBeforeDrawObservable = new BABYLON.Observable();
  19240. // Members
  19241. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19242. this.instances = new Array();
  19243. this._LODLevels = new Array();
  19244. this._visibleInstances = {};
  19245. this._renderIdForInstances = new Array();
  19246. this._batchCache = new _InstancesBatch();
  19247. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19248. this._sideOrientation = Mesh._DEFAULTSIDE;
  19249. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19250. if (source) {
  19251. // Geometry
  19252. if (source._geometry) {
  19253. source._geometry.applyToMesh(this);
  19254. }
  19255. // Deep copy
  19256. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  19257. // Pivot
  19258. this.setPivotMatrix(source.getPivotMatrix());
  19259. this.id = name + "." + source.id;
  19260. // Material
  19261. this.material = source.material;
  19262. var index;
  19263. if (!doNotCloneChildren) {
  19264. // Children
  19265. for (index = 0; index < scene.meshes.length; index++) {
  19266. var mesh = scene.meshes[index];
  19267. if (mesh.parent === source) {
  19268. // doNotCloneChildren is always going to be False
  19269. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  19270. }
  19271. }
  19272. }
  19273. // Physics clone
  19274. var physicsEngine = this.getScene().getPhysicsEngine();
  19275. if (clonePhysicsImpostor && physicsEngine) {
  19276. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19277. if (impostor) {
  19278. this.physicsImpostor = impostor.clone(this);
  19279. }
  19280. }
  19281. // Particles
  19282. for (index = 0; index < scene.particleSystems.length; index++) {
  19283. var system = scene.particleSystems[index];
  19284. if (system.emitter === source) {
  19285. system.clone(system.name, this);
  19286. }
  19287. }
  19288. this.computeWorldMatrix(true);
  19289. }
  19290. // Parent
  19291. if (parent !== null) {
  19292. this.parent = parent;
  19293. }
  19294. }
  19295. Object.defineProperty(Mesh, "FRONTSIDE", {
  19296. /**
  19297. * Mesh side orientation : usually the external or front surface
  19298. */
  19299. get: function () {
  19300. return Mesh._FRONTSIDE;
  19301. },
  19302. enumerable: true,
  19303. configurable: true
  19304. });
  19305. Object.defineProperty(Mesh, "BACKSIDE", {
  19306. /**
  19307. * Mesh side orientation : usually the internal or back surface
  19308. */
  19309. get: function () {
  19310. return Mesh._BACKSIDE;
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19316. /**
  19317. * Mesh side orientation : both internal and external or front and back surfaces
  19318. */
  19319. get: function () {
  19320. return Mesh._DOUBLESIDE;
  19321. },
  19322. enumerable: true,
  19323. configurable: true
  19324. });
  19325. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19326. /**
  19327. * Mesh side orientation : by default, `FRONTSIDE`
  19328. */
  19329. get: function () {
  19330. return Mesh._DEFAULTSIDE;
  19331. },
  19332. enumerable: true,
  19333. configurable: true
  19334. });
  19335. Object.defineProperty(Mesh, "NO_CAP", {
  19336. /**
  19337. * Mesh cap setting : no cap
  19338. */
  19339. get: function () {
  19340. return Mesh._NO_CAP;
  19341. },
  19342. enumerable: true,
  19343. configurable: true
  19344. });
  19345. Object.defineProperty(Mesh, "CAP_START", {
  19346. /**
  19347. * Mesh cap setting : one cap at the beginning of the mesh
  19348. */
  19349. get: function () {
  19350. return Mesh._CAP_START;
  19351. },
  19352. enumerable: true,
  19353. configurable: true
  19354. });
  19355. Object.defineProperty(Mesh, "CAP_END", {
  19356. /**
  19357. * Mesh cap setting : one cap at the end of the mesh
  19358. */
  19359. get: function () {
  19360. return Mesh._CAP_END;
  19361. },
  19362. enumerable: true,
  19363. configurable: true
  19364. });
  19365. Object.defineProperty(Mesh, "CAP_ALL", {
  19366. /**
  19367. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19368. */
  19369. get: function () {
  19370. return Mesh._CAP_ALL;
  19371. },
  19372. enumerable: true,
  19373. configurable: true
  19374. });
  19375. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19376. set: function (callback) {
  19377. if (this._onBeforeDrawObserver) {
  19378. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19379. }
  19380. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19381. },
  19382. enumerable: true,
  19383. configurable: true
  19384. });
  19385. // Methods
  19386. /**
  19387. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19388. */
  19389. Mesh.prototype.toString = function (fullDetails) {
  19390. var ret = _super.prototype.toString.call(this, fullDetails);
  19391. ret += ", n vertices: " + this.getTotalVertices();
  19392. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19393. if (this.animations) {
  19394. for (var i = 0; i < this.animations.length; i++) {
  19395. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19396. }
  19397. }
  19398. if (fullDetails) {
  19399. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19400. }
  19401. return ret;
  19402. };
  19403. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19404. get: function () {
  19405. return this._LODLevels.length > 0;
  19406. },
  19407. enumerable: true,
  19408. configurable: true
  19409. });
  19410. Mesh.prototype._sortLODLevels = function () {
  19411. this._LODLevels.sort(function (a, b) {
  19412. if (a.distance < b.distance) {
  19413. return 1;
  19414. }
  19415. if (a.distance > b.distance) {
  19416. return -1;
  19417. }
  19418. return 0;
  19419. });
  19420. };
  19421. /**
  19422. * Add a mesh as LOD level triggered at the given distance.
  19423. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19424. * @param {number} distance The distance from the center of the object to show this level
  19425. * @param {Mesh} mesh The mesh to be added as LOD level
  19426. * @return {Mesh} This mesh (for chaining)
  19427. */
  19428. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19429. if (mesh && mesh._masterMesh) {
  19430. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19431. return this;
  19432. }
  19433. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19434. this._LODLevels.push(level);
  19435. if (mesh) {
  19436. mesh._masterMesh = this;
  19437. }
  19438. this._sortLODLevels();
  19439. return this;
  19440. };
  19441. /**
  19442. * Returns the LOD level mesh at the passed distance or null if not found.
  19443. * It is related to the method `addLODLevel(distance, mesh)`.
  19444. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19445. */
  19446. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19447. for (var index = 0; index < this._LODLevels.length; index++) {
  19448. var level = this._LODLevels[index];
  19449. if (level.distance === distance) {
  19450. return level.mesh;
  19451. }
  19452. }
  19453. return null;
  19454. };
  19455. /**
  19456. * Remove a mesh from the LOD array
  19457. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19458. * @param {Mesh} mesh The mesh to be removed.
  19459. * @return {Mesh} This mesh (for chaining)
  19460. */
  19461. Mesh.prototype.removeLODLevel = function (mesh) {
  19462. for (var index = 0; index < this._LODLevels.length; index++) {
  19463. if (this._LODLevels[index].mesh === mesh) {
  19464. this._LODLevels.splice(index, 1);
  19465. if (mesh) {
  19466. mesh._masterMesh = null;
  19467. }
  19468. }
  19469. }
  19470. this._sortLODLevels();
  19471. return this;
  19472. };
  19473. /**
  19474. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19475. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19476. */
  19477. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19478. if (!this._LODLevels || this._LODLevels.length === 0) {
  19479. return this;
  19480. }
  19481. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19482. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19483. if (this.onLODLevelSelection) {
  19484. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19485. }
  19486. return this;
  19487. }
  19488. for (var index = 0; index < this._LODLevels.length; index++) {
  19489. var level = this._LODLevels[index];
  19490. if (level.distance < distanceToCamera) {
  19491. if (level.mesh) {
  19492. level.mesh._preActivate();
  19493. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19494. }
  19495. if (this.onLODLevelSelection) {
  19496. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19497. }
  19498. return level.mesh;
  19499. }
  19500. }
  19501. if (this.onLODLevelSelection) {
  19502. this.onLODLevelSelection(distanceToCamera, this, this);
  19503. }
  19504. return this;
  19505. };
  19506. Object.defineProperty(Mesh.prototype, "geometry", {
  19507. /**
  19508. * Returns the mesh internal Geometry object.
  19509. */
  19510. get: function () {
  19511. return this._geometry;
  19512. },
  19513. enumerable: true,
  19514. configurable: true
  19515. });
  19516. /**
  19517. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19518. */
  19519. Mesh.prototype.getTotalVertices = function () {
  19520. if (!this._geometry) {
  19521. return 0;
  19522. }
  19523. return this._geometry.getTotalVertices();
  19524. };
  19525. /**
  19526. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19527. * 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.
  19528. * Returns null if the mesh has no geometry or no vertex buffer.
  19529. * Possible `kind` values :
  19530. * - BABYLON.VertexBuffer.PositionKind
  19531. * - BABYLON.VertexBuffer.UVKind
  19532. * - BABYLON.VertexBuffer.UV2Kind
  19533. * - BABYLON.VertexBuffer.UV3Kind
  19534. * - BABYLON.VertexBuffer.UV4Kind
  19535. * - BABYLON.VertexBuffer.UV5Kind
  19536. * - BABYLON.VertexBuffer.UV6Kind
  19537. * - BABYLON.VertexBuffer.ColorKind
  19538. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19539. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19540. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19541. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19542. */
  19543. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19544. if (!this._geometry) {
  19545. return null;
  19546. }
  19547. return this._geometry.getVerticesData(kind, copyWhenShared);
  19548. };
  19549. /**
  19550. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19551. * Returns `undefined` if the mesh has no geometry.
  19552. * Possible `kind` values :
  19553. * - BABYLON.VertexBuffer.PositionKind
  19554. * - BABYLON.VertexBuffer.UVKind
  19555. * - BABYLON.VertexBuffer.UV2Kind
  19556. * - BABYLON.VertexBuffer.UV3Kind
  19557. * - BABYLON.VertexBuffer.UV4Kind
  19558. * - BABYLON.VertexBuffer.UV5Kind
  19559. * - BABYLON.VertexBuffer.UV6Kind
  19560. * - BABYLON.VertexBuffer.ColorKind
  19561. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19562. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19563. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19564. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19565. */
  19566. Mesh.prototype.getVertexBuffer = function (kind) {
  19567. if (!this._geometry) {
  19568. return undefined;
  19569. }
  19570. return this._geometry.getVertexBuffer(kind);
  19571. };
  19572. /**
  19573. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19574. * Possible `kind` values :
  19575. * - BABYLON.VertexBuffer.PositionKind
  19576. * - BABYLON.VertexBuffer.UVKind
  19577. * - BABYLON.VertexBuffer.UV2Kind
  19578. * - BABYLON.VertexBuffer.UV3Kind
  19579. * - BABYLON.VertexBuffer.UV4Kind
  19580. * - BABYLON.VertexBuffer.UV5Kind
  19581. * - BABYLON.VertexBuffer.UV6Kind
  19582. * - BABYLON.VertexBuffer.ColorKind
  19583. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19584. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19585. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19586. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19587. */
  19588. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19589. if (!this._geometry) {
  19590. if (this._delayInfo) {
  19591. return this._delayInfo.indexOf(kind) !== -1;
  19592. }
  19593. return false;
  19594. }
  19595. return this._geometry.isVerticesDataPresent(kind);
  19596. };
  19597. /**
  19598. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19599. * Possible `kind` values :
  19600. * - BABYLON.VertexBuffer.PositionKind
  19601. * - BABYLON.VertexBuffer.UVKind
  19602. * - BABYLON.VertexBuffer.UV2Kind
  19603. * - BABYLON.VertexBuffer.UV3Kind
  19604. * - BABYLON.VertexBuffer.UV4Kind
  19605. * - BABYLON.VertexBuffer.UV5Kind
  19606. * - BABYLON.VertexBuffer.UV6Kind
  19607. * - BABYLON.VertexBuffer.ColorKind
  19608. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19609. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19610. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19611. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19612. */
  19613. Mesh.prototype.getVerticesDataKinds = function () {
  19614. if (!this._geometry) {
  19615. var result = [];
  19616. if (this._delayInfo) {
  19617. this._delayInfo.forEach(function (kind, index, array) {
  19618. result.push(kind);
  19619. });
  19620. }
  19621. return result;
  19622. }
  19623. return this._geometry.getVerticesDataKinds();
  19624. };
  19625. /**
  19626. * Returns a positive integer : the total number of indices in this mesh geometry.
  19627. * Returns zero if the mesh has no geometry.
  19628. */
  19629. Mesh.prototype.getTotalIndices = function () {
  19630. if (!this._geometry) {
  19631. return 0;
  19632. }
  19633. return this._geometry.getTotalIndices();
  19634. };
  19635. /**
  19636. * Returns an array of integers or a Int32Array populated with the mesh indices.
  19637. * 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.
  19638. * Returns an empty array if the mesh has no geometry.
  19639. */
  19640. Mesh.prototype.getIndices = function (copyWhenShared) {
  19641. if (!this._geometry) {
  19642. return [];
  19643. }
  19644. return this._geometry.getIndices(copyWhenShared);
  19645. };
  19646. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19647. get: function () {
  19648. return this._masterMesh !== null && this._masterMesh !== undefined;
  19649. },
  19650. enumerable: true,
  19651. configurable: true
  19652. });
  19653. /**
  19654. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19655. */
  19656. Mesh.prototype.isReady = function () {
  19657. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19658. return false;
  19659. }
  19660. return _super.prototype.isReady.call(this);
  19661. };
  19662. /**
  19663. * Boolean : true if the mesh has been disposed.
  19664. */
  19665. Mesh.prototype.isDisposed = function () {
  19666. return this._isDisposed;
  19667. };
  19668. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19669. get: function () {
  19670. return this._sideOrientation;
  19671. },
  19672. /**
  19673. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19674. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19675. */
  19676. set: function (sideO) {
  19677. this._sideOrientation = sideO;
  19678. },
  19679. enumerable: true,
  19680. configurable: true
  19681. });
  19682. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19683. /**
  19684. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19685. * This property is pertinent only for updatable parametric shapes.
  19686. */
  19687. get: function () {
  19688. return this._areNormalsFrozen;
  19689. },
  19690. enumerable: true,
  19691. configurable: true
  19692. });
  19693. /**
  19694. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19695. * It has no effect at all on other shapes.
  19696. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19697. */
  19698. Mesh.prototype.freezeNormals = function () {
  19699. this._areNormalsFrozen = true;
  19700. };
  19701. /**
  19702. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19703. * It has no effect at all on other shapes.
  19704. * It reactivates the mesh normals computation if it was previously frozen.
  19705. */
  19706. Mesh.prototype.unfreezeNormals = function () {
  19707. this._areNormalsFrozen = false;
  19708. };
  19709. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19710. /**
  19711. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19712. */
  19713. set: function (count) {
  19714. this._overridenInstanceCount = count;
  19715. },
  19716. enumerable: true,
  19717. configurable: true
  19718. });
  19719. // Methods
  19720. Mesh.prototype._preActivate = function () {
  19721. var sceneRenderId = this.getScene().getRenderId();
  19722. if (this._preActivateId === sceneRenderId) {
  19723. return;
  19724. }
  19725. this._preActivateId = sceneRenderId;
  19726. this._visibleInstances = null;
  19727. };
  19728. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19729. if (this._visibleInstances) {
  19730. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19731. }
  19732. };
  19733. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19734. if (!this._visibleInstances) {
  19735. this._visibleInstances = {};
  19736. this._visibleInstances.defaultRenderId = renderId;
  19737. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19738. }
  19739. if (!this._visibleInstances[renderId]) {
  19740. this._visibleInstances[renderId] = new Array();
  19741. }
  19742. this._visibleInstances[renderId].push(instance);
  19743. };
  19744. /**
  19745. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19746. * This means the mesh underlying bounding box and sphere are recomputed.
  19747. */
  19748. Mesh.prototype.refreshBoundingInfo = function () {
  19749. if (this._boundingInfo.isLocked) {
  19750. return;
  19751. }
  19752. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19753. if (data) {
  19754. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19755. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19756. }
  19757. if (this.subMeshes) {
  19758. for (var index = 0; index < this.subMeshes.length; index++) {
  19759. this.subMeshes[index].refreshBoundingInfo();
  19760. }
  19761. }
  19762. this._updateBoundingInfo();
  19763. };
  19764. Mesh.prototype._createGlobalSubMesh = function () {
  19765. var totalVertices = this.getTotalVertices();
  19766. if (!totalVertices || !this.getIndices()) {
  19767. return null;
  19768. }
  19769. this.releaseSubMeshes();
  19770. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19771. };
  19772. Mesh.prototype.subdivide = function (count) {
  19773. if (count < 1) {
  19774. return;
  19775. }
  19776. var totalIndices = this.getTotalIndices();
  19777. var subdivisionSize = (totalIndices / count) | 0;
  19778. var offset = 0;
  19779. // Ensure that subdivisionSize is a multiple of 3
  19780. while (subdivisionSize % 3 !== 0) {
  19781. subdivisionSize++;
  19782. }
  19783. this.releaseSubMeshes();
  19784. for (var index = 0; index < count; index++) {
  19785. if (offset >= totalIndices) {
  19786. break;
  19787. }
  19788. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19789. offset += subdivisionSize;
  19790. }
  19791. this.synchronizeInstances();
  19792. };
  19793. /**
  19794. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19795. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19796. * The `data` are either a numeric array either a Float32Array.
  19797. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19798. * 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).
  19799. * Note that a new underlying VertexBuffer object is created each call.
  19800. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19801. *
  19802. * Possible `kind` values :
  19803. * - BABYLON.VertexBuffer.PositionKind
  19804. * - BABYLON.VertexBuffer.UVKind
  19805. * - BABYLON.VertexBuffer.UV2Kind
  19806. * - BABYLON.VertexBuffer.UV3Kind
  19807. * - BABYLON.VertexBuffer.UV4Kind
  19808. * - BABYLON.VertexBuffer.UV5Kind
  19809. * - BABYLON.VertexBuffer.UV6Kind
  19810. * - BABYLON.VertexBuffer.ColorKind
  19811. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19812. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19813. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19814. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19815. */
  19816. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19817. if (!this._geometry) {
  19818. var vertexData = new BABYLON.VertexData();
  19819. vertexData.set(data, kind);
  19820. var scene = this.getScene();
  19821. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19822. }
  19823. else {
  19824. this._geometry.setVerticesData(kind, data, updatable, stride);
  19825. }
  19826. };
  19827. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19828. if (!this._geometry) {
  19829. var scene = this.getScene();
  19830. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19831. }
  19832. this._geometry.setVerticesBuffer(buffer);
  19833. };
  19834. /**
  19835. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19836. * If the mesh has no geometry, it is simply returned as it is.
  19837. * The `data` are either a numeric array either a Float32Array.
  19838. * No new underlying VertexBuffer object is created.
  19839. * 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.
  19840. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19841. *
  19842. * Possible `kind` values :
  19843. * - BABYLON.VertexBuffer.PositionKind
  19844. * - BABYLON.VertexBuffer.UVKind
  19845. * - BABYLON.VertexBuffer.UV2Kind
  19846. * - BABYLON.VertexBuffer.UV3Kind
  19847. * - BABYLON.VertexBuffer.UV4Kind
  19848. * - BABYLON.VertexBuffer.UV5Kind
  19849. * - BABYLON.VertexBuffer.UV6Kind
  19850. * - BABYLON.VertexBuffer.ColorKind
  19851. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19852. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19853. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19854. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19855. */
  19856. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19857. if (!this._geometry) {
  19858. return;
  19859. }
  19860. if (!makeItUnique) {
  19861. this._geometry.updateVerticesData(kind, data, updateExtends);
  19862. }
  19863. else {
  19864. this.makeGeometryUnique();
  19865. this.updateVerticesData(kind, data, updateExtends, false);
  19866. }
  19867. };
  19868. /**
  19869. * Deprecated since BabylonJS v2.3
  19870. */
  19871. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19872. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19873. if (!this._geometry) {
  19874. return;
  19875. }
  19876. if (!makeItUnique) {
  19877. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19878. }
  19879. else {
  19880. this.makeGeometryUnique();
  19881. this.updateVerticesDataDirectly(kind, data, offset, false);
  19882. }
  19883. };
  19884. /**
  19885. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19886. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19887. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19888. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19889. */
  19890. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19891. if (computeNormals === void 0) { computeNormals = true; }
  19892. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19893. positionFunction(positions);
  19894. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19895. if (computeNormals) {
  19896. var indices = this.getIndices();
  19897. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19898. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19899. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19900. }
  19901. };
  19902. Mesh.prototype.makeGeometryUnique = function () {
  19903. if (!this._geometry) {
  19904. return;
  19905. }
  19906. var oldGeometry = this._geometry;
  19907. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19908. oldGeometry.releaseForMesh(this, true);
  19909. geometry.applyToMesh(this);
  19910. };
  19911. /**
  19912. * Sets the mesh indices.
  19913. * Expects an array populated with integers or a Int32Array.
  19914. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19915. * This method creates a new index buffer each call.
  19916. */
  19917. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19918. if (!this._geometry) {
  19919. var vertexData = new BABYLON.VertexData();
  19920. vertexData.indices = indices;
  19921. var scene = this.getScene();
  19922. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19923. }
  19924. else {
  19925. this._geometry.setIndices(indices, totalVertices);
  19926. }
  19927. };
  19928. /**
  19929. * Invert the geometry to move from a right handed system to a left handed one.
  19930. */
  19931. Mesh.prototype.toLeftHanded = function () {
  19932. if (!this._geometry) {
  19933. return;
  19934. }
  19935. this._geometry.toLeftHanded();
  19936. };
  19937. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19938. var engine = this.getScene().getEngine();
  19939. // Wireframe
  19940. var indexToBind;
  19941. if (this._unIndexed) {
  19942. indexToBind = null;
  19943. }
  19944. else {
  19945. switch (fillMode) {
  19946. case BABYLON.Material.PointFillMode:
  19947. indexToBind = null;
  19948. break;
  19949. case BABYLON.Material.WireFrameFillMode:
  19950. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19951. break;
  19952. default:
  19953. case BABYLON.Material.TriangleFillMode:
  19954. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19955. break;
  19956. }
  19957. }
  19958. // VBOs
  19959. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19960. };
  19961. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19962. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19963. return;
  19964. }
  19965. this.onBeforeDrawObservable.notifyObservers(this);
  19966. var engine = this.getScene().getEngine();
  19967. // Draw order
  19968. switch (fillMode) {
  19969. case BABYLON.Material.PointFillMode:
  19970. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19971. break;
  19972. case BABYLON.Material.WireFrameFillMode:
  19973. if (this._unIndexed) {
  19974. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19975. }
  19976. else {
  19977. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19978. }
  19979. break;
  19980. default:
  19981. if (this._unIndexed) {
  19982. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19983. }
  19984. else {
  19985. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19986. }
  19987. }
  19988. };
  19989. /**
  19990. * Registers for this mesh a javascript function called just before the rendering process.
  19991. * This function is passed the current mesh and doesn't return anything.
  19992. */
  19993. Mesh.prototype.registerBeforeRender = function (func) {
  19994. this.onBeforeRenderObservable.add(func);
  19995. };
  19996. /**
  19997. * Disposes a previously registered javascript function called before the rendering.
  19998. * This function is passed the current mesh and doesn't return anything.
  19999. */
  20000. Mesh.prototype.unregisterBeforeRender = function (func) {
  20001. this.onBeforeRenderObservable.removeCallback(func);
  20002. };
  20003. /**
  20004. * Registers for this mesh a javascript function called just after the rendering is complete.
  20005. * This function is passed the current mesh and doesn't return anything.
  20006. */
  20007. Mesh.prototype.registerAfterRender = function (func) {
  20008. this.onAfterRenderObservable.add(func);
  20009. };
  20010. /**
  20011. * Disposes a previously registered javascript function called after the rendering.
  20012. * This function is passed the current mesh and doesn't return anything.
  20013. */
  20014. Mesh.prototype.unregisterAfterRender = function (func) {
  20015. this.onAfterRenderObservable.removeCallback(func);
  20016. };
  20017. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20018. var scene = this.getScene();
  20019. this._batchCache.mustReturn = false;
  20020. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20021. this._batchCache.visibleInstances[subMeshId] = null;
  20022. if (this._visibleInstances) {
  20023. var currentRenderId = scene.getRenderId();
  20024. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20025. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20026. var selfRenderId = this._renderId;
  20027. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20028. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20029. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20030. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20031. }
  20032. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20033. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20034. this._batchCache.mustReturn = true;
  20035. return this._batchCache;
  20036. }
  20037. if (currentRenderId !== selfRenderId) {
  20038. this._batchCache.renderSelf[subMeshId] = false;
  20039. }
  20040. }
  20041. this._renderIdForInstances[subMeshId] = currentRenderId;
  20042. }
  20043. return this._batchCache;
  20044. };
  20045. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20046. var visibleInstances = batch.visibleInstances[subMesh._id];
  20047. var matricesCount = visibleInstances.length + 1;
  20048. var bufferSize = matricesCount * 16 * 4;
  20049. var currentInstancesBufferSize = this._instancesBufferSize;
  20050. var instancesBuffer = this._instancesBuffer;
  20051. while (this._instancesBufferSize < bufferSize) {
  20052. this._instancesBufferSize *= 2;
  20053. }
  20054. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20055. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20056. }
  20057. var offset = 0;
  20058. var instancesCount = 0;
  20059. var world = this.getWorldMatrix();
  20060. if (batch.renderSelf[subMesh._id]) {
  20061. world.copyToArray(this._instancesData, offset);
  20062. offset += 16;
  20063. instancesCount++;
  20064. }
  20065. if (visibleInstances) {
  20066. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20067. var instance = visibleInstances[instanceIndex];
  20068. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20069. offset += 16;
  20070. instancesCount++;
  20071. }
  20072. }
  20073. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20074. if (instancesBuffer) {
  20075. instancesBuffer.dispose();
  20076. }
  20077. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20078. this._instancesBuffer = instancesBuffer;
  20079. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20080. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20081. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20082. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20083. }
  20084. else {
  20085. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20086. }
  20087. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20088. this._draw(subMesh, fillMode, instancesCount);
  20089. engine.unbindInstanceAttributes();
  20090. };
  20091. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20092. var scene = this.getScene();
  20093. var engine = scene.getEngine();
  20094. if (hardwareInstancedRendering) {
  20095. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20096. }
  20097. else {
  20098. if (batch.renderSelf[subMesh._id]) {
  20099. // Draw
  20100. if (onBeforeDraw) {
  20101. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20102. }
  20103. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20104. }
  20105. if (batch.visibleInstances[subMesh._id]) {
  20106. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20107. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20108. // World
  20109. var world = instance.getWorldMatrix();
  20110. if (onBeforeDraw) {
  20111. onBeforeDraw(true, world, effectiveMaterial);
  20112. }
  20113. // Draw
  20114. this._draw(subMesh, fillMode);
  20115. }
  20116. }
  20117. }
  20118. };
  20119. /**
  20120. * Triggers the draw call for the mesh.
  20121. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20122. */
  20123. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20124. var scene = this.getScene();
  20125. // Managing instances
  20126. var batch = this._getInstancesRenderList(subMesh._id);
  20127. if (batch.mustReturn) {
  20128. return;
  20129. }
  20130. // Checking geometry state
  20131. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20132. return;
  20133. }
  20134. var callbackIndex;
  20135. this.onBeforeRenderObservable.notifyObservers(this);
  20136. var engine = scene.getEngine();
  20137. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20138. // Material
  20139. var effectiveMaterial = subMesh.getMaterial();
  20140. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20141. return;
  20142. }
  20143. // Outline - step 1
  20144. var savedDepthWrite = engine.getDepthWrite();
  20145. if (this.renderOutline) {
  20146. engine.setDepthWrite(false);
  20147. scene.getOutlineRenderer().render(subMesh, batch);
  20148. engine.setDepthWrite(savedDepthWrite);
  20149. }
  20150. effectiveMaterial._preBind();
  20151. var effect = effectiveMaterial.getEffect();
  20152. // Bind
  20153. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20154. this._bind(subMesh, effect, fillMode);
  20155. var world = this.getWorldMatrix();
  20156. effectiveMaterial.bind(world, this);
  20157. // Alpha mode
  20158. if (enableAlphaMode) {
  20159. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20160. }
  20161. // Draw
  20162. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20163. // Unbind
  20164. effectiveMaterial.unbind();
  20165. // Outline - step 2
  20166. if (this.renderOutline && savedDepthWrite) {
  20167. engine.setDepthWrite(true);
  20168. engine.setColorWrite(false);
  20169. scene.getOutlineRenderer().render(subMesh, batch);
  20170. engine.setColorWrite(true);
  20171. }
  20172. // Overlay
  20173. if (this.renderOverlay) {
  20174. var currentMode = engine.getAlphaMode();
  20175. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20176. scene.getOutlineRenderer().render(subMesh, batch, true);
  20177. engine.setAlphaMode(currentMode);
  20178. }
  20179. this.onAfterRenderObservable.notifyObservers(this);
  20180. };
  20181. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20182. if (isInstance) {
  20183. effectiveMaterial.bindOnlyWorldMatrix(world);
  20184. }
  20185. };
  20186. /**
  20187. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20188. */
  20189. Mesh.prototype.getEmittedParticleSystems = function () {
  20190. var results = new Array();
  20191. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20192. var particleSystem = this.getScene().particleSystems[index];
  20193. if (particleSystem.emitter === this) {
  20194. results.push(particleSystem);
  20195. }
  20196. }
  20197. return results;
  20198. };
  20199. /**
  20200. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20201. */
  20202. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20203. var results = new Array();
  20204. var descendants = this.getDescendants();
  20205. descendants.push(this);
  20206. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20207. var particleSystem = this.getScene().particleSystems[index];
  20208. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20209. results.push(particleSystem);
  20210. }
  20211. }
  20212. return results;
  20213. };
  20214. Mesh.prototype._checkDelayState = function () {
  20215. var scene = this.getScene();
  20216. if (this._geometry) {
  20217. this._geometry.load(scene);
  20218. }
  20219. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20220. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20221. this._queueLoad(this, scene);
  20222. }
  20223. };
  20224. Mesh.prototype._queueLoad = function (mesh, scene) {
  20225. var _this = this;
  20226. scene._addPendingData(mesh);
  20227. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20228. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20229. if (data instanceof ArrayBuffer) {
  20230. _this._delayLoadingFunction(data, _this);
  20231. }
  20232. else {
  20233. _this._delayLoadingFunction(JSON.parse(data), _this);
  20234. }
  20235. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20236. scene._removePendingData(_this);
  20237. }, function () { }, scene.database, getBinaryData);
  20238. };
  20239. /**
  20240. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20241. */
  20242. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20243. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20244. return false;
  20245. }
  20246. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20247. return false;
  20248. }
  20249. this._checkDelayState();
  20250. return true;
  20251. };
  20252. /**
  20253. * Sets the mesh material by the material or multiMaterial `id` property.
  20254. * The material `id` is a string identifying the material or the multiMaterial.
  20255. * This method returns nothing.
  20256. */
  20257. Mesh.prototype.setMaterialByID = function (id) {
  20258. var materials = this.getScene().materials;
  20259. var index;
  20260. for (index = 0; index < materials.length; index++) {
  20261. if (materials[index].id === id) {
  20262. this.material = materials[index];
  20263. return;
  20264. }
  20265. }
  20266. // Multi
  20267. var multiMaterials = this.getScene().multiMaterials;
  20268. for (index = 0; index < multiMaterials.length; index++) {
  20269. if (multiMaterials[index].id === id) {
  20270. this.material = multiMaterials[index];
  20271. return;
  20272. }
  20273. }
  20274. };
  20275. /**
  20276. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20277. */
  20278. Mesh.prototype.getAnimatables = function () {
  20279. var results = [];
  20280. if (this.material) {
  20281. results.push(this.material);
  20282. }
  20283. if (this.skeleton) {
  20284. results.push(this.skeleton);
  20285. }
  20286. return results;
  20287. };
  20288. /**
  20289. * Modifies the mesh geometry according to the passed transformation matrix.
  20290. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20291. * The mesh normals are modified accordingly the same transformation.
  20292. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20293. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20294. */
  20295. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20296. // Position
  20297. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20298. return;
  20299. }
  20300. var submeshes = this.subMeshes.splice(0);
  20301. this._resetPointsArrayCache();
  20302. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20303. var temp = [];
  20304. var index;
  20305. for (index = 0; index < data.length; index += 3) {
  20306. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20307. }
  20308. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20309. // Normals
  20310. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20311. return;
  20312. }
  20313. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20314. temp = [];
  20315. for (index = 0; index < data.length; index += 3) {
  20316. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20317. }
  20318. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20319. // flip faces?
  20320. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20321. this.flipFaces();
  20322. }
  20323. // Restore submeshes
  20324. this.releaseSubMeshes();
  20325. this.subMeshes = submeshes;
  20326. };
  20327. /**
  20328. * Modifies the mesh geometry according to its own current World Matrix.
  20329. * The mesh World Matrix is then reset.
  20330. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20331. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20332. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20333. */
  20334. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20335. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20336. this.scaling.copyFromFloats(1, 1, 1);
  20337. this.position.copyFromFloats(0, 0, 0);
  20338. this.rotation.copyFromFloats(0, 0, 0);
  20339. //only if quaternion is already set
  20340. if (this.rotationQuaternion) {
  20341. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20342. }
  20343. this._worldMatrix = BABYLON.Matrix.Identity();
  20344. };
  20345. // Cache
  20346. Mesh.prototype._resetPointsArrayCache = function () {
  20347. this._positions = null;
  20348. };
  20349. Mesh.prototype._generatePointsArray = function () {
  20350. if (this._positions)
  20351. return true;
  20352. this._positions = [];
  20353. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20354. if (!data) {
  20355. return false;
  20356. }
  20357. for (var index = 0; index < data.length; index += 3) {
  20358. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20359. }
  20360. return true;
  20361. };
  20362. /**
  20363. * Returns a new Mesh object generated from the current mesh properties.
  20364. * This method must not get confused with createInstance().
  20365. * The parameter `name` is a string, the name given to the new mesh.
  20366. * The optional parameter `newParent` can be any Node object (default `null`).
  20367. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20368. * 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.
  20369. */
  20370. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20371. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20372. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20373. };
  20374. /**
  20375. * Disposes the mesh.
  20376. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20377. */
  20378. Mesh.prototype.dispose = function (doNotRecurse) {
  20379. if (this._geometry) {
  20380. this._geometry.releaseForMesh(this, true);
  20381. }
  20382. // Instances
  20383. if (this._instancesBuffer) {
  20384. this._instancesBuffer.dispose();
  20385. this._instancesBuffer = null;
  20386. }
  20387. while (this.instances.length) {
  20388. this.instances[0].dispose();
  20389. }
  20390. // Highlight layers.
  20391. var highlightLayers = this.getScene().highlightLayers;
  20392. for (var i = 0; i < highlightLayers.length; i++) {
  20393. var highlightLayer = highlightLayers[i];
  20394. if (highlightLayer) {
  20395. highlightLayer.removeMesh(this);
  20396. highlightLayer.removeExcludedMesh(this);
  20397. }
  20398. }
  20399. _super.prototype.dispose.call(this, doNotRecurse);
  20400. };
  20401. /**
  20402. * Modifies the mesh geometry according to a displacement map.
  20403. * 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.
  20404. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20405. * This method returns nothing.
  20406. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20407. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20408. * 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.
  20409. */
  20410. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20411. var _this = this;
  20412. var scene = this.getScene();
  20413. var onload = function (img) {
  20414. // Getting height map data
  20415. var canvas = document.createElement("canvas");
  20416. var context = canvas.getContext("2d");
  20417. var heightMapWidth = img.width;
  20418. var heightMapHeight = img.height;
  20419. canvas.width = heightMapWidth;
  20420. canvas.height = heightMapHeight;
  20421. context.drawImage(img, 0, 0);
  20422. // Create VertexData from map data
  20423. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20424. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20425. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20426. //execute success callback, if set
  20427. if (onSuccess) {
  20428. onSuccess(_this);
  20429. }
  20430. };
  20431. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20432. };
  20433. /**
  20434. * Modifies the mesh geometry according to a displacementMap buffer.
  20435. * 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.
  20436. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20437. * This method returns nothing.
  20438. * 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.
  20439. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20440. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20441. */
  20442. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20443. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20444. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20445. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20446. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20447. return;
  20448. }
  20449. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20450. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20451. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20452. var position = BABYLON.Vector3.Zero();
  20453. var normal = BABYLON.Vector3.Zero();
  20454. var uv = BABYLON.Vector2.Zero();
  20455. for (var index = 0; index < positions.length; index += 3) {
  20456. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20457. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20458. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20459. // Compute height
  20460. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20461. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20462. var pos = (u + v * heightMapWidth) * 4;
  20463. var r = buffer[pos] / 255.0;
  20464. var g = buffer[pos + 1] / 255.0;
  20465. var b = buffer[pos + 2] / 255.0;
  20466. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20467. normal.normalize();
  20468. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20469. position = position.add(normal);
  20470. position.toArray(positions, index);
  20471. }
  20472. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20473. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20474. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20475. };
  20476. /**
  20477. * Modify the mesh to get a flat shading rendering.
  20478. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20479. * This method returns nothing.
  20480. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20481. */
  20482. Mesh.prototype.convertToFlatShadedMesh = function () {
  20483. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20484. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20485. var kinds = this.getVerticesDataKinds();
  20486. var vbs = [];
  20487. var data = [];
  20488. var newdata = [];
  20489. var updatableNormals = false;
  20490. var kindIndex;
  20491. var kind;
  20492. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20493. kind = kinds[kindIndex];
  20494. var vertexBuffer = this.getVertexBuffer(kind);
  20495. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20496. updatableNormals = vertexBuffer.isUpdatable();
  20497. kinds.splice(kindIndex, 1);
  20498. kindIndex--;
  20499. continue;
  20500. }
  20501. vbs[kind] = vertexBuffer;
  20502. data[kind] = vbs[kind].getData();
  20503. newdata[kind] = [];
  20504. }
  20505. // Save previous submeshes
  20506. var previousSubmeshes = this.subMeshes.slice(0);
  20507. var indices = this.getIndices();
  20508. var totalIndices = this.getTotalIndices();
  20509. // Generating unique vertices per face
  20510. var index;
  20511. for (index = 0; index < totalIndices; index++) {
  20512. var vertexIndex = indices[index];
  20513. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20514. kind = kinds[kindIndex];
  20515. var stride = vbs[kind].getStrideSize();
  20516. for (var offset = 0; offset < stride; offset++) {
  20517. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20518. }
  20519. }
  20520. }
  20521. // Updating faces & normal
  20522. var normals = [];
  20523. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20524. for (index = 0; index < totalIndices; index += 3) {
  20525. indices[index] = index;
  20526. indices[index + 1] = index + 1;
  20527. indices[index + 2] = index + 2;
  20528. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20529. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20530. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20531. var p1p2 = p1.subtract(p2);
  20532. var p3p2 = p3.subtract(p2);
  20533. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20534. // Store same normals for every vertex
  20535. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20536. normals.push(normal.x);
  20537. normals.push(normal.y);
  20538. normals.push(normal.z);
  20539. }
  20540. }
  20541. this.setIndices(indices);
  20542. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20543. // Updating vertex buffers
  20544. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20545. kind = kinds[kindIndex];
  20546. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20547. }
  20548. // Updating submeshes
  20549. this.releaseSubMeshes();
  20550. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20551. var previousOne = previousSubmeshes[submeshIndex];
  20552. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20553. }
  20554. this.synchronizeInstances();
  20555. };
  20556. /**
  20557. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20558. * In other words, more vertices, no more indices and a single bigger VBO.
  20559. * This method returns nothing.
  20560. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20561. *
  20562. */
  20563. Mesh.prototype.convertToUnIndexedMesh = function () {
  20564. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20565. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20566. var kinds = this.getVerticesDataKinds();
  20567. var vbs = [];
  20568. var data = [];
  20569. var newdata = [];
  20570. var updatableNormals = false;
  20571. var kindIndex;
  20572. var kind;
  20573. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20574. kind = kinds[kindIndex];
  20575. var vertexBuffer = this.getVertexBuffer(kind);
  20576. vbs[kind] = vertexBuffer;
  20577. data[kind] = vbs[kind].getData();
  20578. newdata[kind] = [];
  20579. }
  20580. // Save previous submeshes
  20581. var previousSubmeshes = this.subMeshes.slice(0);
  20582. var indices = this.getIndices();
  20583. var totalIndices = this.getTotalIndices();
  20584. // Generating unique vertices per face
  20585. var index;
  20586. for (index = 0; index < totalIndices; index++) {
  20587. var vertexIndex = indices[index];
  20588. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20589. kind = kinds[kindIndex];
  20590. var stride = vbs[kind].getStrideSize();
  20591. for (var offset = 0; offset < stride; offset++) {
  20592. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20593. }
  20594. }
  20595. }
  20596. // Updating indices
  20597. for (index = 0; index < totalIndices; index += 3) {
  20598. indices[index] = index;
  20599. indices[index + 1] = index + 1;
  20600. indices[index + 2] = index + 2;
  20601. }
  20602. this.setIndices(indices);
  20603. // Updating vertex buffers
  20604. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20605. kind = kinds[kindIndex];
  20606. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20607. }
  20608. // Updating submeshes
  20609. this.releaseSubMeshes();
  20610. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20611. var previousOne = previousSubmeshes[submeshIndex];
  20612. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20613. }
  20614. this._unIndexed = true;
  20615. this.synchronizeInstances();
  20616. };
  20617. /**
  20618. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20619. * This method returns nothing.
  20620. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20621. */
  20622. Mesh.prototype.flipFaces = function (flipNormals) {
  20623. if (flipNormals === void 0) { flipNormals = false; }
  20624. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20625. var i;
  20626. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20627. for (i = 0; i < vertex_data.normals.length; i++) {
  20628. vertex_data.normals[i] *= -1;
  20629. }
  20630. }
  20631. var temp;
  20632. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20633. // reassign indices
  20634. temp = vertex_data.indices[i + 1];
  20635. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20636. vertex_data.indices[i + 2] = temp;
  20637. }
  20638. vertex_data.applyToMesh(this);
  20639. };
  20640. // Instances
  20641. /**
  20642. * Creates a new InstancedMesh object from the mesh model.
  20643. * An instance shares the same properties and the same material than its model.
  20644. * Only these properties of each instance can then be set individually :
  20645. * - position
  20646. * - rotation
  20647. * - rotationQuaternion
  20648. * - setPivotMatrix
  20649. * - scaling
  20650. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20651. * Warning : this method is not supported for Line mesh and LineSystem
  20652. */
  20653. Mesh.prototype.createInstance = function (name) {
  20654. return new BABYLON.InstancedMesh(name, this);
  20655. };
  20656. /**
  20657. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20658. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20659. * This method returns nothing.
  20660. */
  20661. Mesh.prototype.synchronizeInstances = function () {
  20662. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20663. var instance = this.instances[instanceIndex];
  20664. instance._syncSubMeshes();
  20665. }
  20666. };
  20667. /**
  20668. * Simplify the mesh according to the given array of settings.
  20669. * Function will return immediately and will simplify async. It returns nothing.
  20670. * @param settings a collection of simplification settings.
  20671. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20672. * @param type the type of simplification to run.
  20673. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20674. */
  20675. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20676. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20677. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20678. this.getScene().simplificationQueue.addTask({
  20679. settings: settings,
  20680. parallelProcessing: parallelProcessing,
  20681. mesh: this,
  20682. simplificationType: simplificationType,
  20683. successCallback: successCallback
  20684. });
  20685. };
  20686. /**
  20687. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20688. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20689. * This should be used together with the simplification to avoid disappearing triangles.
  20690. * @param successCallback an optional success callback to be called after the optimization finished.
  20691. */
  20692. Mesh.prototype.optimizeIndices = function (successCallback) {
  20693. var _this = this;
  20694. var indices = this.getIndices();
  20695. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20696. var vectorPositions = [];
  20697. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20698. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20699. }
  20700. var dupes = [];
  20701. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20702. var realPos = vectorPositions.length - 1 - iteration;
  20703. var testedPosition = vectorPositions[realPos];
  20704. for (var j = 0; j < realPos; ++j) {
  20705. var againstPosition = vectorPositions[j];
  20706. if (testedPosition.equals(againstPosition)) {
  20707. dupes[realPos] = j;
  20708. break;
  20709. }
  20710. }
  20711. }, function () {
  20712. for (var i = 0; i < indices.length; ++i) {
  20713. indices[i] = dupes[indices[i]] || indices[i];
  20714. }
  20715. //indices are now reordered
  20716. var originalSubMeshes = _this.subMeshes.slice(0);
  20717. _this.setIndices(indices);
  20718. _this.subMeshes = originalSubMeshes;
  20719. if (successCallback) {
  20720. successCallback(_this);
  20721. }
  20722. });
  20723. };
  20724. // Statics
  20725. /**
  20726. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20727. * The parameter `parsedMesh` is the mesh to be copied.
  20728. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20729. */
  20730. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20731. var mesh = new Mesh(parsedMesh.name, scene);
  20732. mesh.id = parsedMesh.id;
  20733. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20734. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20735. if (parsedMesh.metadata !== undefined) {
  20736. mesh.metadata = parsedMesh.metadata;
  20737. }
  20738. if (parsedMesh.rotationQuaternion) {
  20739. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20740. }
  20741. else if (parsedMesh.rotation) {
  20742. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20743. }
  20744. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20745. if (parsedMesh.localMatrix) {
  20746. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20747. }
  20748. else if (parsedMesh.pivotMatrix) {
  20749. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20750. }
  20751. mesh.setEnabled(parsedMesh.isEnabled);
  20752. mesh.isVisible = parsedMesh.isVisible;
  20753. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20754. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20755. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20756. if (parsedMesh.applyFog !== undefined) {
  20757. mesh.applyFog = parsedMesh.applyFog;
  20758. }
  20759. if (parsedMesh.pickable !== undefined) {
  20760. mesh.isPickable = parsedMesh.pickable;
  20761. }
  20762. if (parsedMesh.alphaIndex !== undefined) {
  20763. mesh.alphaIndex = parsedMesh.alphaIndex;
  20764. }
  20765. mesh.receiveShadows = parsedMesh.receiveShadows;
  20766. mesh.billboardMode = parsedMesh.billboardMode;
  20767. if (parsedMesh.visibility !== undefined) {
  20768. mesh.visibility = parsedMesh.visibility;
  20769. }
  20770. mesh.checkCollisions = parsedMesh.checkCollisions;
  20771. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20772. // freezeWorldMatrix
  20773. if (parsedMesh.freezeWorldMatrix) {
  20774. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20775. }
  20776. // Parent
  20777. if (parsedMesh.parentId) {
  20778. mesh._waitingParentId = parsedMesh.parentId;
  20779. }
  20780. // Actions
  20781. if (parsedMesh.actions !== undefined) {
  20782. mesh._waitingActions = parsedMesh.actions;
  20783. }
  20784. // Geometry
  20785. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20786. if (parsedMesh.delayLoadingFile) {
  20787. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20788. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20789. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20790. if (parsedMesh._binaryInfo) {
  20791. mesh._binaryInfo = parsedMesh._binaryInfo;
  20792. }
  20793. mesh._delayInfo = [];
  20794. if (parsedMesh.hasUVs) {
  20795. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20796. }
  20797. if (parsedMesh.hasUVs2) {
  20798. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20799. }
  20800. if (parsedMesh.hasUVs3) {
  20801. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20802. }
  20803. if (parsedMesh.hasUVs4) {
  20804. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20805. }
  20806. if (parsedMesh.hasUVs5) {
  20807. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20808. }
  20809. if (parsedMesh.hasUVs6) {
  20810. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20811. }
  20812. if (parsedMesh.hasColors) {
  20813. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20814. }
  20815. if (parsedMesh.hasMatricesIndices) {
  20816. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20817. }
  20818. if (parsedMesh.hasMatricesWeights) {
  20819. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20820. }
  20821. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20822. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20823. mesh._checkDelayState();
  20824. }
  20825. }
  20826. else {
  20827. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20828. }
  20829. // Material
  20830. if (parsedMesh.materialId) {
  20831. mesh.setMaterialByID(parsedMesh.materialId);
  20832. }
  20833. else {
  20834. mesh.material = null;
  20835. }
  20836. // Skeleton
  20837. if (parsedMesh.skeletonId > -1) {
  20838. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20839. if (parsedMesh.numBoneInfluencers) {
  20840. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20841. }
  20842. }
  20843. // Animations
  20844. if (parsedMesh.animations) {
  20845. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20846. var parsedAnimation = parsedMesh.animations[animationIndex];
  20847. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20848. }
  20849. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20850. }
  20851. if (parsedMesh.autoAnimate) {
  20852. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20853. }
  20854. // Layer Mask
  20855. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20856. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20857. }
  20858. else {
  20859. mesh.layerMask = 0x0FFFFFFF;
  20860. }
  20861. //(Deprecated) physics
  20862. if (parsedMesh.physicsImpostor) {
  20863. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20864. mass: parsedMesh.physicsMass,
  20865. friction: parsedMesh.physicsFriction,
  20866. restitution: parsedMesh.physicsRestitution
  20867. }, scene);
  20868. }
  20869. // Instances
  20870. if (parsedMesh.instances) {
  20871. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20872. var parsedInstance = parsedMesh.instances[index];
  20873. var instance = mesh.createInstance(parsedInstance.name);
  20874. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20875. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20876. if (parsedInstance.parentId) {
  20877. instance._waitingParentId = parsedInstance.parentId;
  20878. }
  20879. if (parsedInstance.rotationQuaternion) {
  20880. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20881. }
  20882. else if (parsedInstance.rotation) {
  20883. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20884. }
  20885. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20886. instance.checkCollisions = mesh.checkCollisions;
  20887. if (parsedMesh.animations) {
  20888. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20889. parsedAnimation = parsedMesh.animations[animationIndex];
  20890. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20891. }
  20892. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20893. }
  20894. }
  20895. }
  20896. return mesh;
  20897. };
  20898. /**
  20899. * Creates a ribbon mesh.
  20900. * Please consider using the same method from the MeshBuilder class instead.
  20901. * 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.
  20902. *
  20903. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20904. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20905. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20906. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20907. * 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.
  20908. * 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.
  20909. * 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
  20910. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20911. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20912. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20913. */
  20914. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20915. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20916. pathArray: pathArray,
  20917. closeArray: closeArray,
  20918. closePath: closePath,
  20919. offset: offset,
  20920. updatable: updatable,
  20921. sideOrientation: sideOrientation,
  20922. instance: instance
  20923. }, scene);
  20924. };
  20925. /**
  20926. * Creates a plane polygonal mesh. By default, this is a disc.
  20927. * Please consider using the same method from the MeshBuilder class instead.
  20928. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20929. * 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.
  20930. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20931. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20932. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20933. */
  20934. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20935. var options = {
  20936. radius: radius,
  20937. tessellation: tessellation,
  20938. sideOrientation: sideOrientation,
  20939. updatable: updatable
  20940. };
  20941. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20942. };
  20943. /**
  20944. * Creates a box mesh.
  20945. * Please consider using the same method from the MeshBuilder class instead.
  20946. * The parameter `size` sets the size (float) of each box side (default 1).
  20947. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20948. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20950. */
  20951. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20952. var options = {
  20953. size: size,
  20954. sideOrientation: sideOrientation,
  20955. updatable: updatable
  20956. };
  20957. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20958. };
  20959. /**
  20960. * Creates a sphere mesh.
  20961. * Please consider using the same method from the MeshBuilder class instead.
  20962. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20963. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20964. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20965. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20966. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20967. */
  20968. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20969. var options = {
  20970. segments: segments,
  20971. diameterX: diameter,
  20972. diameterY: diameter,
  20973. diameterZ: diameter,
  20974. sideOrientation: sideOrientation,
  20975. updatable: updatable
  20976. };
  20977. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20978. };
  20979. /**
  20980. * Creates a cylinder or a cone mesh.
  20981. * Please consider using the same method from the MeshBuilder class instead.
  20982. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20983. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20984. * 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.
  20985. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20986. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20987. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20988. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20989. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20990. */
  20991. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20992. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20993. if (scene !== undefined) {
  20994. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20995. updatable = scene;
  20996. }
  20997. scene = subdivisions;
  20998. subdivisions = 1;
  20999. }
  21000. var options = {
  21001. height: height,
  21002. diameterTop: diameterTop,
  21003. diameterBottom: diameterBottom,
  21004. tessellation: tessellation,
  21005. subdivisions: subdivisions,
  21006. sideOrientation: sideOrientation,
  21007. updatable: updatable
  21008. };
  21009. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21010. };
  21011. // Torus (Code from SharpDX.org)
  21012. /**
  21013. * Creates a torus mesh.
  21014. * Please consider using the same method from the MeshBuilder class instead.
  21015. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21016. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21017. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21018. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21019. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21021. */
  21022. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21023. var options = {
  21024. diameter: diameter,
  21025. thickness: thickness,
  21026. tessellation: tessellation,
  21027. sideOrientation: sideOrientation,
  21028. updatable: updatable
  21029. };
  21030. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21031. };
  21032. /**
  21033. * Creates a torus knot mesh.
  21034. * Please consider using the same method from the MeshBuilder class instead.
  21035. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21036. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21037. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21038. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21039. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21040. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21041. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21042. */
  21043. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21044. var options = {
  21045. radius: radius,
  21046. tube: tube,
  21047. radialSegments: radialSegments,
  21048. tubularSegments: tubularSegments,
  21049. p: p,
  21050. q: q,
  21051. sideOrientation: sideOrientation,
  21052. updatable: updatable
  21053. };
  21054. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21055. };
  21056. /**
  21057. * Creates a line mesh.
  21058. * Please consider using the same method from the MeshBuilder class instead.
  21059. * 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.
  21060. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21061. * The parameter `points` is an array successive Vector3.
  21062. * 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
  21063. * When updating an instance, remember that only point positions can change, not the number of points.
  21064. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21065. */
  21066. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21067. var options = {
  21068. points: points,
  21069. updatable: updatable,
  21070. instance: instance
  21071. };
  21072. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21073. };
  21074. /**
  21075. * Creates a dashed line mesh.
  21076. * Please consider using the same method from the MeshBuilder class instead.
  21077. * 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.
  21078. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21079. * The parameter `points` is an array successive Vector3.
  21080. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21081. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21082. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21083. * 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
  21084. * When updating an instance, remember that only point positions can change, not the number of points.
  21085. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21086. */
  21087. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21088. var options = {
  21089. points: points,
  21090. dashSize: dashSize,
  21091. gapSize: gapSize,
  21092. dashNb: dashNb,
  21093. updatable: updatable,
  21094. instance: instance
  21095. };
  21096. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21097. };
  21098. /**
  21099. * Creates an extruded shape mesh.
  21100. * 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.
  21101. * Please consider using the same method from the MeshBuilder class instead.
  21102. *
  21103. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21104. * 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
  21105. * extruded along the Z axis.
  21106. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21107. * 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.
  21108. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21109. * 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
  21110. * 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
  21111. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21112. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21113. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21115. */
  21116. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21117. var options = {
  21118. shape: shape,
  21119. path: path,
  21120. scale: scale,
  21121. rotation: rotation,
  21122. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21123. sideOrientation: sideOrientation,
  21124. instance: instance,
  21125. updatable: updatable
  21126. };
  21127. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21128. };
  21129. /**
  21130. * Creates an custom extruded shape mesh.
  21131. * 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.
  21132. * Please consider using the same method from the MeshBuilder class instead.
  21133. *
  21134. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21135. * 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
  21136. * extruded along the Z axis.
  21137. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21138. * 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
  21139. * and the distance of this point from the begining of the path :
  21140. * ```javascript
  21141. * var rotationFunction = function(i, distance) {
  21142. * // do things
  21143. * return rotationValue; }
  21144. * ```
  21145. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21146. * 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
  21147. * and the distance of this point from the begining of the path :
  21148. * ```javascript
  21149. * var scaleFunction = function(i, distance) {
  21150. * // do things
  21151. * return scaleValue;}
  21152. * ```
  21153. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21154. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21155. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21156. * 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
  21157. * 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
  21158. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21162. */
  21163. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21164. var options = {
  21165. shape: shape,
  21166. path: path,
  21167. scaleFunction: scaleFunction,
  21168. rotationFunction: rotationFunction,
  21169. ribbonCloseArray: ribbonCloseArray,
  21170. ribbonClosePath: ribbonClosePath,
  21171. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21172. sideOrientation: sideOrientation,
  21173. instance: instance,
  21174. updatable: updatable
  21175. };
  21176. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21177. };
  21178. /**
  21179. * Creates lathe mesh.
  21180. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21181. * Please consider using the same method from the MeshBuilder class instead.
  21182. * 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
  21183. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21184. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21185. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21186. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21187. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21188. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21189. */
  21190. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21191. var options = {
  21192. shape: shape,
  21193. radius: radius,
  21194. tessellation: tessellation,
  21195. sideOrientation: sideOrientation,
  21196. updatable: updatable
  21197. };
  21198. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21199. };
  21200. /**
  21201. * Creates a plane mesh.
  21202. * Please consider using the same method from the MeshBuilder class instead.
  21203. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21204. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21205. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21207. */
  21208. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21209. var options = {
  21210. size: size,
  21211. width: size,
  21212. height: size,
  21213. sideOrientation: sideOrientation,
  21214. updatable: updatable
  21215. };
  21216. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21217. };
  21218. /**
  21219. * Creates a ground mesh.
  21220. * Please consider using the same method from the MeshBuilder class instead.
  21221. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21222. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21223. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21224. */
  21225. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21226. var options = {
  21227. width: width,
  21228. height: height,
  21229. subdivisions: subdivisions,
  21230. updatable: updatable
  21231. };
  21232. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21233. };
  21234. /**
  21235. * Creates a tiled ground mesh.
  21236. * Please consider using the same method from the MeshBuilder class instead.
  21237. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21238. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21239. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21240. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21241. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21242. * numbers of subdivisions on the ground width and height of each tile.
  21243. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21244. */
  21245. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21246. var options = {
  21247. xmin: xmin,
  21248. zmin: zmin,
  21249. xmax: xmax,
  21250. zmax: zmax,
  21251. subdivisions: subdivisions,
  21252. precision: precision,
  21253. updatable: updatable
  21254. };
  21255. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21256. };
  21257. /**
  21258. * Creates a ground mesh from a height map.
  21259. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21260. * Please consider using the same method from the MeshBuilder class instead.
  21261. * The parameter `url` sets the URL of the height map image resource.
  21262. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21263. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21264. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21265. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21266. * 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).
  21267. * This function is passed the newly built mesh :
  21268. * ```javascript
  21269. * function(mesh) { // do things
  21270. * return; }
  21271. * ```
  21272. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21273. */
  21274. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21275. var options = {
  21276. width: width,
  21277. height: height,
  21278. subdivisions: subdivisions,
  21279. minHeight: minHeight,
  21280. maxHeight: maxHeight,
  21281. updatable: updatable,
  21282. onReady: onReady
  21283. };
  21284. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21285. };
  21286. /**
  21287. * Creates a tube mesh.
  21288. * 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.
  21289. * Please consider using the same method from the MeshBuilder class instead.
  21290. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21291. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21292. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21293. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21294. * 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.
  21295. * It must return a radius value (positive float) :
  21296. * ```javascript
  21297. * var radiusFunction = function(i, distance) {
  21298. * // do things
  21299. * return radius; }
  21300. * ```
  21301. * 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
  21302. * 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
  21303. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21304. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21305. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21306. */
  21307. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21308. var options = {
  21309. path: path,
  21310. radius: radius,
  21311. tessellation: tessellation,
  21312. radiusFunction: radiusFunction,
  21313. arc: 1,
  21314. cap: cap,
  21315. updatable: updatable,
  21316. sideOrientation: sideOrientation,
  21317. instance: instance
  21318. };
  21319. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21320. };
  21321. /**
  21322. * Creates a polyhedron mesh.
  21323. * Please consider using the same method from the MeshBuilder class instead.
  21324. * 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
  21325. * to choose the wanted type.
  21326. * The parameter `size` (positive float, default 1) sets the polygon size.
  21327. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21328. * 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`.
  21329. * 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
  21330. * 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)`).
  21331. * 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
  21332. * 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.
  21333. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21334. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21336. */
  21337. Mesh.CreatePolyhedron = function (name, options, scene) {
  21338. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21339. };
  21340. /**
  21341. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21342. * Please consider using the same method from the MeshBuilder class instead.
  21343. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21344. * 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`).
  21345. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21346. * 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.
  21347. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21348. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21349. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21350. */
  21351. Mesh.CreateIcoSphere = function (name, options, scene) {
  21352. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21353. };
  21354. /**
  21355. * Creates a decal mesh.
  21356. * Please consider using the same method from the MeshBuilder class instead.
  21357. * 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.
  21358. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21359. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21360. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21361. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21362. */
  21363. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21364. var options = {
  21365. position: position,
  21366. normal: normal,
  21367. size: size,
  21368. angle: angle
  21369. };
  21370. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21371. };
  21372. // Skeletons
  21373. /**
  21374. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21375. */
  21376. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21377. var source;
  21378. if (!this._sourcePositions) {
  21379. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21380. this._sourcePositions = new Float32Array(source);
  21381. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21382. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21383. }
  21384. }
  21385. return this._sourcePositions;
  21386. };
  21387. /**
  21388. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21389. */
  21390. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21391. var source;
  21392. if (!this._sourceNormals) {
  21393. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21394. this._sourceNormals = new Float32Array(source);
  21395. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21396. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21397. }
  21398. }
  21399. return this._sourceNormals;
  21400. };
  21401. /**
  21402. * Update the vertex buffers by applying transformation from the bones
  21403. * @param {skeleton} skeleton to apply
  21404. */
  21405. Mesh.prototype.applySkeleton = function (skeleton) {
  21406. if (!this.geometry) {
  21407. return;
  21408. }
  21409. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21410. return;
  21411. }
  21412. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21413. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21414. return this;
  21415. }
  21416. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21417. return this;
  21418. }
  21419. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21420. return this;
  21421. }
  21422. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21423. return this;
  21424. }
  21425. if (!this._sourcePositions) {
  21426. var submeshes = this.subMeshes.slice();
  21427. this.setPositionsForCPUSkinning();
  21428. this.subMeshes = submeshes;
  21429. }
  21430. if (!this._sourceNormals) {
  21431. this.setNormalsForCPUSkinning();
  21432. }
  21433. // positionsData checks for not being Float32Array will only pass at most once
  21434. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21435. if (!(positionsData instanceof Float32Array)) {
  21436. positionsData = new Float32Array(positionsData);
  21437. }
  21438. // normalsData checks for not being Float32Array will only pass at most once
  21439. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21440. if (!(normalsData instanceof Float32Array)) {
  21441. normalsData = new Float32Array(normalsData);
  21442. }
  21443. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21444. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21445. var needExtras = this.numBoneInfluencers > 4;
  21446. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21447. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21448. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21449. var tempVector3 = BABYLON.Vector3.Zero();
  21450. var finalMatrix = new BABYLON.Matrix();
  21451. var tempMatrix = new BABYLON.Matrix();
  21452. var matWeightIdx = 0;
  21453. var inf;
  21454. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21455. var weight;
  21456. for (inf = 0; inf < 4; inf++) {
  21457. weight = matricesWeightsData[matWeightIdx + inf];
  21458. if (weight > 0) {
  21459. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21460. finalMatrix.addToSelf(tempMatrix);
  21461. }
  21462. else
  21463. break;
  21464. }
  21465. if (needExtras) {
  21466. for (inf = 0; inf < 4; inf++) {
  21467. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21468. if (weight > 0) {
  21469. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21470. finalMatrix.addToSelf(tempMatrix);
  21471. }
  21472. else
  21473. break;
  21474. }
  21475. }
  21476. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21477. tempVector3.toArray(positionsData, index);
  21478. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21479. tempVector3.toArray(normalsData, index);
  21480. finalMatrix.reset();
  21481. }
  21482. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21483. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21484. return this;
  21485. };
  21486. // Tools
  21487. /**
  21488. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21489. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21490. */
  21491. Mesh.MinMax = function (meshes) {
  21492. var minVector = null;
  21493. var maxVector = null;
  21494. meshes.forEach(function (mesh, index, array) {
  21495. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21496. if (!minVector) {
  21497. minVector = boundingBox.minimumWorld;
  21498. maxVector = boundingBox.maximumWorld;
  21499. }
  21500. else {
  21501. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21502. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21503. }
  21504. });
  21505. return {
  21506. min: minVector,
  21507. max: maxVector
  21508. };
  21509. };
  21510. /**
  21511. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21512. */
  21513. Mesh.Center = function (meshesOrMinMaxVector) {
  21514. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21515. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21516. };
  21517. /**
  21518. * Merge the array of meshes into a single mesh for performance reasons.
  21519. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21520. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21521. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21522. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21523. */
  21524. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21525. if (disposeSource === void 0) { disposeSource = true; }
  21526. var index;
  21527. if (!allow32BitsIndices) {
  21528. var totalVertices = 0;
  21529. // Counting vertices
  21530. for (index = 0; index < meshes.length; index++) {
  21531. if (meshes[index]) {
  21532. totalVertices += meshes[index].getTotalVertices();
  21533. if (totalVertices > 65536) {
  21534. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21535. return null;
  21536. }
  21537. }
  21538. }
  21539. }
  21540. // Merge
  21541. var vertexData;
  21542. var otherVertexData;
  21543. var source;
  21544. for (index = 0; index < meshes.length; index++) {
  21545. if (meshes[index]) {
  21546. meshes[index].computeWorldMatrix(true);
  21547. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21548. otherVertexData.transform(meshes[index].getWorldMatrix());
  21549. if (vertexData) {
  21550. vertexData.merge(otherVertexData);
  21551. }
  21552. else {
  21553. vertexData = otherVertexData;
  21554. source = meshes[index];
  21555. }
  21556. }
  21557. }
  21558. if (!meshSubclass) {
  21559. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21560. }
  21561. vertexData.applyToMesh(meshSubclass);
  21562. // Setting properties
  21563. meshSubclass.material = source.material;
  21564. meshSubclass.checkCollisions = source.checkCollisions;
  21565. // Cleaning
  21566. if (disposeSource) {
  21567. for (index = 0; index < meshes.length; index++) {
  21568. if (meshes[index]) {
  21569. meshes[index].dispose();
  21570. }
  21571. }
  21572. }
  21573. return meshSubclass;
  21574. };
  21575. // Consts
  21576. Mesh._FRONTSIDE = 0;
  21577. Mesh._BACKSIDE = 1;
  21578. Mesh._DOUBLESIDE = 2;
  21579. Mesh._DEFAULTSIDE = 0;
  21580. Mesh._NO_CAP = 0;
  21581. Mesh._CAP_START = 1;
  21582. Mesh._CAP_END = 2;
  21583. Mesh._CAP_ALL = 3;
  21584. return Mesh;
  21585. }(BABYLON.AbstractMesh));
  21586. BABYLON.Mesh = Mesh;
  21587. })(BABYLON || (BABYLON = {}));
  21588. var BABYLON;
  21589. (function (BABYLON) {
  21590. var SubMesh = (function () {
  21591. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21592. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21593. this.materialIndex = materialIndex;
  21594. this.verticesStart = verticesStart;
  21595. this.verticesCount = verticesCount;
  21596. this.indexStart = indexStart;
  21597. this.indexCount = indexCount;
  21598. this._renderId = 0;
  21599. this._mesh = mesh;
  21600. this._renderingMesh = renderingMesh || mesh;
  21601. mesh.subMeshes.push(this);
  21602. this._trianglePlanes = [];
  21603. this._id = mesh.subMeshes.length - 1;
  21604. if (createBoundingBox) {
  21605. this.refreshBoundingInfo();
  21606. mesh.computeWorldMatrix(true);
  21607. }
  21608. }
  21609. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21610. get: function () {
  21611. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21612. },
  21613. enumerable: true,
  21614. configurable: true
  21615. });
  21616. SubMesh.prototype.getBoundingInfo = function () {
  21617. if (this.IsGlobal) {
  21618. return this._mesh.getBoundingInfo();
  21619. }
  21620. return this._boundingInfo;
  21621. };
  21622. SubMesh.prototype.getMesh = function () {
  21623. return this._mesh;
  21624. };
  21625. SubMesh.prototype.getRenderingMesh = function () {
  21626. return this._renderingMesh;
  21627. };
  21628. SubMesh.prototype.getMaterial = function () {
  21629. var rootMaterial = this._renderingMesh.material;
  21630. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  21631. var multiMaterial = rootMaterial;
  21632. return multiMaterial.getSubMaterial(this.materialIndex);
  21633. }
  21634. if (!rootMaterial) {
  21635. return this._mesh.getScene().defaultMaterial;
  21636. }
  21637. return rootMaterial;
  21638. };
  21639. // Methods
  21640. SubMesh.prototype.refreshBoundingInfo = function () {
  21641. this._lastColliderWorldVertices = null;
  21642. if (this.IsGlobal) {
  21643. return;
  21644. }
  21645. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21646. if (!data) {
  21647. this._boundingInfo = this._mesh._boundingInfo;
  21648. return;
  21649. }
  21650. var indices = this._renderingMesh.getIndices();
  21651. var extend;
  21652. //is this the only submesh?
  21653. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21654. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21655. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21656. }
  21657. else {
  21658. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21659. }
  21660. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21661. };
  21662. SubMesh.prototype._checkCollision = function (collider) {
  21663. return this.getBoundingInfo()._checkCollision(collider);
  21664. };
  21665. SubMesh.prototype.updateBoundingInfo = function (world) {
  21666. if (!this.getBoundingInfo()) {
  21667. this.refreshBoundingInfo();
  21668. }
  21669. this.getBoundingInfo().update(world);
  21670. };
  21671. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21672. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21673. };
  21674. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21675. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21676. };
  21677. SubMesh.prototype.render = function (enableAlphaMode) {
  21678. this._renderingMesh.render(this, enableAlphaMode);
  21679. };
  21680. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21681. if (!this._linesIndexBuffer) {
  21682. var linesIndices = [];
  21683. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21684. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21685. }
  21686. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21687. this.linesIndexCount = linesIndices.length;
  21688. }
  21689. return this._linesIndexBuffer;
  21690. };
  21691. SubMesh.prototype.canIntersects = function (ray) {
  21692. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21693. };
  21694. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21695. var intersectInfo = null;
  21696. // LineMesh first as it's also a Mesh...
  21697. if (this._mesh instanceof BABYLON.LinesMesh) {
  21698. var lineMesh = this._mesh;
  21699. // Line test
  21700. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21701. var p0 = positions[indices[index]];
  21702. var p1 = positions[indices[index + 1]];
  21703. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21704. if (length < 0) {
  21705. continue;
  21706. }
  21707. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21708. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21709. if (fastCheck) {
  21710. break;
  21711. }
  21712. }
  21713. }
  21714. }
  21715. else {
  21716. // Triangles test
  21717. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21718. var p0 = positions[indices[index]];
  21719. var p1 = positions[indices[index + 1]];
  21720. var p2 = positions[indices[index + 2]];
  21721. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21722. if (currentIntersectInfo) {
  21723. if (currentIntersectInfo.distance < 0) {
  21724. continue;
  21725. }
  21726. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21727. intersectInfo = currentIntersectInfo;
  21728. intersectInfo.faceId = index / 3;
  21729. if (fastCheck) {
  21730. break;
  21731. }
  21732. }
  21733. }
  21734. }
  21735. }
  21736. return intersectInfo;
  21737. };
  21738. // Clone
  21739. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21740. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21741. if (!this.IsGlobal) {
  21742. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21743. }
  21744. return result;
  21745. };
  21746. // Dispose
  21747. SubMesh.prototype.dispose = function () {
  21748. if (this._linesIndexBuffer) {
  21749. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21750. this._linesIndexBuffer = null;
  21751. }
  21752. // Remove from mesh
  21753. var index = this._mesh.subMeshes.indexOf(this);
  21754. this._mesh.subMeshes.splice(index, 1);
  21755. };
  21756. // Statics
  21757. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21758. var minVertexIndex = Number.MAX_VALUE;
  21759. var maxVertexIndex = -Number.MAX_VALUE;
  21760. renderingMesh = renderingMesh || mesh;
  21761. var indices = renderingMesh.getIndices();
  21762. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21763. var vertexIndex = indices[index];
  21764. if (vertexIndex < minVertexIndex)
  21765. minVertexIndex = vertexIndex;
  21766. if (vertexIndex > maxVertexIndex)
  21767. maxVertexIndex = vertexIndex;
  21768. }
  21769. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21770. };
  21771. return SubMesh;
  21772. }());
  21773. BABYLON.SubMesh = SubMesh;
  21774. })(BABYLON || (BABYLON = {}));
  21775. var BABYLON;
  21776. (function (BABYLON) {
  21777. var MeshBuilder = (function () {
  21778. function MeshBuilder() {
  21779. }
  21780. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  21781. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  21782. return BABYLON.Mesh.DOUBLESIDE;
  21783. }
  21784. if (orientation === undefined || orientation === null) {
  21785. return BABYLON.Mesh.FRONTSIDE;
  21786. }
  21787. return orientation;
  21788. };
  21789. /**
  21790. * Creates a box mesh.
  21791. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21792. * The parameter `size` sets the size (float) of each box side (default 1).
  21793. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21794. * 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).
  21795. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21796. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21799. */
  21800. MeshBuilder.CreateBox = function (name, options, scene) {
  21801. var box = new BABYLON.Mesh(name, scene);
  21802. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21803. var vertexData = BABYLON.VertexData.CreateBox(options);
  21804. vertexData.applyToMesh(box, options.updatable);
  21805. return box;
  21806. };
  21807. /**
  21808. * Creates a sphere mesh.
  21809. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21810. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21811. * 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`).
  21812. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21813. * 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
  21814. * 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).
  21815. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21816. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21817. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21818. */
  21819. MeshBuilder.CreateSphere = function (name, options, scene) {
  21820. var sphere = new BABYLON.Mesh(name, scene);
  21821. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21822. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21823. vertexData.applyToMesh(sphere, options.updatable);
  21824. return sphere;
  21825. };
  21826. /**
  21827. * Creates a plane polygonal mesh. By default, this is a disc.
  21828. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21829. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21830. * 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.
  21831. * 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
  21832. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21833. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21835. */
  21836. MeshBuilder.CreateDisc = function (name, options, scene) {
  21837. var disc = new BABYLON.Mesh(name, scene);
  21838. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21839. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21840. vertexData.applyToMesh(disc, options.updatable);
  21841. return disc;
  21842. };
  21843. /**
  21844. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21845. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21846. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21847. * 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`).
  21848. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21849. * 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.
  21850. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21851. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21853. */
  21854. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21855. var sphere = new BABYLON.Mesh(name, scene);
  21856. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21857. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21858. vertexData.applyToMesh(sphere, options.updatable);
  21859. return sphere;
  21860. };
  21861. ;
  21862. /**
  21863. * Creates a ribbon mesh.
  21864. * 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.
  21865. *
  21866. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21867. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21868. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21869. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21870. * 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.
  21871. * 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.
  21872. * 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
  21873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21874. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21875. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21876. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21877. */
  21878. MeshBuilder.CreateRibbon = function (name, options, scene) {
  21879. var pathArray = options.pathArray;
  21880. var closeArray = options.closeArray;
  21881. var closePath = options.closePath;
  21882. var offset = options.offset;
  21883. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21884. var instance = options.instance;
  21885. var updatable = options.updatable;
  21886. if (instance) {
  21887. // positionFunction : ribbon case
  21888. // only pathArray and sideOrientation parameters are taken into account for positions update
  21889. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21890. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21891. var positionFunction = function (positions) {
  21892. var minlg = pathArray[0].length;
  21893. var i = 0;
  21894. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21895. for (var si = 1; si <= ns; si++) {
  21896. for (var p = 0; p < pathArray.length; p++) {
  21897. var path = pathArray[p];
  21898. var l = path.length;
  21899. minlg = (minlg < l) ? minlg : l;
  21900. var j = 0;
  21901. while (j < minlg) {
  21902. positions[i] = path[j].x;
  21903. positions[i + 1] = path[j].y;
  21904. positions[i + 2] = path[j].z;
  21905. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21906. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21907. }
  21908. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21909. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21910. }
  21911. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21912. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21913. }
  21914. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21915. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21916. }
  21917. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21918. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21919. }
  21920. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21921. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21922. }
  21923. j++;
  21924. i += 3;
  21925. }
  21926. if (instance._closePath) {
  21927. positions[i] = path[0].x;
  21928. positions[i + 1] = path[0].y;
  21929. positions[i + 2] = path[0].z;
  21930. i += 3;
  21931. }
  21932. }
  21933. }
  21934. };
  21935. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21936. positionFunction(positions);
  21937. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21938. instance._boundingInfo.update(instance._worldMatrix);
  21939. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21940. if (!(instance.areNormalsFrozen)) {
  21941. var indices = instance.getIndices();
  21942. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21943. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21944. if (instance._closePath) {
  21945. var indexFirst = 0;
  21946. var indexLast = 0;
  21947. for (var p = 0; p < pathArray.length; p++) {
  21948. indexFirst = instance._idx[p] * 3;
  21949. if (p + 1 < pathArray.length) {
  21950. indexLast = (instance._idx[p + 1] - 1) * 3;
  21951. }
  21952. else {
  21953. indexLast = normals.length - 3;
  21954. }
  21955. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21956. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21957. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21958. normals[indexLast] = normals[indexFirst];
  21959. normals[indexLast + 1] = normals[indexFirst + 1];
  21960. normals[indexLast + 2] = normals[indexFirst + 2];
  21961. }
  21962. }
  21963. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21964. }
  21965. return instance;
  21966. }
  21967. else {
  21968. var ribbon = new BABYLON.Mesh(name, scene);
  21969. ribbon.sideOrientation = sideOrientation;
  21970. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21971. if (closePath) {
  21972. ribbon._idx = vertexData._idx;
  21973. }
  21974. ribbon._closePath = closePath;
  21975. ribbon._closeArray = closeArray;
  21976. vertexData.applyToMesh(ribbon, updatable);
  21977. return ribbon;
  21978. }
  21979. };
  21980. /**
  21981. * Creates a cylinder or a cone mesh.
  21982. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21983. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21984. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21985. * 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.
  21986. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21987. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21988. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21989. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21990. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21991. * 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).
  21992. * 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
  21993. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21994. * 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
  21995. * 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.
  21996. * If `enclose` is false, a ring surface is one element.
  21997. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21998. * 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
  21999. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22000. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22002. */
  22003. MeshBuilder.CreateCylinder = function (name, options, scene) {
  22004. var cylinder = new BABYLON.Mesh(name, scene);
  22005. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22006. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  22007. vertexData.applyToMesh(cylinder, options.updatable);
  22008. return cylinder;
  22009. };
  22010. /**
  22011. * Creates a torus mesh.
  22012. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  22013. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22014. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22015. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22016. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22017. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22019. */
  22020. MeshBuilder.CreateTorus = function (name, options, scene) {
  22021. var torus = new BABYLON.Mesh(name, scene);
  22022. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22023. var vertexData = BABYLON.VertexData.CreateTorus(options);
  22024. vertexData.applyToMesh(torus, options.updatable);
  22025. return torus;
  22026. };
  22027. /**
  22028. * Creates a torus knot mesh.
  22029. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  22030. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22031. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22032. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22033. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22034. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22035. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22037. */
  22038. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  22039. var torusKnot = new BABYLON.Mesh(name, scene);
  22040. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22041. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  22042. vertexData.applyToMesh(torusKnot, options.updatable);
  22043. return torusKnot;
  22044. };
  22045. /**
  22046. * Creates a line system mesh.
  22047. * A line system is a pool of many lines gathered in a single mesh.
  22048. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  22049. * 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.
  22050. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  22051. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  22052. * 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
  22053. * 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
  22054. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  22055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22056. */
  22057. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22058. var instance = options.instance;
  22059. var lines = options.lines;
  22060. if (instance) {
  22061. var positionFunction = function (positions) {
  22062. var i = 0;
  22063. for (var l = 0; l < lines.length; l++) {
  22064. var points = lines[l];
  22065. for (var p = 0; p < points.length; p++) {
  22066. positions[i] = points[p].x;
  22067. positions[i + 1] = points[p].y;
  22068. positions[i + 2] = points[p].z;
  22069. i += 3;
  22070. }
  22071. }
  22072. };
  22073. instance.updateMeshPositions(positionFunction, false);
  22074. return instance;
  22075. }
  22076. // line system creation
  22077. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22078. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22079. vertexData.applyToMesh(lineSystem, options.updatable);
  22080. return lineSystem;
  22081. };
  22082. /**
  22083. * Creates a line mesh.
  22084. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22085. * 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.
  22086. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22087. * The parameter `points` is an array successive Vector3.
  22088. * 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
  22089. * When updating an instance, remember that only point positions can change, not the number of points.
  22090. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22091. */
  22092. MeshBuilder.CreateLines = function (name, options, scene) {
  22093. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22094. return lines;
  22095. };
  22096. /**
  22097. * Creates a dashed line mesh.
  22098. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22099. * 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.
  22100. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22101. * The parameter `points` is an array successive Vector3.
  22102. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22103. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22104. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22105. * 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
  22106. * When updating an instance, remember that only point positions can change, not the number of points.
  22107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22108. */
  22109. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22110. var points = options.points;
  22111. var instance = options.instance;
  22112. var gapSize = options.gapSize;
  22113. var dashNb = options.dashNb;
  22114. var dashSize = options.dashSize;
  22115. if (instance) {
  22116. var positionFunction = function (positions) {
  22117. var curvect = BABYLON.Vector3.Zero();
  22118. var nbSeg = positions.length / 6;
  22119. var lg = 0;
  22120. var nb = 0;
  22121. var shft = 0;
  22122. var dashshft = 0;
  22123. var curshft = 0;
  22124. var p = 0;
  22125. var i = 0;
  22126. var j = 0;
  22127. for (i = 0; i < points.length - 1; i++) {
  22128. points[i + 1].subtractToRef(points[i], curvect);
  22129. lg += curvect.length();
  22130. }
  22131. shft = lg / nbSeg;
  22132. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22133. for (i = 0; i < points.length - 1; i++) {
  22134. points[i + 1].subtractToRef(points[i], curvect);
  22135. nb = Math.floor(curvect.length() / shft);
  22136. curvect.normalize();
  22137. j = 0;
  22138. while (j < nb && p < positions.length) {
  22139. curshft = shft * j;
  22140. positions[p] = points[i].x + curshft * curvect.x;
  22141. positions[p + 1] = points[i].y + curshft * curvect.y;
  22142. positions[p + 2] = points[i].z + curshft * curvect.z;
  22143. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22144. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22145. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22146. p += 6;
  22147. j++;
  22148. }
  22149. }
  22150. while (p < positions.length) {
  22151. positions[p] = points[i].x;
  22152. positions[p + 1] = points[i].y;
  22153. positions[p + 2] = points[i].z;
  22154. p += 3;
  22155. }
  22156. };
  22157. instance.updateMeshPositions(positionFunction, false);
  22158. return instance;
  22159. }
  22160. // dashed lines creation
  22161. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22162. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22163. vertexData.applyToMesh(dashedLines, options.updatable);
  22164. dashedLines.dashSize = dashSize;
  22165. dashedLines.gapSize = gapSize;
  22166. return dashedLines;
  22167. };
  22168. /**
  22169. * Creates an extruded shape mesh.
  22170. * 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.
  22171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22172. *
  22173. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22174. * 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
  22175. * extruded along the Z axis.
  22176. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22177. * 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.
  22178. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22179. * 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
  22180. * 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
  22181. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22182. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22183. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22184. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22185. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22186. */
  22187. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22188. var path = options.path;
  22189. var shape = options.shape;
  22190. var scale = options.scale || 1;
  22191. var rotation = options.rotation || 0;
  22192. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22193. var updatable = options.updatable;
  22194. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22195. var instance = options.instance;
  22196. var invertUV = options.invertUV || false;
  22197. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22198. };
  22199. /**
  22200. * Creates an custom extruded shape mesh.
  22201. * 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.
  22202. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22203. *
  22204. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22205. * 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
  22206. * extruded along the Z axis.
  22207. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22208. * 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
  22209. * and the distance of this point from the begining of the path :
  22210. * ```javascript
  22211. * var rotationFunction = function(i, distance) {
  22212. * // do things
  22213. * return rotationValue; }
  22214. * ```
  22215. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22216. * 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
  22217. * and the distance of this point from the begining of the path :
  22218. * ```javascript
  22219. * var scaleFunction = function(i, distance) {
  22220. * // do things
  22221. * return scaleValue;}
  22222. * ```
  22223. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22224. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22225. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22226. * 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
  22227. * 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
  22228. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22229. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22230. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22231. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22233. */
  22234. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22235. var path = options.path;
  22236. var shape = options.shape;
  22237. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22238. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22239. var ribbonCloseArray = options.ribbonCloseArray || false;
  22240. var ribbonClosePath = options.ribbonClosePath || false;
  22241. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22242. var updatable = options.updatable;
  22243. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22244. var instance = options.instance;
  22245. var invertUV = options.invertUV || false;
  22246. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22247. };
  22248. /**
  22249. * Creates lathe mesh.
  22250. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22251. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22252. *
  22253. * 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
  22254. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22255. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22256. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22257. * 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.
  22258. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22259. * 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
  22260. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22261. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22262. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22264. */
  22265. MeshBuilder.CreateLathe = function (name, options, scene) {
  22266. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22267. var closed = (options.closed === undefined) ? true : options.closed;
  22268. var shape = options.shape;
  22269. var radius = options.radius || 1;
  22270. var tessellation = options.tessellation || 64;
  22271. var updatable = options.updatable;
  22272. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22273. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22274. var pi2 = Math.PI * 2;
  22275. var paths = new Array();
  22276. var invertUV = options.invertUV || false;
  22277. var i = 0;
  22278. var p = 0;
  22279. var step = pi2 / tessellation * arc;
  22280. var rotated;
  22281. var path = new Array();
  22282. ;
  22283. for (i = 0; i <= tessellation; i++) {
  22284. var path = [];
  22285. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22286. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22287. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22288. }
  22289. for (p = 0; p < shape.length; p++) {
  22290. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22291. path.push(rotated);
  22292. }
  22293. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22294. 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));
  22295. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22296. }
  22297. paths.push(path);
  22298. }
  22299. // lathe ribbon
  22300. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22301. return lathe;
  22302. };
  22303. /**
  22304. * Creates a plane mesh.
  22305. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22306. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22307. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22308. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22309. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22310. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22311. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22312. */
  22313. MeshBuilder.CreatePlane = function (name, options, scene) {
  22314. var plane = new BABYLON.Mesh(name, scene);
  22315. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22316. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22317. vertexData.applyToMesh(plane, options.updatable);
  22318. if (options.sourcePlane) {
  22319. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22320. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22321. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22322. plane.rotate(vectorProduct, product);
  22323. }
  22324. return plane;
  22325. };
  22326. /**
  22327. * Creates a ground mesh.
  22328. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22329. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22330. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22332. */
  22333. MeshBuilder.CreateGround = function (name, options, scene) {
  22334. var ground = new BABYLON.GroundMesh(name, scene);
  22335. ground._setReady(false);
  22336. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22337. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22338. ground._width = options.width || 1;
  22339. ground._height = options.height || 1;
  22340. ground._maxX = ground._width / 2;
  22341. ground._maxZ = ground._height / 2;
  22342. ground._minX = -ground._maxX;
  22343. ground._minZ = -ground._maxZ;
  22344. var vertexData = BABYLON.VertexData.CreateGround(options);
  22345. vertexData.applyToMesh(ground, options.updatable);
  22346. ground._setReady(true);
  22347. return ground;
  22348. };
  22349. /**
  22350. * Creates a tiled ground mesh.
  22351. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22352. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22353. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22354. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22355. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22356. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22357. * numbers of subdivisions on the ground width and height of each tile.
  22358. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22359. */
  22360. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22361. var tiledGround = new BABYLON.Mesh(name, scene);
  22362. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22363. vertexData.applyToMesh(tiledGround, options.updatable);
  22364. return tiledGround;
  22365. };
  22366. /**
  22367. * Creates a ground mesh from a height map.
  22368. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22369. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22370. * The parameter `url` sets the URL of the height map image resource.
  22371. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22372. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22373. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22374. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22375. * 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).
  22376. * This function is passed the newly built mesh :
  22377. * ```javascript
  22378. * function(mesh) { // do things
  22379. * return; }
  22380. * ```
  22381. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22382. */
  22383. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22384. var width = options.width || 10.0;
  22385. var height = options.height || 10.0;
  22386. var subdivisions = options.subdivisions || 1 | 0;
  22387. var minHeight = options.minHeight || 0.0;
  22388. var maxHeight = options.maxHeight || 10.0;
  22389. var updatable = options.updatable;
  22390. var onReady = options.onReady;
  22391. var ground = new BABYLON.GroundMesh(name, scene);
  22392. ground._subdivisionsX = subdivisions;
  22393. ground._subdivisionsY = subdivisions;
  22394. ground._width = width;
  22395. ground._height = height;
  22396. ground._maxX = ground._width / 2.0;
  22397. ground._maxZ = ground._height / 2.0;
  22398. ground._minX = -ground._maxX;
  22399. ground._minZ = -ground._maxZ;
  22400. ground._setReady(false);
  22401. var onload = function (img) {
  22402. // Getting height map data
  22403. var canvas = document.createElement("canvas");
  22404. var context = canvas.getContext("2d");
  22405. var bufferWidth = img.width;
  22406. var bufferHeight = img.height;
  22407. canvas.width = bufferWidth;
  22408. canvas.height = bufferHeight;
  22409. context.drawImage(img, 0, 0);
  22410. // Create VertexData from map data
  22411. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22412. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22413. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22414. width: width, height: height,
  22415. subdivisions: subdivisions,
  22416. minHeight: minHeight, maxHeight: maxHeight,
  22417. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22418. });
  22419. vertexData.applyToMesh(ground, updatable);
  22420. ground._setReady(true);
  22421. //execute ready callback, if set
  22422. if (onReady) {
  22423. onReady(ground);
  22424. }
  22425. };
  22426. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22427. return ground;
  22428. };
  22429. /**
  22430. * Creates a tube mesh.
  22431. * 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.
  22432. *
  22433. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22434. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22435. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22436. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22437. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22438. * 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.
  22439. * It must return a radius value (positive float) :
  22440. * ```javascript
  22441. * var radiusFunction = function(i, distance) {
  22442. * // do things
  22443. * return radius; }
  22444. * ```
  22445. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22446. * 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
  22447. * 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
  22448. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22449. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22450. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22452. */
  22453. MeshBuilder.CreateTube = function (name, options, scene) {
  22454. var path = options.path;
  22455. var radius = options.radius || 1.0;
  22456. var tessellation = options.tessellation || 64 | 0;
  22457. var radiusFunction = options.radiusFunction;
  22458. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22459. var invertUV = options.invertUV || false;
  22460. var updatable = options.updatable;
  22461. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22462. var instance = options.instance;
  22463. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22464. // tube geometry
  22465. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22466. var tangents = path3D.getTangents();
  22467. var normals = path3D.getNormals();
  22468. var distances = path3D.getDistances();
  22469. var pi2 = Math.PI * 2;
  22470. var step = pi2 / tessellation * arc;
  22471. var returnRadius = function () { return radius; };
  22472. var radiusFunctionFinal = radiusFunction || returnRadius;
  22473. var circlePath;
  22474. var rad;
  22475. var normal;
  22476. var rotated;
  22477. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22478. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22479. for (var i = 0; i < path.length; i++) {
  22480. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22481. circlePath = Array(); // current circle array
  22482. normal = normals[i]; // current normal
  22483. for (var t = 0; t < tessellation; t++) {
  22484. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22485. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22486. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22487. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22488. circlePath[t] = rotated;
  22489. }
  22490. circlePaths[index] = circlePath;
  22491. index++;
  22492. }
  22493. // cap
  22494. var capPath = function (nbPoints, pathIndex) {
  22495. var pointCap = Array();
  22496. for (var i = 0; i < nbPoints; i++) {
  22497. pointCap.push(path[pathIndex]);
  22498. }
  22499. return pointCap;
  22500. };
  22501. switch (cap) {
  22502. case BABYLON.Mesh.NO_CAP:
  22503. break;
  22504. case BABYLON.Mesh.CAP_START:
  22505. circlePaths[0] = capPath(tessellation, 0);
  22506. circlePaths[1] = circlePaths[2].slice(0);
  22507. break;
  22508. case BABYLON.Mesh.CAP_END:
  22509. circlePaths[index] = circlePaths[index - 1].slice(0);
  22510. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22511. break;
  22512. case BABYLON.Mesh.CAP_ALL:
  22513. circlePaths[0] = capPath(tessellation, 0);
  22514. circlePaths[1] = circlePaths[2].slice(0);
  22515. circlePaths[index] = circlePaths[index - 1].slice(0);
  22516. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22517. break;
  22518. default:
  22519. break;
  22520. }
  22521. return circlePaths;
  22522. };
  22523. var path3D;
  22524. var pathArray;
  22525. if (instance) {
  22526. var arc = options.arc || instance.arc;
  22527. path3D = (instance.path3D).update(path);
  22528. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22529. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22530. instance.path3D = path3D;
  22531. instance.pathArray = pathArray;
  22532. instance.arc = arc;
  22533. return instance;
  22534. }
  22535. // tube creation
  22536. path3D = new BABYLON.Path3D(path);
  22537. var newPathArray = new Array();
  22538. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22539. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22540. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22541. tube.pathArray = pathArray;
  22542. tube.path3D = path3D;
  22543. tube.tessellation = tessellation;
  22544. tube.cap = cap;
  22545. tube.arc = options.arc;
  22546. return tube;
  22547. };
  22548. /**
  22549. * Creates a polyhedron mesh.
  22550. *
  22551. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22552. * 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
  22553. * to choose the wanted type.
  22554. * The parameter `size` (positive float, default 1) sets the polygon size.
  22555. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22556. * 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`.
  22557. * 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
  22558. * 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)`).
  22559. * 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
  22560. * 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.
  22561. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22562. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22564. */
  22565. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22566. var polyhedron = new BABYLON.Mesh(name, scene);
  22567. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22568. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22569. vertexData.applyToMesh(polyhedron, options.updatable);
  22570. return polyhedron;
  22571. };
  22572. /**
  22573. * Creates a decal mesh.
  22574. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22575. * 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.
  22576. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22577. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22578. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22579. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22580. */
  22581. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22582. var indices = sourceMesh.getIndices();
  22583. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22584. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22585. var position = options.position || BABYLON.Vector3.Zero();
  22586. var normal = options.normal || BABYLON.Vector3.Up();
  22587. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22588. var angle = options.angle || 0;
  22589. // Getting correct rotation
  22590. if (!normal) {
  22591. var target = new BABYLON.Vector3(0, 0, 1);
  22592. var camera = sourceMesh.getScene().activeCamera;
  22593. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22594. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22595. }
  22596. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22597. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22598. var pitch = Math.atan2(normal.y, len);
  22599. // Matrix
  22600. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22601. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22602. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22603. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22604. var vertexData = new BABYLON.VertexData();
  22605. vertexData.indices = [];
  22606. vertexData.positions = [];
  22607. vertexData.normals = [];
  22608. vertexData.uvs = [];
  22609. var currentVertexDataIndex = 0;
  22610. var extractDecalVector3 = function (indexId) {
  22611. var vertexId = indices[indexId];
  22612. var result = new BABYLON.PositionNormalVertex();
  22613. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  22614. // Send vector to decal local world
  22615. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  22616. // Get normal
  22617. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  22618. return result;
  22619. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  22620. var clip = function (vertices, axis) {
  22621. if (vertices.length === 0) {
  22622. return vertices;
  22623. }
  22624. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  22625. var clipVertices = function (v0, v1) {
  22626. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  22627. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  22628. };
  22629. var result = new Array();
  22630. for (var index = 0; index < vertices.length; index += 3) {
  22631. var v1Out;
  22632. var v2Out;
  22633. var v3Out;
  22634. var total = 0;
  22635. var nV1, nV2, nV3, nV4;
  22636. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  22637. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  22638. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  22639. v1Out = d1 > 0;
  22640. v2Out = d2 > 0;
  22641. v3Out = d3 > 0;
  22642. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  22643. switch (total) {
  22644. case 0:
  22645. result.push(vertices[index]);
  22646. result.push(vertices[index + 1]);
  22647. result.push(vertices[index + 2]);
  22648. break;
  22649. case 1:
  22650. if (v1Out) {
  22651. nV1 = vertices[index + 1];
  22652. nV2 = vertices[index + 2];
  22653. nV3 = clipVertices(vertices[index], nV1);
  22654. nV4 = clipVertices(vertices[index], nV2);
  22655. }
  22656. if (v2Out) {
  22657. nV1 = vertices[index];
  22658. nV2 = vertices[index + 2];
  22659. nV3 = clipVertices(vertices[index + 1], nV1);
  22660. nV4 = clipVertices(vertices[index + 1], nV2);
  22661. result.push(nV3);
  22662. result.push(nV2.clone());
  22663. result.push(nV1.clone());
  22664. result.push(nV2.clone());
  22665. result.push(nV3.clone());
  22666. result.push(nV4);
  22667. break;
  22668. }
  22669. if (v3Out) {
  22670. nV1 = vertices[index];
  22671. nV2 = vertices[index + 1];
  22672. nV3 = clipVertices(vertices[index + 2], nV1);
  22673. nV4 = clipVertices(vertices[index + 2], nV2);
  22674. }
  22675. result.push(nV1.clone());
  22676. result.push(nV2.clone());
  22677. result.push(nV3);
  22678. result.push(nV4);
  22679. result.push(nV3.clone());
  22680. result.push(nV2.clone());
  22681. break;
  22682. case 2:
  22683. if (!v1Out) {
  22684. nV1 = vertices[index].clone();
  22685. nV2 = clipVertices(nV1, vertices[index + 1]);
  22686. nV3 = clipVertices(nV1, vertices[index + 2]);
  22687. result.push(nV1);
  22688. result.push(nV2);
  22689. result.push(nV3);
  22690. }
  22691. if (!v2Out) {
  22692. nV1 = vertices[index + 1].clone();
  22693. nV2 = clipVertices(nV1, vertices[index + 2]);
  22694. nV3 = clipVertices(nV1, vertices[index]);
  22695. result.push(nV1);
  22696. result.push(nV2);
  22697. result.push(nV3);
  22698. }
  22699. if (!v3Out) {
  22700. nV1 = vertices[index + 2].clone();
  22701. nV2 = clipVertices(nV1, vertices[index]);
  22702. nV3 = clipVertices(nV1, vertices[index + 1]);
  22703. result.push(nV1);
  22704. result.push(nV2);
  22705. result.push(nV3);
  22706. }
  22707. break;
  22708. case 3:
  22709. break;
  22710. }
  22711. }
  22712. return result;
  22713. };
  22714. for (var index = 0; index < indices.length; index += 3) {
  22715. var faceVertices = new Array();
  22716. faceVertices.push(extractDecalVector3(index));
  22717. faceVertices.push(extractDecalVector3(index + 1));
  22718. faceVertices.push(extractDecalVector3(index + 2));
  22719. // Clip
  22720. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  22721. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  22722. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  22723. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  22724. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  22725. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  22726. if (faceVertices.length === 0) {
  22727. continue;
  22728. }
  22729. // Add UVs and get back to world
  22730. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  22731. var vertex = faceVertices[vIndex];
  22732. //TODO check for Int32Array
  22733. vertexData.indices.push(currentVertexDataIndex);
  22734. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  22735. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  22736. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  22737. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  22738. currentVertexDataIndex++;
  22739. }
  22740. }
  22741. // Return mesh
  22742. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  22743. vertexData.applyToMesh(decal);
  22744. decal.position = position.clone();
  22745. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  22746. return decal;
  22747. };
  22748. // Privates
  22749. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  22750. // extrusion geometry
  22751. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  22752. var tangents = path3D.getTangents();
  22753. var normals = path3D.getNormals();
  22754. var binormals = path3D.getBinormals();
  22755. var distances = path3D.getDistances();
  22756. var angle = 0;
  22757. var returnScale = function () { return scale; };
  22758. var returnRotation = function () { return rotation; };
  22759. var rotate = custom ? rotateFunction : returnRotation;
  22760. var scl = custom ? scaleFunction : returnScale;
  22761. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22762. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22763. for (var i = 0; i < curve.length; i++) {
  22764. var shapePath = new Array();
  22765. var angleStep = rotate(i, distances[i]);
  22766. var scaleRatio = scl(i, distances[i]);
  22767. for (var p = 0; p < shape.length; p++) {
  22768. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  22769. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  22770. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  22771. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  22772. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  22773. shapePath[p] = rotated;
  22774. }
  22775. shapePaths[index] = shapePath;
  22776. angle += angleStep;
  22777. index++;
  22778. }
  22779. // cap
  22780. var capPath = function (shapePath) {
  22781. var pointCap = Array();
  22782. var barycenter = BABYLON.Vector3.Zero();
  22783. var i;
  22784. for (i = 0; i < shapePath.length; i++) {
  22785. barycenter.addInPlace(shapePath[i]);
  22786. }
  22787. barycenter.scaleInPlace(1 / shapePath.length);
  22788. for (i = 0; i < shapePath.length; i++) {
  22789. pointCap.push(barycenter);
  22790. }
  22791. return pointCap;
  22792. };
  22793. switch (cap) {
  22794. case BABYLON.Mesh.NO_CAP:
  22795. break;
  22796. case BABYLON.Mesh.CAP_START:
  22797. shapePaths[0] = capPath(shapePaths[2]);
  22798. shapePaths[1] = shapePaths[2].slice(0);
  22799. break;
  22800. case BABYLON.Mesh.CAP_END:
  22801. shapePaths[index] = shapePaths[index - 1];
  22802. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22803. break;
  22804. case BABYLON.Mesh.CAP_ALL:
  22805. shapePaths[0] = capPath(shapePaths[2]);
  22806. shapePaths[1] = shapePaths[2].slice(0);
  22807. shapePaths[index] = shapePaths[index - 1];
  22808. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22809. break;
  22810. default:
  22811. break;
  22812. }
  22813. return shapePaths;
  22814. };
  22815. var path3D;
  22816. var pathArray;
  22817. if (instance) {
  22818. path3D = (instance.path3D).update(curve);
  22819. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22820. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  22821. return instance;
  22822. }
  22823. // extruded shape creation
  22824. path3D = new BABYLON.Path3D(curve);
  22825. var newShapePaths = new Array();
  22826. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22827. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22828. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22829. extrudedGeneric.pathArray = pathArray;
  22830. extrudedGeneric.path3D = path3D;
  22831. extrudedGeneric.cap = cap;
  22832. return extrudedGeneric;
  22833. };
  22834. return MeshBuilder;
  22835. }());
  22836. BABYLON.MeshBuilder = MeshBuilder;
  22837. })(BABYLON || (BABYLON = {}));
  22838. var BABYLON;
  22839. (function (BABYLON) {
  22840. var BaseTexture = (function () {
  22841. function BaseTexture(scene) {
  22842. this.hasAlpha = false;
  22843. this.getAlphaFromRGB = false;
  22844. this.level = 1;
  22845. this.coordinatesIndex = 0;
  22846. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22847. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22848. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22849. this.anisotropicFilteringLevel = 4;
  22850. this.isCube = false;
  22851. this.isRenderTarget = false;
  22852. this.animations = new Array();
  22853. /**
  22854. * An event triggered when the texture is disposed.
  22855. * @type {BABYLON.Observable}
  22856. */
  22857. this.onDisposeObservable = new BABYLON.Observable();
  22858. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22859. this._scene = scene;
  22860. this._scene.textures.push(this);
  22861. this._uid = null;
  22862. }
  22863. Object.defineProperty(BaseTexture.prototype, "uid", {
  22864. get: function () {
  22865. if (!this._uid) {
  22866. this._uid = BABYLON.Tools.RandomId();
  22867. }
  22868. return this._uid;
  22869. },
  22870. enumerable: true,
  22871. configurable: true
  22872. });
  22873. BaseTexture.prototype.toString = function () {
  22874. return this.name;
  22875. };
  22876. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22877. set: function (callback) {
  22878. if (this._onDisposeObserver) {
  22879. this.onDisposeObservable.remove(this._onDisposeObserver);
  22880. }
  22881. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22882. },
  22883. enumerable: true,
  22884. configurable: true
  22885. });
  22886. BaseTexture.prototype.getScene = function () {
  22887. return this._scene;
  22888. };
  22889. BaseTexture.prototype.getTextureMatrix = function () {
  22890. return null;
  22891. };
  22892. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22893. return null;
  22894. };
  22895. BaseTexture.prototype.getInternalTexture = function () {
  22896. return this._texture;
  22897. };
  22898. BaseTexture.prototype.isReady = function () {
  22899. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22900. return true;
  22901. }
  22902. if (this._texture) {
  22903. return this._texture.isReady;
  22904. }
  22905. return false;
  22906. };
  22907. BaseTexture.prototype.getSize = function () {
  22908. if (this._texture._width) {
  22909. return new BABYLON.Size(this._texture._width, this._texture._height);
  22910. }
  22911. if (this._texture._size) {
  22912. return new BABYLON.Size(this._texture._size, this._texture._size);
  22913. }
  22914. return BABYLON.Size.Zero();
  22915. };
  22916. BaseTexture.prototype.getBaseSize = function () {
  22917. if (!this.isReady() || !this._texture)
  22918. return BABYLON.Size.Zero();
  22919. if (this._texture._size) {
  22920. return new BABYLON.Size(this._texture._size, this._texture._size);
  22921. }
  22922. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22923. };
  22924. BaseTexture.prototype.scale = function (ratio) {
  22925. };
  22926. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22927. get: function () {
  22928. return false;
  22929. },
  22930. enumerable: true,
  22931. configurable: true
  22932. });
  22933. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22934. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22935. for (var index = 0; index < texturesCache.length; index++) {
  22936. var texturesCacheEntry = texturesCache[index];
  22937. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22938. texturesCache.splice(index, 1);
  22939. return;
  22940. }
  22941. }
  22942. };
  22943. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22944. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22945. for (var index = 0; index < texturesCache.length; index++) {
  22946. var texturesCacheEntry = texturesCache[index];
  22947. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22948. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22949. texturesCacheEntry.references++;
  22950. return texturesCacheEntry;
  22951. }
  22952. }
  22953. }
  22954. return null;
  22955. };
  22956. BaseTexture.prototype.delayLoad = function () {
  22957. };
  22958. BaseTexture.prototype.clone = function () {
  22959. return null;
  22960. };
  22961. BaseTexture.prototype.releaseInternalTexture = function () {
  22962. if (this._texture) {
  22963. this._scene.getEngine().releaseInternalTexture(this._texture);
  22964. delete this._texture;
  22965. }
  22966. };
  22967. BaseTexture.prototype.dispose = function () {
  22968. // Animations
  22969. this.getScene().stopAnimation(this);
  22970. // Remove from scene
  22971. var index = this._scene.textures.indexOf(this);
  22972. if (index >= 0) {
  22973. this._scene.textures.splice(index, 1);
  22974. }
  22975. if (this._texture === undefined) {
  22976. return;
  22977. }
  22978. // Release
  22979. this.releaseInternalTexture();
  22980. // Callback
  22981. this.onDisposeObservable.notifyObservers(this);
  22982. this.onDisposeObservable.clear();
  22983. };
  22984. BaseTexture.prototype.serialize = function () {
  22985. if (!this.name) {
  22986. return null;
  22987. }
  22988. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22989. // Animations
  22990. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22991. return serializationObject;
  22992. };
  22993. __decorate([
  22994. BABYLON.serialize()
  22995. ], BaseTexture.prototype, "name", void 0);
  22996. __decorate([
  22997. BABYLON.serialize()
  22998. ], BaseTexture.prototype, "hasAlpha", void 0);
  22999. __decorate([
  23000. BABYLON.serialize()
  23001. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23002. __decorate([
  23003. BABYLON.serialize()
  23004. ], BaseTexture.prototype, "level", void 0);
  23005. __decorate([
  23006. BABYLON.serialize()
  23007. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23008. __decorate([
  23009. BABYLON.serialize()
  23010. ], BaseTexture.prototype, "coordinatesMode", void 0);
  23011. __decorate([
  23012. BABYLON.serialize()
  23013. ], BaseTexture.prototype, "wrapU", void 0);
  23014. __decorate([
  23015. BABYLON.serialize()
  23016. ], BaseTexture.prototype, "wrapV", void 0);
  23017. __decorate([
  23018. BABYLON.serialize()
  23019. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23020. __decorate([
  23021. BABYLON.serialize()
  23022. ], BaseTexture.prototype, "isCube", void 0);
  23023. __decorate([
  23024. BABYLON.serialize()
  23025. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23026. return BaseTexture;
  23027. }());
  23028. BABYLON.BaseTexture = BaseTexture;
  23029. })(BABYLON || (BABYLON = {}));
  23030. var BABYLON;
  23031. (function (BABYLON) {
  23032. var Texture = (function (_super) {
  23033. __extends(Texture, _super);
  23034. function Texture(urlOrList, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  23035. var _this = this;
  23036. if (noMipmap === void 0) { noMipmap = false; }
  23037. if (invertY === void 0) { invertY = true; }
  23038. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23039. if (onLoad === void 0) { onLoad = null; }
  23040. if (onError === void 0) { onError = null; }
  23041. if (buffer === void 0) { buffer = null; }
  23042. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23043. _super.call(this, scene);
  23044. this.uOffset = 0;
  23045. this.vOffset = 0;
  23046. this.uScale = 1.0;
  23047. this.vScale = 1.0;
  23048. this.uAng = 0;
  23049. this.vAng = 0;
  23050. this.wAng = 0;
  23051. var url = ((urlOrList instanceof Array) ? urlOrList[0] : urlOrList);
  23052. this.name = url;
  23053. this.url = url;
  23054. this._delayReloadData = urlOrList;
  23055. this._noMipmap = noMipmap;
  23056. this._invertY = invertY;
  23057. this._samplingMode = samplingMode;
  23058. this._buffer = buffer;
  23059. this._deleteBuffer = deleteBuffer;
  23060. if (!url) {
  23061. return;
  23062. }
  23063. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  23064. var load = function () {
  23065. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23066. _this.onLoadObservable.notifyObservers(true);
  23067. }
  23068. if (onLoad) {
  23069. onLoad();
  23070. }
  23071. };
  23072. if (!this._texture) {
  23073. if (!scene.useDelayedTextureLoading) {
  23074. this._texture = scene.getEngine().createTexture(urlOrList, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  23075. if (deleteBuffer) {
  23076. delete this._buffer;
  23077. }
  23078. }
  23079. else {
  23080. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23081. this._delayedOnLoad = load;
  23082. this._delayedOnError = onError;
  23083. }
  23084. }
  23085. else {
  23086. if (this._texture.isReady) {
  23087. BABYLON.Tools.SetImmediate(function () { return load(); });
  23088. }
  23089. else {
  23090. this._texture.onLoadedCallbacks.push(load);
  23091. }
  23092. }
  23093. }
  23094. Object.defineProperty(Texture.prototype, "noMipmap", {
  23095. get: function () {
  23096. return this._noMipmap;
  23097. },
  23098. enumerable: true,
  23099. configurable: true
  23100. });
  23101. Texture.prototype.delayLoad = function () {
  23102. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23103. return;
  23104. }
  23105. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23106. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23107. if (!this._texture) {
  23108. this._texture = this.getScene().getEngine().createTexture(this._delayReloadData, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23109. if (this._deleteBuffer) {
  23110. delete this._buffer;
  23111. }
  23112. }
  23113. };
  23114. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23115. if (!this._texture) {
  23116. return;
  23117. }
  23118. this._samplingMode = samplingMode;
  23119. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23120. };
  23121. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23122. x *= this.uScale;
  23123. y *= this.vScale;
  23124. x -= 0.5 * this.uScale;
  23125. y -= 0.5 * this.vScale;
  23126. z -= 0.5;
  23127. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23128. t.x += 0.5 * this.uScale + this.uOffset;
  23129. t.y += 0.5 * this.vScale + this.vOffset;
  23130. t.z += 0.5;
  23131. };
  23132. Texture.prototype.getTextureMatrix = function () {
  23133. if (this.uOffset === this._cachedUOffset &&
  23134. this.vOffset === this._cachedVOffset &&
  23135. this.uScale === this._cachedUScale &&
  23136. this.vScale === this._cachedVScale &&
  23137. this.uAng === this._cachedUAng &&
  23138. this.vAng === this._cachedVAng &&
  23139. this.wAng === this._cachedWAng) {
  23140. return this._cachedTextureMatrix;
  23141. }
  23142. this._cachedUOffset = this.uOffset;
  23143. this._cachedVOffset = this.vOffset;
  23144. this._cachedUScale = this.uScale;
  23145. this._cachedVScale = this.vScale;
  23146. this._cachedUAng = this.uAng;
  23147. this._cachedVAng = this.vAng;
  23148. this._cachedWAng = this.wAng;
  23149. if (!this._cachedTextureMatrix) {
  23150. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23151. this._rowGenerationMatrix = new BABYLON.Matrix();
  23152. this._t0 = BABYLON.Vector3.Zero();
  23153. this._t1 = BABYLON.Vector3.Zero();
  23154. this._t2 = BABYLON.Vector3.Zero();
  23155. }
  23156. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23157. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23158. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23159. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23160. this._t1.subtractInPlace(this._t0);
  23161. this._t2.subtractInPlace(this._t0);
  23162. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23163. this._cachedTextureMatrix.m[0] = this._t1.x;
  23164. this._cachedTextureMatrix.m[1] = this._t1.y;
  23165. this._cachedTextureMatrix.m[2] = this._t1.z;
  23166. this._cachedTextureMatrix.m[4] = this._t2.x;
  23167. this._cachedTextureMatrix.m[5] = this._t2.y;
  23168. this._cachedTextureMatrix.m[6] = this._t2.z;
  23169. this._cachedTextureMatrix.m[8] = this._t0.x;
  23170. this._cachedTextureMatrix.m[9] = this._t0.y;
  23171. this._cachedTextureMatrix.m[10] = this._t0.z;
  23172. return this._cachedTextureMatrix;
  23173. };
  23174. Texture.prototype.getReflectionTextureMatrix = function () {
  23175. if (this.uOffset === this._cachedUOffset &&
  23176. this.vOffset === this._cachedVOffset &&
  23177. this.uScale === this._cachedUScale &&
  23178. this.vScale === this._cachedVScale &&
  23179. this.coordinatesMode === this._cachedCoordinatesMode) {
  23180. return this._cachedTextureMatrix;
  23181. }
  23182. if (!this._cachedTextureMatrix) {
  23183. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23184. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23185. }
  23186. this._cachedCoordinatesMode = this.coordinatesMode;
  23187. switch (this.coordinatesMode) {
  23188. case Texture.PLANAR_MODE:
  23189. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23190. this._cachedTextureMatrix[0] = this.uScale;
  23191. this._cachedTextureMatrix[5] = this.vScale;
  23192. this._cachedTextureMatrix[12] = this.uOffset;
  23193. this._cachedTextureMatrix[13] = this.vOffset;
  23194. break;
  23195. case Texture.PROJECTION_MODE:
  23196. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23197. this._projectionModeMatrix.m[0] = 0.5;
  23198. this._projectionModeMatrix.m[5] = -0.5;
  23199. this._projectionModeMatrix.m[10] = 0.0;
  23200. this._projectionModeMatrix.m[12] = 0.5;
  23201. this._projectionModeMatrix.m[13] = 0.5;
  23202. this._projectionModeMatrix.m[14] = 1.0;
  23203. this._projectionModeMatrix.m[15] = 1.0;
  23204. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23205. break;
  23206. default:
  23207. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23208. break;
  23209. }
  23210. return this._cachedTextureMatrix;
  23211. };
  23212. Texture.prototype.clone = function () {
  23213. var _this = this;
  23214. return BABYLON.SerializationHelper.Clone(function () {
  23215. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23216. }, this);
  23217. };
  23218. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23219. get: function () {
  23220. if (!this._onLoadObservarble) {
  23221. this._onLoadObservarble = new BABYLON.Observable();
  23222. }
  23223. return this._onLoadObservarble;
  23224. },
  23225. enumerable: true,
  23226. configurable: true
  23227. });
  23228. // Statics
  23229. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23230. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23231. if (onLoad === void 0) { onLoad = null; }
  23232. if (onError === void 0) { onError = null; }
  23233. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23234. };
  23235. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23236. if (parsedTexture.customType) {
  23237. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23238. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23239. }
  23240. if (parsedTexture.isCube) {
  23241. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23242. }
  23243. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23244. return null;
  23245. }
  23246. var texture = BABYLON.SerializationHelper.Parse(function () {
  23247. if (parsedTexture.mirrorPlane) {
  23248. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23249. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23250. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23251. return mirrorTexture;
  23252. }
  23253. else if (parsedTexture.isRenderTarget) {
  23254. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23255. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23256. return renderTargetTexture;
  23257. }
  23258. else {
  23259. var texture;
  23260. if (parsedTexture.base64String) {
  23261. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23262. }
  23263. else {
  23264. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23265. }
  23266. return texture;
  23267. }
  23268. }, parsedTexture, scene);
  23269. // Animations
  23270. if (parsedTexture.animations) {
  23271. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23272. var parsedAnimation = parsedTexture.animations[animationIndex];
  23273. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23274. }
  23275. }
  23276. return texture;
  23277. };
  23278. // Constants
  23279. Texture.NEAREST_SAMPLINGMODE = 1;
  23280. Texture.BILINEAR_SAMPLINGMODE = 2;
  23281. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23282. Texture.EXPLICIT_MODE = 0;
  23283. Texture.SPHERICAL_MODE = 1;
  23284. Texture.PLANAR_MODE = 2;
  23285. Texture.CUBIC_MODE = 3;
  23286. Texture.PROJECTION_MODE = 4;
  23287. Texture.SKYBOX_MODE = 5;
  23288. Texture.INVCUBIC_MODE = 6;
  23289. Texture.EQUIRECTANGULAR_MODE = 7;
  23290. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23291. Texture.CLAMP_ADDRESSMODE = 0;
  23292. Texture.WRAP_ADDRESSMODE = 1;
  23293. Texture.MIRROR_ADDRESSMODE = 2;
  23294. __decorate([
  23295. BABYLON.serialize()
  23296. ], Texture.prototype, "url", void 0);
  23297. __decorate([
  23298. BABYLON.serialize()
  23299. ], Texture.prototype, "uOffset", void 0);
  23300. __decorate([
  23301. BABYLON.serialize()
  23302. ], Texture.prototype, "vOffset", void 0);
  23303. __decorate([
  23304. BABYLON.serialize()
  23305. ], Texture.prototype, "uScale", void 0);
  23306. __decorate([
  23307. BABYLON.serialize()
  23308. ], Texture.prototype, "vScale", void 0);
  23309. __decorate([
  23310. BABYLON.serialize()
  23311. ], Texture.prototype, "uAng", void 0);
  23312. __decorate([
  23313. BABYLON.serialize()
  23314. ], Texture.prototype, "vAng", void 0);
  23315. __decorate([
  23316. BABYLON.serialize()
  23317. ], Texture.prototype, "wAng", void 0);
  23318. return Texture;
  23319. }(BABYLON.BaseTexture));
  23320. BABYLON.Texture = Texture;
  23321. })(BABYLON || (BABYLON = {}));
  23322. var BABYLON;
  23323. (function (BABYLON) {
  23324. var CubeTexture = (function (_super) {
  23325. __extends(CubeTexture, _super);
  23326. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23327. if (onLoad === void 0) { onLoad = null; }
  23328. if (onError === void 0) { onError = null; }
  23329. _super.call(this, scene);
  23330. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23331. this.name = rootUrl;
  23332. this.url = rootUrl;
  23333. this._noMipmap = noMipmap;
  23334. this.hasAlpha = false;
  23335. if (!rootUrl && !files) {
  23336. return;
  23337. }
  23338. this._texture = this._getFromCache(rootUrl, noMipmap);
  23339. if (!files) {
  23340. if (!extensions) {
  23341. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23342. }
  23343. files = [];
  23344. for (var index = 0; index < extensions.length; index++) {
  23345. files.push(rootUrl + extensions[index]);
  23346. }
  23347. this._extensions = extensions;
  23348. }
  23349. this._files = files;
  23350. if (!this._texture) {
  23351. if (!scene.useDelayedTextureLoading) {
  23352. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23353. }
  23354. else {
  23355. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23356. }
  23357. }
  23358. else if (onLoad) {
  23359. if (this._texture.isReady) {
  23360. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23361. }
  23362. else {
  23363. this._texture.onLoadedCallbacks.push(onLoad);
  23364. }
  23365. }
  23366. this.isCube = true;
  23367. this._textureMatrix = BABYLON.Matrix.Identity();
  23368. }
  23369. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23370. return new CubeTexture("", scene, null, noMipmap, files);
  23371. };
  23372. // Methods
  23373. CubeTexture.prototype.delayLoad = function () {
  23374. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23375. return;
  23376. }
  23377. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23378. this._texture = this._getFromCache(this.url, this._noMipmap);
  23379. if (!this._texture) {
  23380. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23381. }
  23382. };
  23383. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23384. return this._textureMatrix;
  23385. };
  23386. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23387. var texture = BABYLON.SerializationHelper.Parse(function () {
  23388. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23389. }, parsedTexture, scene);
  23390. // Animations
  23391. if (parsedTexture.animations) {
  23392. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23393. var parsedAnimation = parsedTexture.animations[animationIndex];
  23394. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23395. }
  23396. }
  23397. return texture;
  23398. };
  23399. CubeTexture.prototype.clone = function () {
  23400. var _this = this;
  23401. return BABYLON.SerializationHelper.Clone(function () {
  23402. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23403. }, this);
  23404. };
  23405. return CubeTexture;
  23406. }(BABYLON.BaseTexture));
  23407. BABYLON.CubeTexture = CubeTexture;
  23408. })(BABYLON || (BABYLON = {}));
  23409. var BABYLON;
  23410. (function (BABYLON) {
  23411. var RenderTargetTexture = (function (_super) {
  23412. __extends(RenderTargetTexture, _super);
  23413. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23414. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23415. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23416. if (isCube === void 0) { isCube = false; }
  23417. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23418. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23419. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23420. _super.call(this, null, scene, !generateMipMaps);
  23421. this.isCube = isCube;
  23422. /**
  23423. * Use this list to define the list of mesh you want to render.
  23424. */
  23425. this.renderList = new Array();
  23426. this.renderParticles = true;
  23427. this.renderSprites = false;
  23428. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23429. // Events
  23430. /**
  23431. * An event triggered when the texture is unbind.
  23432. * @type {BABYLON.Observable}
  23433. */
  23434. this.onAfterUnbindObservable = new BABYLON.Observable();
  23435. /**
  23436. * An event triggered before rendering the texture
  23437. * @type {BABYLON.Observable}
  23438. */
  23439. this.onBeforeRenderObservable = new BABYLON.Observable();
  23440. /**
  23441. * An event triggered after rendering the texture
  23442. * @type {BABYLON.Observable}
  23443. */
  23444. this.onAfterRenderObservable = new BABYLON.Observable();
  23445. /**
  23446. * An event triggered after the texture clear
  23447. * @type {BABYLON.Observable}
  23448. */
  23449. this.onClearObservable = new BABYLON.Observable();
  23450. this._currentRefreshId = -1;
  23451. this._refreshRate = 1;
  23452. this.name = name;
  23453. this.isRenderTarget = true;
  23454. this._size = size;
  23455. this._generateMipMaps = generateMipMaps;
  23456. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23457. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23458. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23459. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23460. }
  23461. if (isCube) {
  23462. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23463. generateMipMaps: generateMipMaps,
  23464. samplingMode: samplingMode,
  23465. generateDepthBuffer: generateDepthBuffer,
  23466. generateStencilBuffer: generateStencilBuffer
  23467. });
  23468. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23469. this._textureMatrix = BABYLON.Matrix.Identity();
  23470. }
  23471. else {
  23472. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23473. generateMipMaps: generateMipMaps,
  23474. type: type,
  23475. samplingMode: samplingMode,
  23476. generateDepthBuffer: generateDepthBuffer,
  23477. generateStencilBuffer: generateStencilBuffer
  23478. });
  23479. }
  23480. // Rendering groups
  23481. this._renderingManager = new BABYLON.RenderingManager(scene);
  23482. }
  23483. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23484. get: function () {
  23485. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23486. },
  23487. enumerable: true,
  23488. configurable: true
  23489. });
  23490. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23491. get: function () {
  23492. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23493. },
  23494. enumerable: true,
  23495. configurable: true
  23496. });
  23497. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23498. get: function () {
  23499. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23500. },
  23501. enumerable: true,
  23502. configurable: true
  23503. });
  23504. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23505. set: function (callback) {
  23506. if (this._onAfterUnbindObserver) {
  23507. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23508. }
  23509. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23510. },
  23511. enumerable: true,
  23512. configurable: true
  23513. });
  23514. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23515. set: function (callback) {
  23516. if (this._onBeforeRenderObserver) {
  23517. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23518. }
  23519. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23520. },
  23521. enumerable: true,
  23522. configurable: true
  23523. });
  23524. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23525. set: function (callback) {
  23526. if (this._onAfterRenderObserver) {
  23527. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23528. }
  23529. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23530. },
  23531. enumerable: true,
  23532. configurable: true
  23533. });
  23534. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23535. set: function (callback) {
  23536. if (this._onClearObserver) {
  23537. this.onClearObservable.remove(this._onClearObserver);
  23538. }
  23539. this._onClearObserver = this.onClearObservable.add(callback);
  23540. },
  23541. enumerable: true,
  23542. configurable: true
  23543. });
  23544. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23545. this._currentRefreshId = -1;
  23546. };
  23547. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23548. get: function () {
  23549. return this._refreshRate;
  23550. },
  23551. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23552. set: function (value) {
  23553. this._refreshRate = value;
  23554. this.resetRefreshCounter();
  23555. },
  23556. enumerable: true,
  23557. configurable: true
  23558. });
  23559. RenderTargetTexture.prototype._shouldRender = function () {
  23560. if (this._currentRefreshId === -1) {
  23561. this._currentRefreshId = 1;
  23562. return true;
  23563. }
  23564. if (this.refreshRate === this._currentRefreshId) {
  23565. this._currentRefreshId = 1;
  23566. return true;
  23567. }
  23568. this._currentRefreshId++;
  23569. return false;
  23570. };
  23571. RenderTargetTexture.prototype.isReady = function () {
  23572. if (!this.getScene().renderTargetsEnabled) {
  23573. return false;
  23574. }
  23575. return _super.prototype.isReady.call(this);
  23576. };
  23577. RenderTargetTexture.prototype.getRenderSize = function () {
  23578. return this._size;
  23579. };
  23580. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23581. get: function () {
  23582. return true;
  23583. },
  23584. enumerable: true,
  23585. configurable: true
  23586. });
  23587. RenderTargetTexture.prototype.scale = function (ratio) {
  23588. var newSize = this._size * ratio;
  23589. this.resize(newSize, this._generateMipMaps);
  23590. };
  23591. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23592. if (this.isCube) {
  23593. return this._textureMatrix;
  23594. }
  23595. return _super.prototype.getReflectionTextureMatrix.call(this);
  23596. };
  23597. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  23598. this.releaseInternalTexture();
  23599. if (this.isCube) {
  23600. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  23601. }
  23602. else {
  23603. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23604. }
  23605. };
  23606. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  23607. var scene = this.getScene();
  23608. if (this.useCameraPostProcesses !== undefined) {
  23609. useCameraPostProcess = this.useCameraPostProcesses;
  23610. }
  23611. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23612. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  23613. }
  23614. if (this._waitingRenderList) {
  23615. this.renderList = [];
  23616. for (var index = 0; index < this._waitingRenderList.length; index++) {
  23617. var id = this._waitingRenderList[index];
  23618. this.renderList.push(scene.getMeshByID(id));
  23619. }
  23620. delete this._waitingRenderList;
  23621. }
  23622. // Is predicate defined?
  23623. if (this.renderListPredicate) {
  23624. this.renderList.splice(0); // Clear previous renderList
  23625. var sceneMeshes = this.getScene().meshes;
  23626. for (var index = 0; index < sceneMeshes.length; index++) {
  23627. var mesh = sceneMeshes[index];
  23628. if (this.renderListPredicate(mesh)) {
  23629. this.renderList.push(mesh);
  23630. }
  23631. }
  23632. }
  23633. if (this.renderList && this.renderList.length === 0) {
  23634. return;
  23635. }
  23636. // Prepare renderingManager
  23637. this._renderingManager.reset();
  23638. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  23639. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  23640. var sceneRenderId = scene.getRenderId();
  23641. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  23642. var mesh = currentRenderList[meshIndex];
  23643. if (mesh) {
  23644. if (!mesh.isReady()) {
  23645. // Reset _currentRefreshId
  23646. this.resetRefreshCounter();
  23647. continue;
  23648. }
  23649. mesh._preActivateForIntermediateRendering(sceneRenderId);
  23650. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  23651. mesh._activate(sceneRenderId);
  23652. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23653. var subMesh = mesh.subMeshes[subIndex];
  23654. scene._activeIndices.addCount(subMesh.indexCount, false);
  23655. this._renderingManager.dispatch(subMesh);
  23656. }
  23657. }
  23658. }
  23659. }
  23660. if (this.isCube) {
  23661. for (var face = 0; face < 6; face++) {
  23662. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23663. scene.incrementRenderId();
  23664. scene.resetCachedMaterial();
  23665. }
  23666. }
  23667. else {
  23668. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23669. }
  23670. this.onAfterUnbindObservable.notifyObservers(this);
  23671. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23672. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  23673. }
  23674. scene.resetCachedMaterial();
  23675. };
  23676. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  23677. var scene = this.getScene();
  23678. var engine = scene.getEngine();
  23679. // Bind
  23680. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  23681. if (this.isCube) {
  23682. engine.bindFramebuffer(this._texture, faceIndex);
  23683. }
  23684. else {
  23685. engine.bindFramebuffer(this._texture);
  23686. }
  23687. }
  23688. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  23689. // Clear
  23690. if (this.onClearObservable.hasObservers()) {
  23691. this.onClearObservable.notifyObservers(engine);
  23692. }
  23693. else {
  23694. engine.clear(scene.clearColor, true, true, true);
  23695. }
  23696. if (!this._doNotChangeAspectRatio) {
  23697. scene.updateTransformMatrix(true);
  23698. }
  23699. // Render
  23700. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  23701. if (useCameraPostProcess) {
  23702. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  23703. }
  23704. if (!this._doNotChangeAspectRatio) {
  23705. scene.updateTransformMatrix(true);
  23706. }
  23707. this.onAfterRenderObservable.notifyObservers(faceIndex);
  23708. // Dump ?
  23709. if (dumpForDebug) {
  23710. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  23711. }
  23712. // Unbind
  23713. if (!this.isCube || faceIndex === 5) {
  23714. if (this.isCube) {
  23715. if (faceIndex === 5) {
  23716. engine.generateMipMapsForCubemap(this._texture);
  23717. }
  23718. }
  23719. engine.unBindFramebuffer(this._texture, this.isCube);
  23720. }
  23721. };
  23722. /**
  23723. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23724. * This allowed control for front to back rendering or reversly depending of the special needs.
  23725. *
  23726. * @param renderingGroupId The rendering group id corresponding to its index
  23727. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23728. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23729. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23730. */
  23731. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23732. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23733. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23734. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23735. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23736. };
  23737. /**
  23738. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23739. *
  23740. * @param renderingGroupId The rendering group id corresponding to its index
  23741. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23742. */
  23743. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  23744. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  23745. };
  23746. RenderTargetTexture.prototype.clone = function () {
  23747. var textureSize = this.getSize();
  23748. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23749. // Base texture
  23750. newTexture.hasAlpha = this.hasAlpha;
  23751. newTexture.level = this.level;
  23752. // RenderTarget Texture
  23753. newTexture.coordinatesMode = this.coordinatesMode;
  23754. newTexture.renderList = this.renderList.slice(0);
  23755. return newTexture;
  23756. };
  23757. RenderTargetTexture.prototype.serialize = function () {
  23758. if (!this.name) {
  23759. return null;
  23760. }
  23761. var serializationObject = _super.prototype.serialize.call(this);
  23762. serializationObject.renderTargetSize = this.getRenderSize();
  23763. serializationObject.renderList = [];
  23764. for (var index = 0; index < this.renderList.length; index++) {
  23765. serializationObject.renderList.push(this.renderList[index].id);
  23766. }
  23767. return serializationObject;
  23768. };
  23769. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  23770. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  23771. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  23772. return RenderTargetTexture;
  23773. }(BABYLON.Texture));
  23774. BABYLON.RenderTargetTexture = RenderTargetTexture;
  23775. })(BABYLON || (BABYLON = {}));
  23776. var BABYLON;
  23777. (function (BABYLON) {
  23778. var ProceduralTexture = (function (_super) {
  23779. __extends(ProceduralTexture, _super);
  23780. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  23781. if (generateMipMaps === void 0) { generateMipMaps = true; }
  23782. if (isCube === void 0) { isCube = false; }
  23783. _super.call(this, null, scene, !generateMipMaps);
  23784. this.isCube = isCube;
  23785. this.isEnabled = true;
  23786. this._currentRefreshId = -1;
  23787. this._refreshRate = 1;
  23788. this._vertexBuffers = {};
  23789. this._uniforms = new Array();
  23790. this._samplers = new Array();
  23791. this._textures = new Array();
  23792. this._floats = new Array();
  23793. this._floatsArrays = {};
  23794. this._colors3 = new Array();
  23795. this._colors4 = new Array();
  23796. this._vectors2 = new Array();
  23797. this._vectors3 = new Array();
  23798. this._matrices = new Array();
  23799. this._fallbackTextureUsed = false;
  23800. scene._proceduralTextures.push(this);
  23801. this.name = name;
  23802. this.isRenderTarget = true;
  23803. this._size = size;
  23804. this._generateMipMaps = generateMipMaps;
  23805. this.setFragment(fragment);
  23806. this._fallbackTexture = fallbackTexture;
  23807. var engine = scene.getEngine();
  23808. if (isCube) {
  23809. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23810. this.setFloat("face", 0);
  23811. }
  23812. else {
  23813. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23814. }
  23815. // VBO
  23816. var vertices = [];
  23817. vertices.push(1, 1);
  23818. vertices.push(-1, 1);
  23819. vertices.push(-1, -1);
  23820. vertices.push(1, -1);
  23821. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23822. // Indices
  23823. var indices = [];
  23824. indices.push(0);
  23825. indices.push(1);
  23826. indices.push(2);
  23827. indices.push(0);
  23828. indices.push(2);
  23829. indices.push(3);
  23830. this._indexBuffer = engine.createIndexBuffer(indices);
  23831. }
  23832. ProceduralTexture.prototype.reset = function () {
  23833. if (this._effect === undefined) {
  23834. return;
  23835. }
  23836. var engine = this.getScene().getEngine();
  23837. engine._releaseEffect(this._effect);
  23838. };
  23839. ProceduralTexture.prototype.isReady = function () {
  23840. var _this = this;
  23841. var engine = this.getScene().getEngine();
  23842. var shaders;
  23843. if (!this._fragment) {
  23844. return false;
  23845. }
  23846. if (this._fallbackTextureUsed) {
  23847. return true;
  23848. }
  23849. if (this._fragment.fragmentElement !== undefined) {
  23850. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23851. }
  23852. else {
  23853. shaders = { vertex: "procedural", fragment: this._fragment };
  23854. }
  23855. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23856. _this.releaseInternalTexture();
  23857. if (_this._fallbackTexture) {
  23858. _this._texture = _this._fallbackTexture._texture;
  23859. _this._texture.references++;
  23860. }
  23861. _this._fallbackTextureUsed = true;
  23862. });
  23863. return this._effect.isReady();
  23864. };
  23865. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23866. this._currentRefreshId = -1;
  23867. };
  23868. ProceduralTexture.prototype.setFragment = function (fragment) {
  23869. this._fragment = fragment;
  23870. };
  23871. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23872. get: function () {
  23873. return this._refreshRate;
  23874. },
  23875. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23876. set: function (value) {
  23877. this._refreshRate = value;
  23878. this.resetRefreshCounter();
  23879. },
  23880. enumerable: true,
  23881. configurable: true
  23882. });
  23883. ProceduralTexture.prototype._shouldRender = function () {
  23884. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23885. return false;
  23886. }
  23887. if (this._fallbackTextureUsed) {
  23888. return false;
  23889. }
  23890. if (this._currentRefreshId === -1) {
  23891. this._currentRefreshId = 1;
  23892. return true;
  23893. }
  23894. if (this.refreshRate === this._currentRefreshId) {
  23895. this._currentRefreshId = 1;
  23896. return true;
  23897. }
  23898. this._currentRefreshId++;
  23899. return false;
  23900. };
  23901. ProceduralTexture.prototype.getRenderSize = function () {
  23902. return this._size;
  23903. };
  23904. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23905. if (this._fallbackTextureUsed) {
  23906. return;
  23907. }
  23908. this.releaseInternalTexture();
  23909. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23910. };
  23911. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23912. if (this._uniforms.indexOf(uniformName) === -1) {
  23913. this._uniforms.push(uniformName);
  23914. }
  23915. };
  23916. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23917. if (this._samplers.indexOf(name) === -1) {
  23918. this._samplers.push(name);
  23919. }
  23920. this._textures[name] = texture;
  23921. return this;
  23922. };
  23923. ProceduralTexture.prototype.setFloat = function (name, value) {
  23924. this._checkUniform(name);
  23925. this._floats[name] = value;
  23926. return this;
  23927. };
  23928. ProceduralTexture.prototype.setFloats = function (name, value) {
  23929. this._checkUniform(name);
  23930. this._floatsArrays[name] = value;
  23931. return this;
  23932. };
  23933. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23934. this._checkUniform(name);
  23935. this._colors3[name] = value;
  23936. return this;
  23937. };
  23938. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23939. this._checkUniform(name);
  23940. this._colors4[name] = value;
  23941. return this;
  23942. };
  23943. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23944. this._checkUniform(name);
  23945. this._vectors2[name] = value;
  23946. return this;
  23947. };
  23948. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23949. this._checkUniform(name);
  23950. this._vectors3[name] = value;
  23951. return this;
  23952. };
  23953. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23954. this._checkUniform(name);
  23955. this._matrices[name] = value;
  23956. return this;
  23957. };
  23958. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23959. var scene = this.getScene();
  23960. var engine = scene.getEngine();
  23961. // Render
  23962. engine.enableEffect(this._effect);
  23963. engine.setState(false);
  23964. // Texture
  23965. for (var name in this._textures) {
  23966. this._effect.setTexture(name, this._textures[name]);
  23967. }
  23968. // Float
  23969. for (name in this._floats) {
  23970. this._effect.setFloat(name, this._floats[name]);
  23971. }
  23972. // Floats
  23973. for (name in this._floatsArrays) {
  23974. this._effect.setArray(name, this._floatsArrays[name]);
  23975. }
  23976. // Color3
  23977. for (name in this._colors3) {
  23978. this._effect.setColor3(name, this._colors3[name]);
  23979. }
  23980. // Color4
  23981. for (name in this._colors4) {
  23982. var color = this._colors4[name];
  23983. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23984. }
  23985. // Vector2
  23986. for (name in this._vectors2) {
  23987. this._effect.setVector2(name, this._vectors2[name]);
  23988. }
  23989. // Vector3
  23990. for (name in this._vectors3) {
  23991. this._effect.setVector3(name, this._vectors3[name]);
  23992. }
  23993. // Matrix
  23994. for (name in this._matrices) {
  23995. this._effect.setMatrix(name, this._matrices[name]);
  23996. }
  23997. // VBOs
  23998. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23999. if (this.isCube) {
  24000. for (var face = 0; face < 6; face++) {
  24001. engine.bindFramebuffer(this._texture, face);
  24002. this._effect.setFloat("face", face);
  24003. // Clear
  24004. engine.clear(scene.clearColor, true, true, true);
  24005. // Draw order
  24006. engine.draw(true, 0, 6);
  24007. // Mipmaps
  24008. if (face === 5) {
  24009. engine.generateMipMapsForCubemap(this._texture);
  24010. }
  24011. }
  24012. }
  24013. else {
  24014. engine.bindFramebuffer(this._texture);
  24015. // Clear
  24016. engine.clear(scene.clearColor, true, true, true);
  24017. // Draw order
  24018. engine.draw(true, 0, 6);
  24019. }
  24020. // Unbind
  24021. engine.unBindFramebuffer(this._texture, this.isCube);
  24022. if (this.onGenerated) {
  24023. this.onGenerated();
  24024. }
  24025. };
  24026. ProceduralTexture.prototype.clone = function () {
  24027. var textureSize = this.getSize();
  24028. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  24029. // Base texture
  24030. newTexture.hasAlpha = this.hasAlpha;
  24031. newTexture.level = this.level;
  24032. // RenderTarget Texture
  24033. newTexture.coordinatesMode = this.coordinatesMode;
  24034. return newTexture;
  24035. };
  24036. ProceduralTexture.prototype.dispose = function () {
  24037. var index = this.getScene()._proceduralTextures.indexOf(this);
  24038. if (index >= 0) {
  24039. this.getScene()._proceduralTextures.splice(index, 1);
  24040. }
  24041. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  24042. if (vertexBuffer) {
  24043. vertexBuffer.dispose();
  24044. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  24045. }
  24046. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  24047. this._indexBuffer = null;
  24048. }
  24049. _super.prototype.dispose.call(this);
  24050. };
  24051. return ProceduralTexture;
  24052. }(BABYLON.Texture));
  24053. BABYLON.ProceduralTexture = ProceduralTexture;
  24054. })(BABYLON || (BABYLON = {}));
  24055. var BABYLON;
  24056. (function (BABYLON) {
  24057. var MirrorTexture = (function (_super) {
  24058. __extends(MirrorTexture, _super);
  24059. function MirrorTexture(name, size, scene, generateMipMaps) {
  24060. var _this = this;
  24061. _super.call(this, name, size, scene, generateMipMaps, true);
  24062. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24063. this._transformMatrix = BABYLON.Matrix.Zero();
  24064. this._mirrorMatrix = BABYLON.Matrix.Zero();
  24065. this.onBeforeRenderObservable.add(function () {
  24066. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24067. _this._savedViewMatrix = scene.getViewMatrix();
  24068. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24069. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24070. scene.clipPlane = _this.mirrorPlane;
  24071. scene.getEngine().cullBackFaces = false;
  24072. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24073. });
  24074. this.onAfterRenderObservable.add(function () {
  24075. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24076. scene.getEngine().cullBackFaces = true;
  24077. scene._mirroredCameraPosition = null;
  24078. delete scene.clipPlane;
  24079. });
  24080. }
  24081. MirrorTexture.prototype.clone = function () {
  24082. var textureSize = this.getSize();
  24083. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24084. // Base texture
  24085. newTexture.hasAlpha = this.hasAlpha;
  24086. newTexture.level = this.level;
  24087. // Mirror Texture
  24088. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24089. newTexture.renderList = this.renderList.slice(0);
  24090. return newTexture;
  24091. };
  24092. MirrorTexture.prototype.serialize = function () {
  24093. if (!this.name) {
  24094. return null;
  24095. }
  24096. var serializationObject = _super.prototype.serialize.call(this);
  24097. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24098. return serializationObject;
  24099. };
  24100. return MirrorTexture;
  24101. }(BABYLON.RenderTargetTexture));
  24102. BABYLON.MirrorTexture = MirrorTexture;
  24103. })(BABYLON || (BABYLON = {}));
  24104. var BABYLON;
  24105. (function (BABYLON) {
  24106. /**
  24107. * Creates a refraction texture used by refraction channel of the standard material.
  24108. * @param name the texture name
  24109. * @param size size of the underlying texture
  24110. * @param scene root scene
  24111. */
  24112. var RefractionTexture = (function (_super) {
  24113. __extends(RefractionTexture, _super);
  24114. function RefractionTexture(name, size, scene, generateMipMaps) {
  24115. var _this = this;
  24116. _super.call(this, name, size, scene, generateMipMaps, true);
  24117. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24118. this.depth = 2.0;
  24119. this.onBeforeRenderObservable.add(function () {
  24120. scene.clipPlane = _this.refractionPlane;
  24121. });
  24122. this.onAfterRenderObservable.add(function () {
  24123. delete scene.clipPlane;
  24124. });
  24125. }
  24126. RefractionTexture.prototype.clone = function () {
  24127. var textureSize = this.getSize();
  24128. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24129. // Base texture
  24130. newTexture.hasAlpha = this.hasAlpha;
  24131. newTexture.level = this.level;
  24132. // Refraction Texture
  24133. newTexture.refractionPlane = this.refractionPlane.clone();
  24134. newTexture.renderList = this.renderList.slice(0);
  24135. newTexture.depth = this.depth;
  24136. return newTexture;
  24137. };
  24138. RefractionTexture.prototype.serialize = function () {
  24139. if (!this.name) {
  24140. return null;
  24141. }
  24142. var serializationObject = _super.prototype.serialize.call(this);
  24143. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24144. serializationObject.depth = this.depth;
  24145. return serializationObject;
  24146. };
  24147. return RefractionTexture;
  24148. }(BABYLON.RenderTargetTexture));
  24149. BABYLON.RefractionTexture = RefractionTexture;
  24150. })(BABYLON || (BABYLON = {}));
  24151. var BABYLON;
  24152. (function (BABYLON) {
  24153. var DynamicTexture = (function (_super) {
  24154. __extends(DynamicTexture, _super);
  24155. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24156. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24157. _super.call(this, null, scene, !generateMipMaps);
  24158. this.name = name;
  24159. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24160. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24161. this._generateMipMaps = generateMipMaps;
  24162. if (options.getContext) {
  24163. this._canvas = options;
  24164. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24165. }
  24166. else {
  24167. this._canvas = document.createElement("canvas");
  24168. if (options.width) {
  24169. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24170. }
  24171. else {
  24172. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24173. }
  24174. }
  24175. var textureSize = this.getSize();
  24176. this._canvas.width = textureSize.width;
  24177. this._canvas.height = textureSize.height;
  24178. this._context = this._canvas.getContext("2d");
  24179. }
  24180. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24181. get: function () {
  24182. return true;
  24183. },
  24184. enumerable: true,
  24185. configurable: true
  24186. });
  24187. DynamicTexture.prototype.scale = function (ratio) {
  24188. var textureSize = this.getSize();
  24189. textureSize.width *= ratio;
  24190. textureSize.height *= ratio;
  24191. this._canvas.width = textureSize.width;
  24192. this._canvas.height = textureSize.height;
  24193. this.releaseInternalTexture();
  24194. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24195. };
  24196. DynamicTexture.prototype.getContext = function () {
  24197. return this._context;
  24198. };
  24199. DynamicTexture.prototype.clear = function () {
  24200. var size = this.getSize();
  24201. this._context.fillRect(0, 0, size.width, size.height);
  24202. };
  24203. DynamicTexture.prototype.update = function (invertY) {
  24204. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24205. };
  24206. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24207. if (update === void 0) { update = true; }
  24208. var size = this.getSize();
  24209. if (clearColor) {
  24210. this._context.fillStyle = clearColor;
  24211. this._context.fillRect(0, 0, size.width, size.height);
  24212. }
  24213. this._context.font = font;
  24214. if (x === null) {
  24215. var textSize = this._context.measureText(text);
  24216. x = (size.width - textSize.width) / 2;
  24217. }
  24218. this._context.fillStyle = color;
  24219. this._context.fillText(text, x, y);
  24220. if (update) {
  24221. this.update(invertY);
  24222. }
  24223. };
  24224. DynamicTexture.prototype.clone = function () {
  24225. var textureSize = this.getSize();
  24226. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24227. // Base texture
  24228. newTexture.hasAlpha = this.hasAlpha;
  24229. newTexture.level = this.level;
  24230. // Dynamic Texture
  24231. newTexture.wrapU = this.wrapU;
  24232. newTexture.wrapV = this.wrapV;
  24233. return newTexture;
  24234. };
  24235. return DynamicTexture;
  24236. }(BABYLON.Texture));
  24237. BABYLON.DynamicTexture = DynamicTexture;
  24238. })(BABYLON || (BABYLON = {}));
  24239. var BABYLON;
  24240. (function (BABYLON) {
  24241. var VideoTexture = (function (_super) {
  24242. __extends(VideoTexture, _super);
  24243. /**
  24244. * Creates a video texture.
  24245. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24246. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24247. * @param {BABYLON.Scene} scene is obviously the current scene.
  24248. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24249. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24250. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24251. */
  24252. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24253. var _this = this;
  24254. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24255. if (invertY === void 0) { invertY = false; }
  24256. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24257. _super.call(this, null, scene, !generateMipMaps, invertY);
  24258. this._autoLaunch = true;
  24259. var urls;
  24260. this.name = name;
  24261. if (urlsOrVideo instanceof HTMLVideoElement) {
  24262. this.video = urlsOrVideo;
  24263. }
  24264. else {
  24265. urls = urlsOrVideo;
  24266. this.video = document.createElement("video");
  24267. this.video.autoplay = false;
  24268. this.video.loop = true;
  24269. }
  24270. this._generateMipMaps = generateMipMaps;
  24271. this._samplingMode = samplingMode;
  24272. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  24273. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24274. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24275. }
  24276. else {
  24277. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24278. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24279. this._generateMipMaps = false;
  24280. }
  24281. if (urls) {
  24282. this.video.addEventListener("canplaythrough", function () {
  24283. _this._createTexture();
  24284. });
  24285. urls.forEach(function (url) {
  24286. var source = document.createElement("source");
  24287. source.src = url;
  24288. _this.video.appendChild(source);
  24289. });
  24290. }
  24291. else {
  24292. this._createTexture();
  24293. }
  24294. this._lastUpdate = BABYLON.Tools.Now;
  24295. }
  24296. VideoTexture.prototype._createTexture = function () {
  24297. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24298. this._texture.isReady = true;
  24299. };
  24300. VideoTexture.prototype.update = function () {
  24301. if (this._autoLaunch) {
  24302. this._autoLaunch = false;
  24303. this.video.play();
  24304. }
  24305. var now = BABYLON.Tools.Now;
  24306. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24307. return false;
  24308. }
  24309. this._lastUpdate = now;
  24310. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24311. return true;
  24312. };
  24313. return VideoTexture;
  24314. }(BABYLON.Texture));
  24315. BABYLON.VideoTexture = VideoTexture;
  24316. })(BABYLON || (BABYLON = {}));
  24317. var BABYLON;
  24318. (function (BABYLON) {
  24319. var CustomProceduralTexture = (function (_super) {
  24320. __extends(CustomProceduralTexture, _super);
  24321. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24322. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  24323. this._animate = true;
  24324. this._time = 0;
  24325. this._texturePath = texturePath;
  24326. //Try to load json
  24327. this.loadJson(texturePath);
  24328. this.refreshRate = 1;
  24329. }
  24330. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24331. var _this = this;
  24332. var that = this;
  24333. function noConfigFile() {
  24334. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24335. try {
  24336. that.setFragment(that._texturePath);
  24337. }
  24338. catch (ex) {
  24339. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24340. }
  24341. }
  24342. var configFileUrl = jsonUrl + "/config.json";
  24343. var xhr = new XMLHttpRequest();
  24344. xhr.open("GET", configFileUrl, true);
  24345. xhr.addEventListener("load", function () {
  24346. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24347. try {
  24348. _this._config = JSON.parse(xhr.response);
  24349. _this.updateShaderUniforms();
  24350. _this.updateTextures();
  24351. _this.setFragment(_this._texturePath + "/custom");
  24352. _this._animate = _this._config.animate;
  24353. _this.refreshRate = _this._config.refreshrate;
  24354. }
  24355. catch (ex) {
  24356. noConfigFile();
  24357. }
  24358. }
  24359. else {
  24360. noConfigFile();
  24361. }
  24362. }, false);
  24363. xhr.addEventListener("error", function () {
  24364. noConfigFile();
  24365. }, false);
  24366. try {
  24367. xhr.send();
  24368. }
  24369. catch (ex) {
  24370. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24371. }
  24372. };
  24373. CustomProceduralTexture.prototype.isReady = function () {
  24374. if (!_super.prototype.isReady.call(this)) {
  24375. return false;
  24376. }
  24377. for (var name in this._textures) {
  24378. var texture = this._textures[name];
  24379. if (!texture.isReady()) {
  24380. return false;
  24381. }
  24382. }
  24383. return true;
  24384. };
  24385. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24386. if (this._animate) {
  24387. this._time += this.getScene().getAnimationRatio() * 0.03;
  24388. this.updateShaderUniforms();
  24389. }
  24390. _super.prototype.render.call(this, useCameraPostProcess);
  24391. };
  24392. CustomProceduralTexture.prototype.updateTextures = function () {
  24393. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24394. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24395. }
  24396. };
  24397. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24398. if (this._config) {
  24399. for (var j = 0; j < this._config.uniforms.length; j++) {
  24400. var uniform = this._config.uniforms[j];
  24401. switch (uniform.type) {
  24402. case "float":
  24403. this.setFloat(uniform.name, uniform.value);
  24404. break;
  24405. case "color3":
  24406. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24407. break;
  24408. case "color4":
  24409. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24410. break;
  24411. case "vector2":
  24412. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24413. break;
  24414. case "vector3":
  24415. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24416. break;
  24417. }
  24418. }
  24419. }
  24420. this.setFloat("time", this._time);
  24421. };
  24422. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24423. get: function () {
  24424. return this._animate;
  24425. },
  24426. set: function (value) {
  24427. this._animate = value;
  24428. },
  24429. enumerable: true,
  24430. configurable: true
  24431. });
  24432. return CustomProceduralTexture;
  24433. }(BABYLON.ProceduralTexture));
  24434. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24435. })(BABYLON || (BABYLON = {}));
  24436. var BABYLON;
  24437. (function (BABYLON) {
  24438. var EffectFallbacks = (function () {
  24439. function EffectFallbacks() {
  24440. this._defines = {};
  24441. this._currentRank = 32;
  24442. this._maxRank = -1;
  24443. }
  24444. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24445. if (!this._defines[rank]) {
  24446. if (rank < this._currentRank) {
  24447. this._currentRank = rank;
  24448. }
  24449. if (rank > this._maxRank) {
  24450. this._maxRank = rank;
  24451. }
  24452. this._defines[rank] = new Array();
  24453. }
  24454. this._defines[rank].push(define);
  24455. };
  24456. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24457. this._meshRank = rank;
  24458. this._mesh = mesh;
  24459. if (rank > this._maxRank) {
  24460. this._maxRank = rank;
  24461. }
  24462. };
  24463. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24464. get: function () {
  24465. return this._currentRank <= this._maxRank;
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24471. var currentFallbacks = this._defines[this._currentRank];
  24472. for (var index = 0; index < currentFallbacks.length; index++) {
  24473. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24474. }
  24475. if (this._mesh && this._currentRank === this._meshRank) {
  24476. this._mesh.computeBonesUsingShaders = false;
  24477. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24478. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24479. }
  24480. this._currentRank++;
  24481. return currentDefines;
  24482. };
  24483. return EffectFallbacks;
  24484. }());
  24485. BABYLON.EffectFallbacks = EffectFallbacks;
  24486. var Effect = (function () {
  24487. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24488. var _this = this;
  24489. this._isReady = false;
  24490. this._compilationError = "";
  24491. this._valueCache = {};
  24492. this._engine = engine;
  24493. this.name = baseName;
  24494. this.defines = defines;
  24495. this._uniformsNames = uniformsNames.concat(samplers);
  24496. this._samplers = samplers;
  24497. this._attributesNames = attributesNames;
  24498. this.onError = onError;
  24499. this.onCompiled = onCompiled;
  24500. this._indexParameters = indexParameters;
  24501. var vertexSource;
  24502. var fragmentSource;
  24503. if (baseName.vertexElement) {
  24504. vertexSource = document.getElementById(baseName.vertexElement);
  24505. if (!vertexSource) {
  24506. vertexSource = baseName.vertexElement;
  24507. }
  24508. }
  24509. else {
  24510. vertexSource = baseName.vertex || baseName;
  24511. }
  24512. if (baseName.fragmentElement) {
  24513. fragmentSource = document.getElementById(baseName.fragmentElement);
  24514. if (!fragmentSource) {
  24515. fragmentSource = baseName.fragmentElement;
  24516. }
  24517. }
  24518. else {
  24519. fragmentSource = baseName.fragment || baseName;
  24520. }
  24521. this._loadVertexShader(vertexSource, function (vertexCode) {
  24522. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24523. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24524. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24525. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24526. });
  24527. });
  24528. });
  24529. });
  24530. }
  24531. // Properties
  24532. Effect.prototype.isReady = function () {
  24533. return this._isReady;
  24534. };
  24535. Effect.prototype.getProgram = function () {
  24536. return this._program;
  24537. };
  24538. Effect.prototype.getAttributesNames = function () {
  24539. return this._attributesNames;
  24540. };
  24541. Effect.prototype.getAttributeLocation = function (index) {
  24542. return this._attributes[index];
  24543. };
  24544. Effect.prototype.getAttributeLocationByName = function (name) {
  24545. var index = this._attributesNames.indexOf(name);
  24546. return this._attributes[index];
  24547. };
  24548. Effect.prototype.getAttributesCount = function () {
  24549. return this._attributes.length;
  24550. };
  24551. Effect.prototype.getUniformIndex = function (uniformName) {
  24552. return this._uniformsNames.indexOf(uniformName);
  24553. };
  24554. Effect.prototype.getUniform = function (uniformName) {
  24555. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24556. };
  24557. Effect.prototype.getSamplers = function () {
  24558. return this._samplers;
  24559. };
  24560. Effect.prototype.getCompilationError = function () {
  24561. return this._compilationError;
  24562. };
  24563. // Methods
  24564. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24565. // DOM element ?
  24566. if (vertex instanceof HTMLElement) {
  24567. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24568. callback(vertexCode);
  24569. return;
  24570. }
  24571. // Base64 encoded ?
  24572. if (vertex.substr(0, 7) === "base64:") {
  24573. var vertexBinary = window.atob(vertex.substr(7));
  24574. callback(vertexBinary);
  24575. return;
  24576. }
  24577. // Is in local store ?
  24578. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24579. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24580. return;
  24581. }
  24582. var vertexShaderUrl;
  24583. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24584. vertexShaderUrl = vertex;
  24585. }
  24586. else {
  24587. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24588. }
  24589. // Vertex shader
  24590. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24591. };
  24592. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24593. // DOM element ?
  24594. if (fragment instanceof HTMLElement) {
  24595. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24596. callback(fragmentCode);
  24597. return;
  24598. }
  24599. // Base64 encoded ?
  24600. if (fragment.substr(0, 7) === "base64:") {
  24601. var fragmentBinary = window.atob(fragment.substr(7));
  24602. callback(fragmentBinary);
  24603. return;
  24604. }
  24605. // Is in local store ?
  24606. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24607. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24608. return;
  24609. }
  24610. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24611. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24612. return;
  24613. }
  24614. var fragmentShaderUrl;
  24615. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24616. fragmentShaderUrl = fragment;
  24617. }
  24618. else {
  24619. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24620. }
  24621. // Fragment shader
  24622. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24623. };
  24624. Effect.prototype._dumpShadersName = function () {
  24625. if (this.name.vertexElement) {
  24626. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  24627. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  24628. }
  24629. else if (this.name.vertex) {
  24630. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  24631. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  24632. }
  24633. else {
  24634. BABYLON.Tools.Error("Vertex shader:" + this.name);
  24635. BABYLON.Tools.Error("Fragment shader:" + this.name);
  24636. }
  24637. };
  24638. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24639. var _this = this;
  24640. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24641. var match = regex.exec(sourceCode);
  24642. var returnValue = new String(sourceCode);
  24643. while (match != null) {
  24644. var includeFile = match[1];
  24645. if (Effect.IncludesShadersStore[includeFile]) {
  24646. // Substitution
  24647. var includeContent = Effect.IncludesShadersStore[includeFile];
  24648. if (match[2]) {
  24649. var splits = match[3].split(",");
  24650. for (var index = 0; index < splits.length; index += 2) {
  24651. var source = new RegExp(splits[index], "g");
  24652. var dest = splits[index + 1];
  24653. includeContent = includeContent.replace(source, dest);
  24654. }
  24655. }
  24656. if (match[4]) {
  24657. var indexString = match[5];
  24658. if (indexString.indexOf("..") !== -1) {
  24659. var indexSplits = indexString.split("..");
  24660. var minIndex = parseInt(indexSplits[0]);
  24661. var maxIndex = parseInt(indexSplits[1]);
  24662. var sourceIncludeContent = includeContent.slice(0);
  24663. includeContent = "";
  24664. if (isNaN(maxIndex)) {
  24665. maxIndex = this._indexParameters[indexSplits[1]];
  24666. }
  24667. for (var i = minIndex; i <= maxIndex; i++) {
  24668. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24669. }
  24670. }
  24671. else {
  24672. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24673. }
  24674. }
  24675. // Replace
  24676. returnValue = returnValue.replace(match[0], includeContent);
  24677. }
  24678. else {
  24679. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24680. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24681. Effect.IncludesShadersStore[includeFile] = fileContent;
  24682. _this._processIncludes(returnValue, callback);
  24683. });
  24684. return;
  24685. }
  24686. match = regex.exec(sourceCode);
  24687. }
  24688. callback(returnValue);
  24689. };
  24690. Effect.prototype._processPrecision = function (source) {
  24691. if (source.indexOf("precision highp float") === -1) {
  24692. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24693. source = "precision mediump float;\n" + source;
  24694. }
  24695. else {
  24696. source = "precision highp float;\n" + source;
  24697. }
  24698. }
  24699. else {
  24700. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24701. source = source.replace("precision highp float", "precision mediump float");
  24702. }
  24703. }
  24704. return source;
  24705. };
  24706. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  24707. try {
  24708. var engine = this._engine;
  24709. // Precision
  24710. vertexSourceCode = this._processPrecision(vertexSourceCode);
  24711. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  24712. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  24713. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24714. this._attributes = engine.getAttributes(this._program, attributesNames);
  24715. var index;
  24716. for (index = 0; index < this._samplers.length; index++) {
  24717. var sampler = this.getUniform(this._samplers[index]);
  24718. if (sampler == null) {
  24719. this._samplers.splice(index, 1);
  24720. index--;
  24721. }
  24722. }
  24723. engine.bindSamplers(this);
  24724. this._compilationError = "";
  24725. this._isReady = true;
  24726. if (this.onCompiled) {
  24727. this.onCompiled(this);
  24728. }
  24729. }
  24730. catch (e) {
  24731. this._compilationError = e.message;
  24732. // Let's go through fallbacks then
  24733. BABYLON.Tools.Error("Unable to compile effect: ");
  24734. BABYLON.Tools.Error("Defines: " + defines);
  24735. BABYLON.Tools.Error("Error: " + this._compilationError);
  24736. this._dumpShadersName();
  24737. if (fallbacks && fallbacks.isMoreFallbacks) {
  24738. BABYLON.Tools.Error("Trying next fallback.");
  24739. defines = fallbacks.reduce(defines);
  24740. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  24741. }
  24742. else {
  24743. if (this.onError) {
  24744. this.onError(this, this._compilationError);
  24745. }
  24746. }
  24747. }
  24748. };
  24749. Object.defineProperty(Effect.prototype, "isSupported", {
  24750. get: function () {
  24751. return this._compilationError === "";
  24752. },
  24753. enumerable: true,
  24754. configurable: true
  24755. });
  24756. Effect.prototype._bindTexture = function (channel, texture) {
  24757. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24758. };
  24759. Effect.prototype.setTexture = function (channel, texture) {
  24760. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24761. };
  24762. Effect.prototype.setTextureArray = function (channel, textures) {
  24763. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24764. var initialPos = this._samplers.indexOf(channel);
  24765. for (var index = 1; index < textures.length; index++) {
  24766. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24767. }
  24768. }
  24769. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24770. };
  24771. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24772. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24773. };
  24774. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24775. var changed = false;
  24776. var cache = this._valueCache[uniformName];
  24777. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  24778. changed = true;
  24779. cache = new BABYLON.Matrix();
  24780. }
  24781. var tm = cache.m;
  24782. var om = matrix.m;
  24783. for (var index = 0; index < 16; index++) {
  24784. if (tm[index] !== om[index]) {
  24785. tm[index] = om[index];
  24786. changed = true;
  24787. }
  24788. }
  24789. this._valueCache[uniformName] = cache;
  24790. return changed;
  24791. };
  24792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24793. var cache = this._valueCache[uniformName];
  24794. if (!cache) {
  24795. cache = [x, y];
  24796. this._valueCache[uniformName] = cache;
  24797. return true;
  24798. }
  24799. var changed = false;
  24800. if (cache[0] !== x) {
  24801. cache[0] = x;
  24802. changed = true;
  24803. }
  24804. if (cache[1] !== y) {
  24805. cache[1] = y;
  24806. changed = true;
  24807. }
  24808. return changed;
  24809. };
  24810. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24811. var cache = this._valueCache[uniformName];
  24812. if (!cache) {
  24813. cache = [x, y, z];
  24814. this._valueCache[uniformName] = cache;
  24815. return true;
  24816. }
  24817. var changed = false;
  24818. if (cache[0] !== x) {
  24819. cache[0] = x;
  24820. changed = true;
  24821. }
  24822. if (cache[1] !== y) {
  24823. cache[1] = y;
  24824. changed = true;
  24825. }
  24826. if (cache[2] !== z) {
  24827. cache[2] = z;
  24828. changed = true;
  24829. }
  24830. return changed;
  24831. };
  24832. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24833. var cache = this._valueCache[uniformName];
  24834. if (!cache) {
  24835. cache = [x, y, z, w];
  24836. this._valueCache[uniformName] = cache;
  24837. return true;
  24838. }
  24839. var changed = false;
  24840. if (cache[0] !== x) {
  24841. cache[0] = x;
  24842. changed = true;
  24843. }
  24844. if (cache[1] !== y) {
  24845. cache[1] = y;
  24846. changed = true;
  24847. }
  24848. if (cache[2] !== z) {
  24849. cache[2] = z;
  24850. changed = true;
  24851. }
  24852. if (cache[3] !== w) {
  24853. cache[3] = w;
  24854. changed = true;
  24855. }
  24856. return changed;
  24857. };
  24858. Effect.prototype.setIntArray = function (uniformName, array) {
  24859. this._valueCache[uniformName] = null;
  24860. this._engine.setIntArray(this.getUniform(uniformName), array);
  24861. return this;
  24862. };
  24863. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24864. this._valueCache[uniformName] = null;
  24865. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24866. return this;
  24867. };
  24868. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24869. this._valueCache[uniformName] = null;
  24870. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24871. return this;
  24872. };
  24873. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24874. this._valueCache[uniformName] = null;
  24875. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24876. return this;
  24877. };
  24878. Effect.prototype.setFloatArray = function (uniformName, array) {
  24879. this._valueCache[uniformName] = null;
  24880. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24881. return this;
  24882. };
  24883. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24884. this._valueCache[uniformName] = null;
  24885. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24886. return this;
  24887. };
  24888. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24889. this._valueCache[uniformName] = null;
  24890. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24891. return this;
  24892. };
  24893. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24894. this._valueCache[uniformName] = null;
  24895. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24896. return this;
  24897. };
  24898. Effect.prototype.setArray = function (uniformName, array) {
  24899. this._valueCache[uniformName] = null;
  24900. this._engine.setArray(this.getUniform(uniformName), array);
  24901. return this;
  24902. };
  24903. Effect.prototype.setArray2 = function (uniformName, array) {
  24904. this._valueCache[uniformName] = null;
  24905. this._engine.setArray2(this.getUniform(uniformName), array);
  24906. return this;
  24907. };
  24908. Effect.prototype.setArray3 = function (uniformName, array) {
  24909. this._valueCache[uniformName] = null;
  24910. this._engine.setArray3(this.getUniform(uniformName), array);
  24911. return this;
  24912. };
  24913. Effect.prototype.setArray4 = function (uniformName, array) {
  24914. this._valueCache[uniformName] = null;
  24915. this._engine.setArray4(this.getUniform(uniformName), array);
  24916. return this;
  24917. };
  24918. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24919. this._valueCache[uniformName] = null;
  24920. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24921. return this;
  24922. };
  24923. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24924. if (this._cacheMatrix(uniformName, matrix)) {
  24925. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24926. }
  24927. return this;
  24928. };
  24929. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24930. this._valueCache[uniformName] = null;
  24931. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24932. return this;
  24933. };
  24934. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24935. this._valueCache[uniformName] = null;
  24936. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24937. return this;
  24938. };
  24939. Effect.prototype.setFloat = function (uniformName, value) {
  24940. var cache = this._valueCache[uniformName];
  24941. if (cache !== undefined && cache === value)
  24942. return this;
  24943. this._valueCache[uniformName] = value;
  24944. this._engine.setFloat(this.getUniform(uniformName), value);
  24945. return this;
  24946. };
  24947. Effect.prototype.setBool = function (uniformName, bool) {
  24948. var cache = this._valueCache[uniformName];
  24949. if (cache !== undefined && cache === bool)
  24950. return this;
  24951. this._valueCache[uniformName] = bool;
  24952. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24953. return this;
  24954. };
  24955. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24956. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24957. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24958. }
  24959. return this;
  24960. };
  24961. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24962. if (this._cacheFloat2(uniformName, x, y)) {
  24963. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24964. }
  24965. return this;
  24966. };
  24967. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24968. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24969. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24970. }
  24971. return this;
  24972. };
  24973. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24974. if (this._cacheFloat3(uniformName, x, y, z)) {
  24975. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24976. }
  24977. return this;
  24978. };
  24979. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24980. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24981. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24982. }
  24983. return this;
  24984. };
  24985. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24986. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24987. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24988. }
  24989. return this;
  24990. };
  24991. Effect.prototype.setColor3 = function (uniformName, color3) {
  24992. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24993. this._engine.setColor3(this.getUniform(uniformName), color3);
  24994. }
  24995. return this;
  24996. };
  24997. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24998. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24999. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25000. }
  25001. return this;
  25002. };
  25003. // Statics
  25004. Effect.ShadersStore = {};
  25005. Effect.IncludesShadersStore = {};
  25006. return Effect;
  25007. }());
  25008. BABYLON.Effect = Effect;
  25009. })(BABYLON || (BABYLON = {}));
  25010. var BABYLON;
  25011. (function (BABYLON) {
  25012. var MaterialHelper = (function () {
  25013. function MaterialHelper() {
  25014. }
  25015. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  25016. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25017. var lightIndex = 0;
  25018. var needNormals = false;
  25019. var needRebuild = false;
  25020. var needShadows = false;
  25021. var lightmapMode = false;
  25022. for (var index = 0; index < scene.lights.length; index++) {
  25023. var light = scene.lights[index];
  25024. if (!light.isEnabled()) {
  25025. continue;
  25026. }
  25027. // Excluded check
  25028. if (light._excludedMeshesIds.length > 0) {
  25029. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  25030. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  25031. if (excludedMesh) {
  25032. light.excludedMeshes.push(excludedMesh);
  25033. }
  25034. }
  25035. light._excludedMeshesIds = [];
  25036. }
  25037. // Included check
  25038. if (light._includedOnlyMeshesIds.length > 0) {
  25039. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  25040. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  25041. if (includedOnlyMesh) {
  25042. light.includedOnlyMeshes.push(includedOnlyMesh);
  25043. }
  25044. }
  25045. light._includedOnlyMeshesIds = [];
  25046. }
  25047. if (!light.canAffectMesh(mesh)) {
  25048. continue;
  25049. }
  25050. needNormals = true;
  25051. if (defines["LIGHT" + lightIndex] === undefined) {
  25052. needRebuild = true;
  25053. }
  25054. defines["LIGHT" + lightIndex] = true;
  25055. var type;
  25056. if (light instanceof BABYLON.SpotLight) {
  25057. type = "SPOTLIGHT" + lightIndex;
  25058. }
  25059. else if (light instanceof BABYLON.HemisphericLight) {
  25060. type = "HEMILIGHT" + lightIndex;
  25061. }
  25062. else if (light instanceof BABYLON.PointLight) {
  25063. type = "POINTLIGHT" + lightIndex;
  25064. }
  25065. else {
  25066. type = "DIRLIGHT" + lightIndex;
  25067. }
  25068. if (defines[type] === undefined) {
  25069. needRebuild = true;
  25070. }
  25071. defines[type] = true;
  25072. // Specular
  25073. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25074. defines["SPECULARTERM"] = true;
  25075. }
  25076. // Shadows
  25077. if (scene.shadowsEnabled) {
  25078. var shadowGenerator = light.getShadowGenerator();
  25079. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25080. if (defines["SHADOW" + lightIndex] === undefined) {
  25081. needRebuild = true;
  25082. }
  25083. defines["SHADOW" + lightIndex] = true;
  25084. defines["SHADOWS"] = true;
  25085. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25086. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25087. needRebuild = true;
  25088. }
  25089. defines["SHADOWVSM" + lightIndex] = true;
  25090. }
  25091. if (shadowGenerator.usePoissonSampling) {
  25092. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25093. needRebuild = true;
  25094. }
  25095. defines["SHADOWPCF" + lightIndex] = true;
  25096. }
  25097. needShadows = true;
  25098. }
  25099. }
  25100. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25101. lightmapMode = true;
  25102. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25103. needRebuild = true;
  25104. }
  25105. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25106. needRebuild = true;
  25107. }
  25108. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25109. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25110. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25111. }
  25112. }
  25113. lightIndex++;
  25114. if (lightIndex === maxSimultaneousLights)
  25115. break;
  25116. }
  25117. var caps = scene.getEngine().getCaps();
  25118. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25119. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25120. needRebuild = true;
  25121. }
  25122. defines["SHADOWFULLFLOAT"] = true;
  25123. }
  25124. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25125. needRebuild = true;
  25126. }
  25127. if (lightmapMode) {
  25128. defines["LIGHTMAPEXCLUDED"] = true;
  25129. }
  25130. if (needRebuild) {
  25131. defines.rebuild();
  25132. }
  25133. return needNormals;
  25134. };
  25135. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25136. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25137. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25138. if (!defines["LIGHT" + lightIndex]) {
  25139. break;
  25140. }
  25141. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25142. samplersList.push("shadowSampler" + lightIndex);
  25143. }
  25144. };
  25145. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25146. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25147. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25148. if (!defines["LIGHT" + lightIndex]) {
  25149. break;
  25150. }
  25151. if (lightIndex > 0) {
  25152. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25153. }
  25154. if (defines["SHADOW" + lightIndex]) {
  25155. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25156. }
  25157. if (defines["SHADOWPCF" + lightIndex]) {
  25158. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25159. }
  25160. if (defines["SHADOWVSM" + lightIndex]) {
  25161. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25162. }
  25163. }
  25164. };
  25165. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25166. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25167. fallbacks.addCPUSkinningFallback(0, mesh);
  25168. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25169. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25170. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25171. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25172. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25173. }
  25174. }
  25175. };
  25176. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25177. if (defines["INSTANCES"]) {
  25178. attribs.push("world0");
  25179. attribs.push("world1");
  25180. attribs.push("world2");
  25181. attribs.push("world3");
  25182. }
  25183. };
  25184. // Bindings
  25185. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25186. var shadowGenerator = light.getShadowGenerator();
  25187. if (mesh.receiveShadows && shadowGenerator) {
  25188. if (!light.needCube()) {
  25189. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25190. }
  25191. else {
  25192. if (!depthValuesAlreadySet) {
  25193. depthValuesAlreadySet = true;
  25194. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25195. }
  25196. }
  25197. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25198. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25199. }
  25200. return depthValuesAlreadySet;
  25201. };
  25202. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25203. if (light instanceof BABYLON.PointLight) {
  25204. // Point Light
  25205. light.transferToEffect(effect, "vLightData" + lightIndex);
  25206. }
  25207. else if (light instanceof BABYLON.DirectionalLight) {
  25208. // Directional Light
  25209. light.transferToEffect(effect, "vLightData" + lightIndex);
  25210. }
  25211. else if (light instanceof BABYLON.SpotLight) {
  25212. // Spot Light
  25213. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25214. }
  25215. else if (light instanceof BABYLON.HemisphericLight) {
  25216. // Hemispheric Light
  25217. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25218. }
  25219. };
  25220. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25221. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25222. var lightIndex = 0;
  25223. var depthValuesAlreadySet = false;
  25224. for (var index = 0; index < scene.lights.length; index++) {
  25225. var light = scene.lights[index];
  25226. if (!light.isEnabled()) {
  25227. continue;
  25228. }
  25229. if (!light.canAffectMesh(mesh)) {
  25230. continue;
  25231. }
  25232. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25233. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25234. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25235. if (defines["SPECULARTERM"]) {
  25236. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25237. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25238. }
  25239. // Shadows
  25240. if (scene.shadowsEnabled) {
  25241. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25242. }
  25243. lightIndex++;
  25244. if (lightIndex === maxSimultaneousLights)
  25245. break;
  25246. }
  25247. };
  25248. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25249. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25250. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25251. effect.setColor3("vFogColor", scene.fogColor);
  25252. }
  25253. };
  25254. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25255. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25256. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25257. if (matrices) {
  25258. effect.setMatrices("mBones", matrices);
  25259. }
  25260. }
  25261. };
  25262. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25263. if (defines["LOGARITHMICDEPTH"]) {
  25264. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25265. }
  25266. };
  25267. MaterialHelper.BindClipPlane = function (effect, scene) {
  25268. if (scene.clipPlane) {
  25269. var clipPlane = scene.clipPlane;
  25270. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25271. }
  25272. };
  25273. return MaterialHelper;
  25274. }());
  25275. BABYLON.MaterialHelper = MaterialHelper;
  25276. })(BABYLON || (BABYLON = {}));
  25277. var BABYLON;
  25278. (function (BABYLON) {
  25279. var FresnelParameters = (function () {
  25280. function FresnelParameters() {
  25281. this.isEnabled = true;
  25282. this.leftColor = BABYLON.Color3.White();
  25283. this.rightColor = BABYLON.Color3.Black();
  25284. this.bias = 0;
  25285. this.power = 1;
  25286. }
  25287. FresnelParameters.prototype.clone = function () {
  25288. var newFresnelParameters = new FresnelParameters();
  25289. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25290. return newFresnelParameters;
  25291. };
  25292. FresnelParameters.prototype.serialize = function () {
  25293. var serializationObject = {};
  25294. serializationObject.isEnabled = this.isEnabled;
  25295. serializationObject.leftColor = this.leftColor;
  25296. serializationObject.rightColor = this.rightColor;
  25297. serializationObject.bias = this.bias;
  25298. serializationObject.power = this.power;
  25299. return serializationObject;
  25300. };
  25301. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25302. var fresnelParameters = new FresnelParameters();
  25303. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25304. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25305. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25306. fresnelParameters.bias = parsedFresnelParameters.bias;
  25307. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25308. return fresnelParameters;
  25309. };
  25310. return FresnelParameters;
  25311. }());
  25312. BABYLON.FresnelParameters = FresnelParameters;
  25313. })(BABYLON || (BABYLON = {}));
  25314. var BABYLON;
  25315. (function (BABYLON) {
  25316. var MaterialDefines = (function () {
  25317. function MaterialDefines() {
  25318. }
  25319. MaterialDefines.prototype.rebuild = function () {
  25320. if (this._keys) {
  25321. delete this._keys;
  25322. }
  25323. this._keys = Object.keys(this);
  25324. };
  25325. MaterialDefines.prototype.isEqual = function (other) {
  25326. if (this._keys.length !== other._keys.length) {
  25327. return false;
  25328. }
  25329. for (var index = 0; index < this._keys.length; index++) {
  25330. var prop = this._keys[index];
  25331. if (this[prop] !== other[prop]) {
  25332. return false;
  25333. }
  25334. }
  25335. return true;
  25336. };
  25337. MaterialDefines.prototype.cloneTo = function (other) {
  25338. if (this._keys.length !== other._keys.length) {
  25339. other._keys = this._keys.slice(0);
  25340. }
  25341. for (var index = 0; index < this._keys.length; index++) {
  25342. var prop = this._keys[index];
  25343. other[prop] = this[prop];
  25344. }
  25345. };
  25346. MaterialDefines.prototype.reset = function () {
  25347. for (var index = 0; index < this._keys.length; index++) {
  25348. var prop = this._keys[index];
  25349. if (typeof (this[prop]) === "number") {
  25350. this[prop] = 0;
  25351. }
  25352. else {
  25353. this[prop] = false;
  25354. }
  25355. }
  25356. };
  25357. MaterialDefines.prototype.toString = function () {
  25358. var result = "";
  25359. for (var index = 0; index < this._keys.length; index++) {
  25360. var prop = this._keys[index];
  25361. if (typeof (this[prop]) === "number") {
  25362. result += "#define " + prop + " " + this[prop] + "\n";
  25363. }
  25364. else if (this[prop]) {
  25365. result += "#define " + prop + "\n";
  25366. }
  25367. }
  25368. return result;
  25369. };
  25370. return MaterialDefines;
  25371. }());
  25372. BABYLON.MaterialDefines = MaterialDefines;
  25373. var Material = (function () {
  25374. function Material(name, scene, doNotAdd) {
  25375. this.name = name;
  25376. this.checkReadyOnEveryCall = false;
  25377. this.checkReadyOnlyOnce = false;
  25378. this.state = "";
  25379. this.alpha = 1.0;
  25380. this.backFaceCulling = true;
  25381. /**
  25382. * An event triggered when the material is disposed.
  25383. * @type {BABYLON.Observable}
  25384. */
  25385. this.onDisposeObservable = new BABYLON.Observable();
  25386. /**
  25387. * An event triggered when the material is bound.
  25388. * @type {BABYLON.Observable}
  25389. */
  25390. this.onBindObservable = new BABYLON.Observable();
  25391. /**
  25392. * An event triggered when the material is unbound.
  25393. * @type {BABYLON.Observable}
  25394. */
  25395. this.onUnBindObservable = new BABYLON.Observable();
  25396. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25397. this.disableDepthWrite = false;
  25398. this.fogEnabled = true;
  25399. this.pointSize = 1.0;
  25400. this.zOffset = 0;
  25401. this._wasPreviouslyReady = false;
  25402. this._fillMode = Material.TriangleFillMode;
  25403. this.id = name;
  25404. this._scene = scene;
  25405. if (scene.useRightHandedSystem) {
  25406. this.sideOrientation = Material.ClockWiseSideOrientation;
  25407. }
  25408. else {
  25409. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25410. }
  25411. if (!doNotAdd) {
  25412. scene.materials.push(this);
  25413. }
  25414. }
  25415. Object.defineProperty(Material, "TriangleFillMode", {
  25416. get: function () {
  25417. return Material._TriangleFillMode;
  25418. },
  25419. enumerable: true,
  25420. configurable: true
  25421. });
  25422. Object.defineProperty(Material, "WireFrameFillMode", {
  25423. get: function () {
  25424. return Material._WireFrameFillMode;
  25425. },
  25426. enumerable: true,
  25427. configurable: true
  25428. });
  25429. Object.defineProperty(Material, "PointFillMode", {
  25430. get: function () {
  25431. return Material._PointFillMode;
  25432. },
  25433. enumerable: true,
  25434. configurable: true
  25435. });
  25436. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25437. get: function () {
  25438. return Material._ClockWiseSideOrientation;
  25439. },
  25440. enumerable: true,
  25441. configurable: true
  25442. });
  25443. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25444. get: function () {
  25445. return Material._CounterClockWiseSideOrientation;
  25446. },
  25447. enumerable: true,
  25448. configurable: true
  25449. });
  25450. Object.defineProperty(Material.prototype, "onDispose", {
  25451. set: function (callback) {
  25452. if (this._onDisposeObserver) {
  25453. this.onDisposeObservable.remove(this._onDisposeObserver);
  25454. }
  25455. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25456. },
  25457. enumerable: true,
  25458. configurable: true
  25459. });
  25460. Object.defineProperty(Material.prototype, "onBind", {
  25461. set: function (callback) {
  25462. if (this._onBindObserver) {
  25463. this.onBindObservable.remove(this._onBindObserver);
  25464. }
  25465. this._onBindObserver = this.onBindObservable.add(callback);
  25466. },
  25467. enumerable: true,
  25468. configurable: true
  25469. });
  25470. Object.defineProperty(Material.prototype, "wireframe", {
  25471. get: function () {
  25472. return this._fillMode === Material.WireFrameFillMode;
  25473. },
  25474. set: function (value) {
  25475. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25476. },
  25477. enumerable: true,
  25478. configurable: true
  25479. });
  25480. Object.defineProperty(Material.prototype, "pointsCloud", {
  25481. get: function () {
  25482. return this._fillMode === Material.PointFillMode;
  25483. },
  25484. set: function (value) {
  25485. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25486. },
  25487. enumerable: true,
  25488. configurable: true
  25489. });
  25490. Object.defineProperty(Material.prototype, "fillMode", {
  25491. get: function () {
  25492. return this._fillMode;
  25493. },
  25494. set: function (value) {
  25495. this._fillMode = value;
  25496. },
  25497. enumerable: true,
  25498. configurable: true
  25499. });
  25500. /**
  25501. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25502. * subclasses should override adding information pertainent to themselves
  25503. */
  25504. Material.prototype.toString = function (fullDetails) {
  25505. var ret = "Name: " + this.name;
  25506. if (fullDetails) {
  25507. }
  25508. return ret;
  25509. };
  25510. Object.defineProperty(Material.prototype, "isFrozen", {
  25511. get: function () {
  25512. return this.checkReadyOnlyOnce;
  25513. },
  25514. enumerable: true,
  25515. configurable: true
  25516. });
  25517. Material.prototype.freeze = function () {
  25518. this.checkReadyOnlyOnce = true;
  25519. };
  25520. Material.prototype.unfreeze = function () {
  25521. this.checkReadyOnlyOnce = false;
  25522. };
  25523. Material.prototype.isReady = function (mesh, useInstances) {
  25524. return true;
  25525. };
  25526. Material.prototype.getEffect = function () {
  25527. return this._effect;
  25528. };
  25529. Material.prototype.getScene = function () {
  25530. return this._scene;
  25531. };
  25532. Material.prototype.needAlphaBlending = function () {
  25533. return (this.alpha < 1.0);
  25534. };
  25535. Material.prototype.needAlphaTesting = function () {
  25536. return false;
  25537. };
  25538. Material.prototype.getAlphaTestTexture = function () {
  25539. return null;
  25540. };
  25541. Material.prototype.markDirty = function () {
  25542. this._wasPreviouslyReady = false;
  25543. };
  25544. Material.prototype._preBind = function () {
  25545. var engine = this._scene.getEngine();
  25546. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25547. engine.enableEffect(this._effect);
  25548. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25549. };
  25550. Material.prototype.bind = function (world, mesh) {
  25551. this._scene._cachedMaterial = this;
  25552. this.onBindObservable.notifyObservers(mesh);
  25553. if (this.disableDepthWrite) {
  25554. var engine = this._scene.getEngine();
  25555. this._cachedDepthWriteState = engine.getDepthWrite();
  25556. engine.setDepthWrite(false);
  25557. }
  25558. };
  25559. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25560. };
  25561. Material.prototype.unbind = function () {
  25562. this.onUnBindObservable.notifyObservers(this);
  25563. if (this.disableDepthWrite) {
  25564. var engine = this._scene.getEngine();
  25565. engine.setDepthWrite(this._cachedDepthWriteState);
  25566. }
  25567. };
  25568. Material.prototype.clone = function (name) {
  25569. return null;
  25570. };
  25571. Material.prototype.getBindedMeshes = function () {
  25572. var result = new Array();
  25573. for (var index = 0; index < this._scene.meshes.length; index++) {
  25574. var mesh = this._scene.meshes[index];
  25575. if (mesh.material === this) {
  25576. result.push(mesh);
  25577. }
  25578. }
  25579. return result;
  25580. };
  25581. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25582. // Animations
  25583. this.getScene().stopAnimation(this);
  25584. // Remove from scene
  25585. var index = this._scene.materials.indexOf(this);
  25586. if (index >= 0) {
  25587. this._scene.materials.splice(index, 1);
  25588. }
  25589. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25590. if (forceDisposeEffect && this._effect) {
  25591. this._scene.getEngine()._releaseEffect(this._effect);
  25592. this._effect = null;
  25593. }
  25594. // Remove from meshes
  25595. for (index = 0; index < this._scene.meshes.length; index++) {
  25596. var mesh = this._scene.meshes[index];
  25597. if (mesh.material === this) {
  25598. mesh.material = null;
  25599. }
  25600. }
  25601. // Callback
  25602. this.onDisposeObservable.notifyObservers(this);
  25603. this.onDisposeObservable.clear();
  25604. this.onBindObservable.clear();
  25605. this.onUnBindObservable.clear();
  25606. };
  25607. Material.prototype.serialize = function () {
  25608. return BABYLON.SerializationHelper.Serialize(this);
  25609. };
  25610. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25611. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25612. multiMaterial.id = parsedMultiMaterial.id;
  25613. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25614. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25615. var subMatId = parsedMultiMaterial.materials[matIndex];
  25616. if (subMatId) {
  25617. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25618. }
  25619. else {
  25620. multiMaterial.subMaterials.push(null);
  25621. }
  25622. }
  25623. return multiMaterial;
  25624. };
  25625. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25626. if (!parsedMaterial.customType) {
  25627. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25628. }
  25629. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25630. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25631. ;
  25632. };
  25633. Material._TriangleFillMode = 0;
  25634. Material._WireFrameFillMode = 1;
  25635. Material._PointFillMode = 2;
  25636. Material._ClockWiseSideOrientation = 0;
  25637. Material._CounterClockWiseSideOrientation = 1;
  25638. __decorate([
  25639. BABYLON.serialize()
  25640. ], Material.prototype, "id", void 0);
  25641. __decorate([
  25642. BABYLON.serialize()
  25643. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25644. __decorate([
  25645. BABYLON.serialize()
  25646. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25647. __decorate([
  25648. BABYLON.serialize()
  25649. ], Material.prototype, "state", void 0);
  25650. __decorate([
  25651. BABYLON.serialize()
  25652. ], Material.prototype, "alpha", void 0);
  25653. __decorate([
  25654. BABYLON.serialize()
  25655. ], Material.prototype, "backFaceCulling", void 0);
  25656. __decorate([
  25657. BABYLON.serialize()
  25658. ], Material.prototype, "sideOrientation", void 0);
  25659. __decorate([
  25660. BABYLON.serialize()
  25661. ], Material.prototype, "alphaMode", void 0);
  25662. __decorate([
  25663. BABYLON.serialize()
  25664. ], Material.prototype, "disableDepthWrite", void 0);
  25665. __decorate([
  25666. BABYLON.serialize()
  25667. ], Material.prototype, "fogEnabled", void 0);
  25668. __decorate([
  25669. BABYLON.serialize()
  25670. ], Material.prototype, "pointSize", void 0);
  25671. __decorate([
  25672. BABYLON.serialize()
  25673. ], Material.prototype, "zOffset", void 0);
  25674. __decorate([
  25675. BABYLON.serialize()
  25676. ], Material.prototype, "wireframe", null);
  25677. __decorate([
  25678. BABYLON.serialize()
  25679. ], Material.prototype, "pointsCloud", null);
  25680. __decorate([
  25681. BABYLON.serialize()
  25682. ], Material.prototype, "fillMode", null);
  25683. return Material;
  25684. }());
  25685. BABYLON.Material = Material;
  25686. })(BABYLON || (BABYLON = {}));
  25687. var BABYLON;
  25688. (function (BABYLON) {
  25689. var StandardMaterialDefines = (function (_super) {
  25690. __extends(StandardMaterialDefines, _super);
  25691. function StandardMaterialDefines() {
  25692. _super.call(this);
  25693. this.DIFFUSE = false;
  25694. this.AMBIENT = false;
  25695. this.OPACITY = false;
  25696. this.OPACITYRGB = false;
  25697. this.REFLECTION = false;
  25698. this.EMISSIVE = false;
  25699. this.SPECULAR = false;
  25700. this.BUMP = false;
  25701. this.PARALLAX = false;
  25702. this.PARALLAXOCCLUSION = false;
  25703. this.SPECULAROVERALPHA = false;
  25704. this.CLIPPLANE = false;
  25705. this.ALPHATEST = false;
  25706. this.ALPHAFROMDIFFUSE = false;
  25707. this.POINTSIZE = false;
  25708. this.FOG = false;
  25709. this.SPECULARTERM = false;
  25710. this.DIFFUSEFRESNEL = false;
  25711. this.OPACITYFRESNEL = false;
  25712. this.REFLECTIONFRESNEL = false;
  25713. this.REFRACTIONFRESNEL = false;
  25714. this.EMISSIVEFRESNEL = false;
  25715. this.FRESNEL = false;
  25716. this.NORMAL = false;
  25717. this.UV1 = false;
  25718. this.UV2 = false;
  25719. this.VERTEXCOLOR = false;
  25720. this.VERTEXALPHA = false;
  25721. this.NUM_BONE_INFLUENCERS = 0;
  25722. this.BonesPerMesh = 0;
  25723. this.INSTANCES = false;
  25724. this.GLOSSINESS = false;
  25725. this.ROUGHNESS = false;
  25726. this.EMISSIVEASILLUMINATION = false;
  25727. this.LINKEMISSIVEWITHDIFFUSE = false;
  25728. this.REFLECTIONFRESNELFROMSPECULAR = false;
  25729. this.LIGHTMAP = false;
  25730. this.USELIGHTMAPASSHADOWMAP = false;
  25731. this.REFLECTIONMAP_3D = false;
  25732. this.REFLECTIONMAP_SPHERICAL = false;
  25733. this.REFLECTIONMAP_PLANAR = false;
  25734. this.REFLECTIONMAP_CUBIC = false;
  25735. this.REFLECTIONMAP_PROJECTION = false;
  25736. this.REFLECTIONMAP_SKYBOX = false;
  25737. this.REFLECTIONMAP_EXPLICIT = false;
  25738. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  25739. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  25740. this.INVERTCUBICMAP = false;
  25741. this.LOGARITHMICDEPTH = false;
  25742. this.REFRACTION = false;
  25743. this.REFRACTIONMAP_3D = false;
  25744. this.REFLECTIONOVERALPHA = false;
  25745. this.INVERTNORMALMAPX = false;
  25746. this.INVERTNORMALMAPY = false;
  25747. this.SHADOWFULLFLOAT = false;
  25748. this.CAMERACOLORGRADING = false;
  25749. this.CAMERACOLORCURVES = false;
  25750. this.rebuild();
  25751. }
  25752. return StandardMaterialDefines;
  25753. }(BABYLON.MaterialDefines));
  25754. var StandardMaterial = (function (_super) {
  25755. __extends(StandardMaterial, _super);
  25756. function StandardMaterial(name, scene) {
  25757. var _this = this;
  25758. _super.call(this, name, scene);
  25759. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25760. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  25761. this.specularColor = new BABYLON.Color3(1, 1, 1);
  25762. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  25763. this.specularPower = 64;
  25764. this.useAlphaFromDiffuseTexture = false;
  25765. this.useEmissiveAsIllumination = false;
  25766. this.linkEmissiveWithDiffuse = false;
  25767. this.useReflectionFresnelFromSpecular = false;
  25768. this.useSpecularOverAlpha = false;
  25769. this.useReflectionOverAlpha = false;
  25770. this.disableLighting = false;
  25771. this.useParallax = false;
  25772. this.useParallaxOcclusion = false;
  25773. this.parallaxScaleBias = 0.05;
  25774. this.roughness = 0;
  25775. this.indexOfRefraction = 0.98;
  25776. this.invertRefractionY = true;
  25777. this.useLightmapAsShadowmap = false;
  25778. this.useGlossinessFromSpecularMapAlpha = false;
  25779. this.maxSimultaneousLights = 4;
  25780. /**
  25781. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  25782. */
  25783. this.invertNormalMapX = false;
  25784. /**
  25785. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  25786. */
  25787. this.invertNormalMapY = false;
  25788. /**
  25789. * Color Grading 2D Lookup Texture.
  25790. * This allows special effects like sepia, black and white to sixties rendering style.
  25791. */
  25792. this.cameraColorGradingTexture = null;
  25793. /**
  25794. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  25795. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  25796. * 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;
  25797. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  25798. */
  25799. this.cameraColorCurves = null;
  25800. this._renderTargets = new BABYLON.SmartArray(16);
  25801. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  25802. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  25803. this._defines = new StandardMaterialDefines();
  25804. this._cachedDefines = new StandardMaterialDefines();
  25805. this._cachedDefines.BonesPerMesh = -1;
  25806. this.getRenderTargetTextures = function () {
  25807. _this._renderTargets.reset();
  25808. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  25809. _this._renderTargets.push(_this.reflectionTexture);
  25810. }
  25811. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  25812. _this._renderTargets.push(_this.refractionTexture);
  25813. }
  25814. return _this._renderTargets;
  25815. };
  25816. }
  25817. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  25818. get: function () {
  25819. return this._useLogarithmicDepth;
  25820. },
  25821. set: function (value) {
  25822. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  25823. },
  25824. enumerable: true,
  25825. configurable: true
  25826. });
  25827. StandardMaterial.prototype.needAlphaBlending = function () {
  25828. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  25829. };
  25830. StandardMaterial.prototype.needAlphaTesting = function () {
  25831. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  25832. };
  25833. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  25834. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  25835. };
  25836. StandardMaterial.prototype.getAlphaTestTexture = function () {
  25837. return this.diffuseTexture;
  25838. };
  25839. // Methods
  25840. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  25841. if (!mesh) {
  25842. return true;
  25843. }
  25844. if (this._defines.INSTANCES !== useInstances) {
  25845. return false;
  25846. }
  25847. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25848. return true;
  25849. }
  25850. return false;
  25851. };
  25852. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25853. if (this.isFrozen) {
  25854. if (this._wasPreviouslyReady) {
  25855. return true;
  25856. }
  25857. }
  25858. var scene = this.getScene();
  25859. if (!this.checkReadyOnEveryCall) {
  25860. if (this._renderId === scene.getRenderId()) {
  25861. if (this._checkCache(scene, mesh, useInstances)) {
  25862. return true;
  25863. }
  25864. }
  25865. }
  25866. var engine = scene.getEngine();
  25867. var needNormals = false;
  25868. var needUVs = false;
  25869. this._defines.reset();
  25870. // Textures
  25871. if (scene.texturesEnabled) {
  25872. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25873. if (!this.diffuseTexture.isReady()) {
  25874. return false;
  25875. }
  25876. else {
  25877. needUVs = true;
  25878. this._defines.DIFFUSE = true;
  25879. }
  25880. }
  25881. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25882. if (!this.ambientTexture.isReady()) {
  25883. return false;
  25884. }
  25885. else {
  25886. needUVs = true;
  25887. this._defines.AMBIENT = true;
  25888. }
  25889. }
  25890. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25891. if (!this.opacityTexture.isReady()) {
  25892. return false;
  25893. }
  25894. else {
  25895. needUVs = true;
  25896. this._defines.OPACITY = true;
  25897. if (this.opacityTexture.getAlphaFromRGB) {
  25898. this._defines.OPACITYRGB = true;
  25899. }
  25900. }
  25901. }
  25902. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25903. if (!this.reflectionTexture.isReady()) {
  25904. return false;
  25905. }
  25906. else {
  25907. needNormals = true;
  25908. this._defines.REFLECTION = true;
  25909. if (this.roughness > 0) {
  25910. this._defines.ROUGHNESS = true;
  25911. }
  25912. if (this.useReflectionOverAlpha) {
  25913. this._defines.REFLECTIONOVERALPHA = true;
  25914. }
  25915. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25916. this._defines.INVERTCUBICMAP = true;
  25917. }
  25918. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25919. switch (this.reflectionTexture.coordinatesMode) {
  25920. case BABYLON.Texture.CUBIC_MODE:
  25921. case BABYLON.Texture.INVCUBIC_MODE:
  25922. this._defines.REFLECTIONMAP_CUBIC = true;
  25923. break;
  25924. case BABYLON.Texture.EXPLICIT_MODE:
  25925. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25926. break;
  25927. case BABYLON.Texture.PLANAR_MODE:
  25928. this._defines.REFLECTIONMAP_PLANAR = true;
  25929. break;
  25930. case BABYLON.Texture.PROJECTION_MODE:
  25931. this._defines.REFLECTIONMAP_PROJECTION = true;
  25932. break;
  25933. case BABYLON.Texture.SKYBOX_MODE:
  25934. this._defines.REFLECTIONMAP_SKYBOX = true;
  25935. break;
  25936. case BABYLON.Texture.SPHERICAL_MODE:
  25937. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25938. break;
  25939. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25940. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25941. break;
  25942. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25943. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25944. break;
  25945. }
  25946. }
  25947. }
  25948. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25949. if (!this.emissiveTexture.isReady()) {
  25950. return false;
  25951. }
  25952. else {
  25953. needUVs = true;
  25954. this._defines.EMISSIVE = true;
  25955. }
  25956. }
  25957. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25958. if (!this.lightmapTexture.isReady()) {
  25959. return false;
  25960. }
  25961. else {
  25962. needUVs = true;
  25963. this._defines.LIGHTMAP = true;
  25964. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25965. }
  25966. }
  25967. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25968. if (!this.specularTexture.isReady()) {
  25969. return false;
  25970. }
  25971. else {
  25972. needUVs = true;
  25973. this._defines.SPECULAR = true;
  25974. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25975. }
  25976. }
  25977. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25978. if (!this.bumpTexture.isReady()) {
  25979. return false;
  25980. }
  25981. else {
  25982. needUVs = true;
  25983. this._defines.BUMP = true;
  25984. if (this.useParallax) {
  25985. this._defines.PARALLAX = true;
  25986. if (this.useParallaxOcclusion) {
  25987. this._defines.PARALLAXOCCLUSION = true;
  25988. }
  25989. }
  25990. if (this.invertNormalMapX) {
  25991. this._defines.INVERTNORMALMAPX = true;
  25992. }
  25993. if (this.invertNormalMapY) {
  25994. this._defines.INVERTNORMALMAPY = true;
  25995. }
  25996. }
  25997. }
  25998. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25999. if (!this.refractionTexture.isReady()) {
  26000. return false;
  26001. }
  26002. else {
  26003. needUVs = true;
  26004. this._defines.REFRACTION = true;
  26005. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  26006. }
  26007. }
  26008. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26009. if (!this.cameraColorGradingTexture.isReady()) {
  26010. return false;
  26011. }
  26012. else {
  26013. this._defines.CAMERACOLORGRADING = true;
  26014. }
  26015. }
  26016. }
  26017. // Effect
  26018. if (scene.clipPlane) {
  26019. this._defines.CLIPPLANE = true;
  26020. }
  26021. if (engine.getAlphaTesting()) {
  26022. this._defines.ALPHATEST = true;
  26023. }
  26024. if (this._shouldUseAlphaFromDiffuseTexture()) {
  26025. this._defines.ALPHAFROMDIFFUSE = true;
  26026. }
  26027. if (this.useEmissiveAsIllumination) {
  26028. this._defines.EMISSIVEASILLUMINATION = true;
  26029. }
  26030. if (this.linkEmissiveWithDiffuse) {
  26031. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  26032. }
  26033. if (this.useLogarithmicDepth) {
  26034. this._defines.LOGARITHMICDEPTH = true;
  26035. }
  26036. if (this.cameraColorCurves) {
  26037. this._defines.CAMERACOLORCURVES = true;
  26038. }
  26039. // Point size
  26040. if (this.pointsCloud || scene.forcePointsCloud) {
  26041. this._defines.POINTSIZE = true;
  26042. }
  26043. // Fog
  26044. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26045. this._defines.FOG = true;
  26046. }
  26047. if (scene.lightsEnabled && !this.disableLighting) {
  26048. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  26049. }
  26050. if (StandardMaterial.FresnelEnabled) {
  26051. // Fresnel
  26052. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26053. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26054. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26055. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26056. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26057. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26058. this._defines.DIFFUSEFRESNEL = true;
  26059. }
  26060. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26061. this._defines.OPACITYFRESNEL = true;
  26062. }
  26063. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26064. this._defines.REFLECTIONFRESNEL = true;
  26065. if (this.useReflectionFresnelFromSpecular) {
  26066. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26067. }
  26068. }
  26069. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26070. this._defines.REFRACTIONFRESNEL = true;
  26071. }
  26072. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26073. this._defines.EMISSIVEFRESNEL = true;
  26074. }
  26075. needNormals = true;
  26076. this._defines.FRESNEL = true;
  26077. }
  26078. }
  26079. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26080. this._defines.SPECULAROVERALPHA = true;
  26081. }
  26082. // Attribs
  26083. if (mesh) {
  26084. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26085. this._defines.NORMAL = true;
  26086. }
  26087. if (needUVs) {
  26088. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26089. this._defines.UV1 = true;
  26090. }
  26091. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26092. this._defines.UV2 = true;
  26093. }
  26094. }
  26095. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26096. this._defines.VERTEXCOLOR = true;
  26097. if (mesh.hasVertexAlpha) {
  26098. this._defines.VERTEXALPHA = true;
  26099. }
  26100. }
  26101. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26102. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26103. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26104. }
  26105. // Instances
  26106. if (useInstances) {
  26107. this._defines.INSTANCES = true;
  26108. }
  26109. }
  26110. // Get correct effect
  26111. if (!this._defines.isEqual(this._cachedDefines)) {
  26112. this._defines.cloneTo(this._cachedDefines);
  26113. scene.resetCachedMaterial();
  26114. // Fallbacks
  26115. var fallbacks = new BABYLON.EffectFallbacks();
  26116. if (this._defines.REFLECTION) {
  26117. fallbacks.addFallback(0, "REFLECTION");
  26118. }
  26119. if (this._defines.SPECULAR) {
  26120. fallbacks.addFallback(0, "SPECULAR");
  26121. }
  26122. if (this._defines.BUMP) {
  26123. fallbacks.addFallback(0, "BUMP");
  26124. }
  26125. if (this._defines.PARALLAX) {
  26126. fallbacks.addFallback(1, "PARALLAX");
  26127. }
  26128. if (this._defines.PARALLAXOCCLUSION) {
  26129. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26130. }
  26131. if (this._defines.SPECULAROVERALPHA) {
  26132. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26133. }
  26134. if (this._defines.FOG) {
  26135. fallbacks.addFallback(1, "FOG");
  26136. }
  26137. if (this._defines.POINTSIZE) {
  26138. fallbacks.addFallback(0, "POINTSIZE");
  26139. }
  26140. if (this._defines.LOGARITHMICDEPTH) {
  26141. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26142. }
  26143. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26144. if (this._defines.SPECULARTERM) {
  26145. fallbacks.addFallback(0, "SPECULARTERM");
  26146. }
  26147. if (this._defines.DIFFUSEFRESNEL) {
  26148. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26149. }
  26150. if (this._defines.OPACITYFRESNEL) {
  26151. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26152. }
  26153. if (this._defines.REFLECTIONFRESNEL) {
  26154. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26155. }
  26156. if (this._defines.EMISSIVEFRESNEL) {
  26157. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26158. }
  26159. if (this._defines.FRESNEL) {
  26160. fallbacks.addFallback(4, "FRESNEL");
  26161. }
  26162. //Attributes
  26163. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26164. if (this._defines.NORMAL) {
  26165. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26166. }
  26167. if (this._defines.UV1) {
  26168. attribs.push(BABYLON.VertexBuffer.UVKind);
  26169. }
  26170. if (this._defines.UV2) {
  26171. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26172. }
  26173. if (this._defines.VERTEXCOLOR) {
  26174. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26175. }
  26176. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26177. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26178. var shaderName = "default";
  26179. var join = this._defines.toString();
  26180. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26181. "vFogInfos", "vFogColor", "pointSize",
  26182. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26183. "mBones",
  26184. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26185. "depthValues",
  26186. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26187. "logarithmicDepthConstant"
  26188. ];
  26189. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26190. if (this._defines.CAMERACOLORCURVES) {
  26191. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26192. }
  26193. if (this._defines.CAMERACOLORGRADING) {
  26194. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26195. }
  26196. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26197. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26198. }
  26199. if (!this._effect.isReady()) {
  26200. return false;
  26201. }
  26202. this._renderId = scene.getRenderId();
  26203. this._wasPreviouslyReady = true;
  26204. if (mesh) {
  26205. if (!mesh._materialDefines) {
  26206. mesh._materialDefines = new StandardMaterialDefines();
  26207. }
  26208. this._defines.cloneTo(mesh._materialDefines);
  26209. }
  26210. return true;
  26211. };
  26212. StandardMaterial.prototype.unbind = function () {
  26213. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26214. this._effect.setTexture("reflection2DSampler", null);
  26215. }
  26216. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26217. this._effect.setTexture("refraction2DSampler", null);
  26218. }
  26219. _super.prototype.unbind.call(this);
  26220. };
  26221. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26222. this._effect.setMatrix("world", world);
  26223. };
  26224. StandardMaterial.prototype.bind = function (world, mesh) {
  26225. var scene = this.getScene();
  26226. // Matrices
  26227. this.bindOnlyWorldMatrix(world);
  26228. // Bones
  26229. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26230. if (scene.getCachedMaterial() !== this) {
  26231. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26232. if (StandardMaterial.FresnelEnabled) {
  26233. // Fresnel
  26234. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26235. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26236. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26237. }
  26238. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26239. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26240. }
  26241. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26242. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26243. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26244. }
  26245. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26246. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26247. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26248. }
  26249. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26250. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26251. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26252. }
  26253. }
  26254. // Textures
  26255. if (scene.texturesEnabled) {
  26256. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26257. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26258. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26259. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26260. }
  26261. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26262. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26263. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26264. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26265. }
  26266. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26267. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26268. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26269. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26270. }
  26271. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26272. if (this.reflectionTexture.isCube) {
  26273. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26274. }
  26275. else {
  26276. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26277. }
  26278. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26279. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26280. }
  26281. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26282. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26283. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26284. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26285. }
  26286. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26287. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26288. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26289. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26290. }
  26291. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26292. this._effect.setTexture("specularSampler", this.specularTexture);
  26293. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26294. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26295. }
  26296. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26297. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26298. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26299. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26300. }
  26301. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26302. var depth = 1.0;
  26303. if (this.refractionTexture.isCube) {
  26304. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26305. }
  26306. else {
  26307. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26308. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26309. if (this.refractionTexture.depth) {
  26310. depth = this.refractionTexture.depth;
  26311. }
  26312. }
  26313. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26314. }
  26315. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26316. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26317. }
  26318. }
  26319. // Clip plane
  26320. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26321. // Point size
  26322. if (this.pointsCloud) {
  26323. this._effect.setFloat("pointSize", this.pointSize);
  26324. }
  26325. // Colors
  26326. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26327. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26328. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26329. if (this._defines.SPECULARTERM) {
  26330. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26331. }
  26332. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26333. }
  26334. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26335. // Diffuse
  26336. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26337. // Lights
  26338. if (scene.lightsEnabled && !this.disableLighting) {
  26339. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26340. }
  26341. // View
  26342. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26343. this._effect.setMatrix("view", scene.getViewMatrix());
  26344. }
  26345. // Fog
  26346. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26347. // Log. depth
  26348. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26349. // Color Curves
  26350. if (this.cameraColorCurves) {
  26351. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26352. }
  26353. }
  26354. _super.prototype.bind.call(this, world, mesh);
  26355. };
  26356. StandardMaterial.prototype.getAnimatables = function () {
  26357. var results = [];
  26358. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26359. results.push(this.diffuseTexture);
  26360. }
  26361. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26362. results.push(this.ambientTexture);
  26363. }
  26364. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26365. results.push(this.opacityTexture);
  26366. }
  26367. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26368. results.push(this.reflectionTexture);
  26369. }
  26370. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26371. results.push(this.emissiveTexture);
  26372. }
  26373. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26374. results.push(this.specularTexture);
  26375. }
  26376. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26377. results.push(this.bumpTexture);
  26378. }
  26379. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26380. results.push(this.lightmapTexture);
  26381. }
  26382. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26383. results.push(this.refractionTexture);
  26384. }
  26385. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26386. results.push(this.cameraColorGradingTexture);
  26387. }
  26388. return results;
  26389. };
  26390. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26391. if (forceDisposeTextures) {
  26392. if (this.diffuseTexture) {
  26393. this.diffuseTexture.dispose();
  26394. }
  26395. if (this.ambientTexture) {
  26396. this.ambientTexture.dispose();
  26397. }
  26398. if (this.opacityTexture) {
  26399. this.opacityTexture.dispose();
  26400. }
  26401. if (this.reflectionTexture) {
  26402. this.reflectionTexture.dispose();
  26403. }
  26404. if (this.emissiveTexture) {
  26405. this.emissiveTexture.dispose();
  26406. }
  26407. if (this.specularTexture) {
  26408. this.specularTexture.dispose();
  26409. }
  26410. if (this.bumpTexture) {
  26411. this.bumpTexture.dispose();
  26412. }
  26413. if (this.lightmapTexture) {
  26414. this.lightmapTexture.dispose();
  26415. }
  26416. if (this.refractionTexture) {
  26417. this.refractionTexture.dispose();
  26418. }
  26419. if (this.cameraColorGradingTexture) {
  26420. this.cameraColorGradingTexture.dispose();
  26421. }
  26422. }
  26423. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  26424. };
  26425. StandardMaterial.prototype.clone = function (name) {
  26426. var _this = this;
  26427. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  26428. };
  26429. StandardMaterial.prototype.serialize = function () {
  26430. return BABYLON.SerializationHelper.Serialize(this);
  26431. };
  26432. // Statics
  26433. StandardMaterial.Parse = function (source, scene, rootUrl) {
  26434. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  26435. };
  26436. // Flags used to enable or disable a type of texture for all Standard Materials
  26437. StandardMaterial.DiffuseTextureEnabled = true;
  26438. StandardMaterial.AmbientTextureEnabled = true;
  26439. StandardMaterial.OpacityTextureEnabled = true;
  26440. StandardMaterial.ReflectionTextureEnabled = true;
  26441. StandardMaterial.EmissiveTextureEnabled = true;
  26442. StandardMaterial.SpecularTextureEnabled = true;
  26443. StandardMaterial.BumpTextureEnabled = true;
  26444. StandardMaterial.FresnelEnabled = true;
  26445. StandardMaterial.LightmapTextureEnabled = true;
  26446. StandardMaterial.RefractionTextureEnabled = true;
  26447. StandardMaterial.ColorGradingTextureEnabled = true;
  26448. __decorate([
  26449. BABYLON.serializeAsTexture()
  26450. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  26451. __decorate([
  26452. BABYLON.serializeAsTexture()
  26453. ], StandardMaterial.prototype, "ambientTexture", void 0);
  26454. __decorate([
  26455. BABYLON.serializeAsTexture()
  26456. ], StandardMaterial.prototype, "opacityTexture", void 0);
  26457. __decorate([
  26458. BABYLON.serializeAsTexture()
  26459. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  26460. __decorate([
  26461. BABYLON.serializeAsTexture()
  26462. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  26463. __decorate([
  26464. BABYLON.serializeAsTexture()
  26465. ], StandardMaterial.prototype, "specularTexture", void 0);
  26466. __decorate([
  26467. BABYLON.serializeAsTexture()
  26468. ], StandardMaterial.prototype, "bumpTexture", void 0);
  26469. __decorate([
  26470. BABYLON.serializeAsTexture()
  26471. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  26472. __decorate([
  26473. BABYLON.serializeAsTexture()
  26474. ], StandardMaterial.prototype, "refractionTexture", void 0);
  26475. __decorate([
  26476. BABYLON.serializeAsColor3("ambient")
  26477. ], StandardMaterial.prototype, "ambientColor", void 0);
  26478. __decorate([
  26479. BABYLON.serializeAsColor3("diffuse")
  26480. ], StandardMaterial.prototype, "diffuseColor", void 0);
  26481. __decorate([
  26482. BABYLON.serializeAsColor3("specular")
  26483. ], StandardMaterial.prototype, "specularColor", void 0);
  26484. __decorate([
  26485. BABYLON.serializeAsColor3("emissive")
  26486. ], StandardMaterial.prototype, "emissiveColor", void 0);
  26487. __decorate([
  26488. BABYLON.serialize()
  26489. ], StandardMaterial.prototype, "specularPower", void 0);
  26490. __decorate([
  26491. BABYLON.serialize()
  26492. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  26493. __decorate([
  26494. BABYLON.serialize()
  26495. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  26496. __decorate([
  26497. BABYLON.serialize()
  26498. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  26499. __decorate([
  26500. BABYLON.serialize()
  26501. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  26502. __decorate([
  26503. BABYLON.serialize()
  26504. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  26505. __decorate([
  26506. BABYLON.serialize()
  26507. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  26508. __decorate([
  26509. BABYLON.serialize()
  26510. ], StandardMaterial.prototype, "disableLighting", void 0);
  26511. __decorate([
  26512. BABYLON.serialize()
  26513. ], StandardMaterial.prototype, "useParallax", void 0);
  26514. __decorate([
  26515. BABYLON.serialize()
  26516. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  26517. __decorate([
  26518. BABYLON.serialize()
  26519. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  26520. __decorate([
  26521. BABYLON.serialize()
  26522. ], StandardMaterial.prototype, "roughness", void 0);
  26523. __decorate([
  26524. BABYLON.serialize()
  26525. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  26526. __decorate([
  26527. BABYLON.serialize()
  26528. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  26529. __decorate([
  26530. BABYLON.serialize()
  26531. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  26532. __decorate([
  26533. BABYLON.serializeAsFresnelParameters()
  26534. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  26535. __decorate([
  26536. BABYLON.serializeAsFresnelParameters()
  26537. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  26538. __decorate([
  26539. BABYLON.serializeAsFresnelParameters()
  26540. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  26541. __decorate([
  26542. BABYLON.serializeAsFresnelParameters()
  26543. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  26544. __decorate([
  26545. BABYLON.serializeAsFresnelParameters()
  26546. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  26547. __decorate([
  26548. BABYLON.serialize()
  26549. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  26550. __decorate([
  26551. BABYLON.serialize()
  26552. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  26553. __decorate([
  26554. BABYLON.serialize()
  26555. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  26556. __decorate([
  26557. BABYLON.serialize()
  26558. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  26559. __decorate([
  26560. BABYLON.serializeAsTexture()
  26561. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  26562. __decorate([
  26563. BABYLON.serializeAsColorCurves()
  26564. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  26565. __decorate([
  26566. BABYLON.serialize()
  26567. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  26568. return StandardMaterial;
  26569. }(BABYLON.Material));
  26570. BABYLON.StandardMaterial = StandardMaterial;
  26571. })(BABYLON || (BABYLON = {}));
  26572. var BABYLON;
  26573. (function (BABYLON) {
  26574. var MultiMaterial = (function (_super) {
  26575. __extends(MultiMaterial, _super);
  26576. function MultiMaterial(name, scene) {
  26577. _super.call(this, name, scene, true);
  26578. this.subMaterials = new Array();
  26579. scene.multiMaterials.push(this);
  26580. }
  26581. // Properties
  26582. MultiMaterial.prototype.getSubMaterial = function (index) {
  26583. if (index < 0 || index >= this.subMaterials.length) {
  26584. return this.getScene().defaultMaterial;
  26585. }
  26586. return this.subMaterials[index];
  26587. };
  26588. // Methods
  26589. MultiMaterial.prototype.isReady = function (mesh) {
  26590. for (var index = 0; index < this.subMaterials.length; index++) {
  26591. var subMaterial = this.subMaterials[index];
  26592. if (subMaterial) {
  26593. if (!this.subMaterials[index].isReady(mesh)) {
  26594. return false;
  26595. }
  26596. }
  26597. }
  26598. return true;
  26599. };
  26600. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  26601. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  26602. for (var index = 0; index < this.subMaterials.length; index++) {
  26603. var subMaterial = null;
  26604. if (cloneChildren) {
  26605. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  26606. }
  26607. else {
  26608. subMaterial = this.subMaterials[index];
  26609. }
  26610. newMultiMaterial.subMaterials.push(subMaterial);
  26611. }
  26612. return newMultiMaterial;
  26613. };
  26614. MultiMaterial.prototype.serialize = function () {
  26615. var serializationObject = {};
  26616. serializationObject.name = this.name;
  26617. serializationObject.id = this.id;
  26618. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26619. serializationObject.materials = [];
  26620. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  26621. var subMat = this.subMaterials[matIndex];
  26622. if (subMat) {
  26623. serializationObject.materials.push(subMat.id);
  26624. }
  26625. else {
  26626. serializationObject.materials.push(null);
  26627. }
  26628. }
  26629. return serializationObject;
  26630. };
  26631. return MultiMaterial;
  26632. }(BABYLON.Material));
  26633. BABYLON.MultiMaterial = MultiMaterial;
  26634. })(BABYLON || (BABYLON = {}));
  26635. var BABYLON;
  26636. (function (BABYLON) {
  26637. var SceneLoader = (function () {
  26638. function SceneLoader() {
  26639. }
  26640. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  26641. get: function () {
  26642. return 0;
  26643. },
  26644. enumerable: true,
  26645. configurable: true
  26646. });
  26647. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  26648. get: function () {
  26649. return 1;
  26650. },
  26651. enumerable: true,
  26652. configurable: true
  26653. });
  26654. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  26655. get: function () {
  26656. return 2;
  26657. },
  26658. enumerable: true,
  26659. configurable: true
  26660. });
  26661. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  26662. get: function () {
  26663. return 3;
  26664. },
  26665. enumerable: true,
  26666. configurable: true
  26667. });
  26668. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  26669. get: function () {
  26670. return SceneLoader._ForceFullSceneLoadingForIncremental;
  26671. },
  26672. set: function (value) {
  26673. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  26674. },
  26675. enumerable: true,
  26676. configurable: true
  26677. });
  26678. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  26679. get: function () {
  26680. return SceneLoader._ShowLoadingScreen;
  26681. },
  26682. set: function (value) {
  26683. SceneLoader._ShowLoadingScreen = value;
  26684. },
  26685. enumerable: true,
  26686. configurable: true
  26687. });
  26688. Object.defineProperty(SceneLoader, "loggingLevel", {
  26689. get: function () {
  26690. return SceneLoader._loggingLevel;
  26691. },
  26692. set: function (value) {
  26693. SceneLoader._loggingLevel = value;
  26694. },
  26695. enumerable: true,
  26696. configurable: true
  26697. });
  26698. SceneLoader._getDefaultPlugin = function () {
  26699. return SceneLoader._registeredPlugins[".babylon"];
  26700. };
  26701. SceneLoader._getPluginForExtension = function (extension) {
  26702. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  26703. if (registeredPlugin) {
  26704. return registeredPlugin;
  26705. }
  26706. return SceneLoader._getDefaultPlugin();
  26707. };
  26708. SceneLoader._getPluginForFilename = function (sceneFilename) {
  26709. if (sceneFilename.name) {
  26710. sceneFilename = sceneFilename.name;
  26711. }
  26712. var dotPosition = sceneFilename.lastIndexOf(".");
  26713. var queryStringPosition = sceneFilename.indexOf("?");
  26714. if (queryStringPosition === -1) {
  26715. queryStringPosition = sceneFilename.length;
  26716. }
  26717. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  26718. return SceneLoader._getPluginForExtension(extension);
  26719. };
  26720. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  26721. SceneLoader._getDirectLoad = function (sceneFilename) {
  26722. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26723. return sceneFilename.substr(5);
  26724. }
  26725. return null;
  26726. };
  26727. // Public functions
  26728. SceneLoader.GetPluginForExtension = function (extension) {
  26729. return SceneLoader._getPluginForExtension(extension).plugin;
  26730. };
  26731. SceneLoader.RegisterPlugin = function (plugin) {
  26732. if (typeof plugin.extensions === "string") {
  26733. var extension = plugin.extensions;
  26734. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26735. plugin: plugin,
  26736. isBinary: false
  26737. };
  26738. }
  26739. else {
  26740. var extensions = plugin.extensions;
  26741. Object.keys(extensions).forEach(function (extension) {
  26742. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26743. plugin: plugin,
  26744. isBinary: extensions[extension].isBinary
  26745. };
  26746. });
  26747. }
  26748. };
  26749. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26750. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26751. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26752. return;
  26753. }
  26754. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26755. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26756. return;
  26757. }
  26758. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26759. var loadingToken = {};
  26760. scene._addPendingData(loadingToken);
  26761. var manifestChecked = function (success) {
  26762. scene.database = database;
  26763. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26764. var plugin = registeredPlugin.plugin;
  26765. var useArrayBuffer = registeredPlugin.isBinary;
  26766. var importMeshFromData = function (data) {
  26767. var meshes = [];
  26768. var particleSystems = [];
  26769. var skeletons = [];
  26770. try {
  26771. if (plugin.importMesh) {
  26772. var syncedPlugin = plugin;
  26773. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  26774. if (onerror) {
  26775. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26776. }
  26777. scene._removePendingData(loadingToken);
  26778. return;
  26779. }
  26780. if (onsuccess) {
  26781. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26782. onsuccess(meshes, particleSystems, skeletons);
  26783. scene._removePendingData(loadingToken);
  26784. }
  26785. }
  26786. else {
  26787. var asyncedPlugin = plugin;
  26788. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  26789. if (onsuccess) {
  26790. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26791. onsuccess(meshes, particleSystems, skeletons);
  26792. scene._removePendingData(loadingToken);
  26793. }
  26794. }, function () {
  26795. if (onerror) {
  26796. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26797. }
  26798. scene._removePendingData(loadingToken);
  26799. });
  26800. }
  26801. }
  26802. catch (e) {
  26803. if (onerror) {
  26804. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  26805. }
  26806. scene._removePendingData(loadingToken);
  26807. }
  26808. };
  26809. if (directLoad) {
  26810. importMeshFromData(directLoad);
  26811. return;
  26812. }
  26813. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  26814. importMeshFromData(data);
  26815. }, progressCallBack, database, useArrayBuffer);
  26816. };
  26817. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  26818. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26819. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26820. }
  26821. else {
  26822. // If the scene is a data stream or offline support is not enabled, it's a direct load
  26823. manifestChecked(true);
  26824. }
  26825. };
  26826. /**
  26827. * Load a scene
  26828. * @param rootUrl a string that defines the root url for scene and resources
  26829. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26830. * @param engine is the instance of BABYLON.Engine to use to create the scene
  26831. */
  26832. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  26833. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  26834. };
  26835. /**
  26836. * Append a scene
  26837. * @param rootUrl a string that defines the root url for scene and resources
  26838. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26839. * @param scene is the instance of BABYLON.Scene to append to
  26840. */
  26841. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26842. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26843. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26844. return;
  26845. }
  26846. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26847. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26848. var plugin = registeredPlugin.plugin;
  26849. var useArrayBuffer = registeredPlugin.isBinary;
  26850. var database;
  26851. var loadingToken = {};
  26852. scene._addPendingData(loadingToken);
  26853. if (SceneLoader.ShowLoadingScreen) {
  26854. scene.getEngine().displayLoadingUI();
  26855. }
  26856. var loadSceneFromData = function (data) {
  26857. scene.database = database;
  26858. if (plugin.load) {
  26859. var syncedPlugin = plugin;
  26860. if (!syncedPlugin.load(scene, data, rootUrl)) {
  26861. if (onerror) {
  26862. onerror(scene);
  26863. }
  26864. scene._removePendingData(loadingToken);
  26865. scene.getEngine().hideLoadingUI();
  26866. return;
  26867. }
  26868. if (onsuccess) {
  26869. onsuccess(scene);
  26870. }
  26871. scene._removePendingData(loadingToken);
  26872. }
  26873. else {
  26874. var asyncedPlugin = plugin;
  26875. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26876. if (onsuccess) {
  26877. onsuccess(scene);
  26878. }
  26879. scene._removePendingData(loadingToken);
  26880. }, function () {
  26881. if (onerror) {
  26882. onerror(scene);
  26883. }
  26884. scene._removePendingData(loadingToken);
  26885. scene.getEngine().hideLoadingUI();
  26886. });
  26887. }
  26888. if (SceneLoader.ShowLoadingScreen) {
  26889. scene.executeWhenReady(function () {
  26890. scene.getEngine().hideLoadingUI();
  26891. });
  26892. }
  26893. };
  26894. var manifestChecked = function (success) {
  26895. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  26896. };
  26897. if (directLoad) {
  26898. loadSceneFromData(directLoad);
  26899. return;
  26900. }
  26901. if (rootUrl.indexOf("file:") === -1) {
  26902. if (scene.getEngine().enableOfflineSupport) {
  26903. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26904. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26905. }
  26906. else {
  26907. manifestChecked(true);
  26908. }
  26909. }
  26910. else {
  26911. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  26912. }
  26913. };
  26914. // Flags
  26915. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26916. SceneLoader._ShowLoadingScreen = true;
  26917. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26918. // Members
  26919. SceneLoader._registeredPlugins = {};
  26920. return SceneLoader;
  26921. }());
  26922. BABYLON.SceneLoader = SceneLoader;
  26923. ;
  26924. })(BABYLON || (BABYLON = {}));
  26925. var BABYLON;
  26926. (function (BABYLON) {
  26927. var Internals;
  26928. (function (Internals) {
  26929. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26930. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26931. var parsedMaterial = parsedData.materials[index];
  26932. if (parsedMaterial.id === id) {
  26933. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26934. }
  26935. }
  26936. return null;
  26937. };
  26938. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26939. names = (names instanceof Array) ? names : [names];
  26940. for (var i in names) {
  26941. if (mesh.name === names[i]) {
  26942. hierarchyIds.push(mesh.id);
  26943. return true;
  26944. }
  26945. }
  26946. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26947. hierarchyIds.push(mesh.id);
  26948. return true;
  26949. }
  26950. return false;
  26951. };
  26952. var logOperation = function (operation, producer) {
  26953. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26954. };
  26955. BABYLON.SceneLoader.RegisterPlugin({
  26956. extensions: ".babylon",
  26957. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26958. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26959. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26960. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26961. // and avoid problems with multiple concurrent .babylon loads.
  26962. var log = "importMesh has failed JSON parse";
  26963. try {
  26964. var parsedData = JSON.parse(data);
  26965. log = "";
  26966. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26967. var loadedSkeletonsIds = [];
  26968. var loadedMaterialsIds = [];
  26969. var hierarchyIds = [];
  26970. var index;
  26971. var cache;
  26972. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26973. var parsedMesh = parsedData.meshes[index];
  26974. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26975. if (meshesNames instanceof Array) {
  26976. // Remove found mesh name from list.
  26977. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26978. }
  26979. //Geometry?
  26980. if (parsedMesh.geometryId) {
  26981. //does the file contain geometries?
  26982. if (parsedData.geometries) {
  26983. //find the correct geometry and add it to the scene
  26984. var found = false;
  26985. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  26986. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  26987. return;
  26988. }
  26989. else {
  26990. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  26991. if (parsedGeometryData.id === parsedMesh.geometryId) {
  26992. switch (geometryType) {
  26993. case "boxes":
  26994. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  26995. break;
  26996. case "spheres":
  26997. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  26998. break;
  26999. case "cylinders":
  27000. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  27001. break;
  27002. case "toruses":
  27003. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  27004. break;
  27005. case "grounds":
  27006. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  27007. break;
  27008. case "planes":
  27009. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  27010. break;
  27011. case "torusKnots":
  27012. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  27013. break;
  27014. case "vertexData":
  27015. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  27016. break;
  27017. }
  27018. found = true;
  27019. }
  27020. });
  27021. }
  27022. });
  27023. if (!found) {
  27024. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  27025. }
  27026. }
  27027. }
  27028. // Material ?
  27029. if (parsedMesh.materialId) {
  27030. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  27031. if (!materialFound && parsedData.multiMaterials) {
  27032. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  27033. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  27034. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  27035. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  27036. var subMatId = parsedMultiMaterial.materials[matIndex];
  27037. loadedMaterialsIds.push(subMatId);
  27038. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  27039. log += "\n\tMaterial " + mat.toString(fullDetails);
  27040. }
  27041. loadedMaterialsIds.push(parsedMultiMaterial.id);
  27042. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27043. materialFound = true;
  27044. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  27045. break;
  27046. }
  27047. }
  27048. }
  27049. if (!materialFound) {
  27050. loadedMaterialsIds.push(parsedMesh.materialId);
  27051. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27052. if (!mat) {
  27053. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27054. }
  27055. else {
  27056. log += "\n\tMaterial " + mat.toString(fullDetails);
  27057. }
  27058. }
  27059. }
  27060. // Skeleton ?
  27061. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27062. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27063. if (!skeletonAlreadyLoaded) {
  27064. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27065. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27066. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27067. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27068. skeletons.push(skeleton);
  27069. loadedSkeletonsIds.push(parsedSkeleton.id);
  27070. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27071. }
  27072. }
  27073. }
  27074. }
  27075. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27076. meshes.push(mesh);
  27077. log += "\n\tMesh " + mesh.toString(fullDetails);
  27078. }
  27079. }
  27080. // Connecting parents
  27081. var currentMesh;
  27082. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27083. currentMesh = scene.meshes[index];
  27084. if (currentMesh._waitingParentId) {
  27085. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27086. currentMesh._waitingParentId = undefined;
  27087. }
  27088. }
  27089. // freeze and compute world matrix application
  27090. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27091. currentMesh = scene.meshes[index];
  27092. if (currentMesh._waitingFreezeWorldMatrix) {
  27093. currentMesh.freezeWorldMatrix();
  27094. currentMesh._waitingFreezeWorldMatrix = undefined;
  27095. }
  27096. else {
  27097. currentMesh.computeWorldMatrix(true);
  27098. }
  27099. }
  27100. // Particles
  27101. if (parsedData.particleSystems) {
  27102. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27103. var parsedParticleSystem = parsedData.particleSystems[index];
  27104. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27105. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27106. }
  27107. }
  27108. }
  27109. return true;
  27110. }
  27111. catch (err) {
  27112. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27113. log = null;
  27114. throw err;
  27115. }
  27116. finally {
  27117. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27118. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27119. }
  27120. }
  27121. },
  27122. load: function (scene, data, rootUrl) {
  27123. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27124. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27125. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27126. // and avoid problems with multiple concurrent .babylon loads.
  27127. var log = "importScene has failed JSON parse";
  27128. try {
  27129. var parsedData = JSON.parse(data);
  27130. log = "";
  27131. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27132. // Scene
  27133. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27134. scene.autoClear = parsedData.autoClear;
  27135. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27136. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27137. if (parsedData.gravity) {
  27138. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27139. }
  27140. // Fog
  27141. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27142. scene.fogMode = parsedData.fogMode;
  27143. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27144. scene.fogStart = parsedData.fogStart;
  27145. scene.fogEnd = parsedData.fogEnd;
  27146. scene.fogDensity = parsedData.fogDensity;
  27147. log += "\tFog mode for scene: ";
  27148. switch (scene.fogMode) {
  27149. // getters not compiling, so using hardcoded
  27150. case 1:
  27151. log += "exp\n";
  27152. break;
  27153. case 2:
  27154. log += "exp2\n";
  27155. break;
  27156. case 3:
  27157. log += "linear\n";
  27158. break;
  27159. }
  27160. }
  27161. //Physics
  27162. if (parsedData.physicsEnabled) {
  27163. var physicsPlugin;
  27164. if (parsedData.physicsEngine === "cannon") {
  27165. physicsPlugin = new BABYLON.CannonJSPlugin();
  27166. }
  27167. else if (parsedData.physicsEngine === "oimo") {
  27168. physicsPlugin = new BABYLON.OimoJSPlugin();
  27169. }
  27170. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27171. //else - default engine, which is currently oimo
  27172. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27173. scene.enablePhysics(physicsGravity, physicsPlugin);
  27174. }
  27175. //collisions, if defined. otherwise, default is true
  27176. if (parsedData.collisionsEnabled != undefined) {
  27177. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27178. }
  27179. scene.workerCollisions = !!parsedData.workerCollisions;
  27180. var index;
  27181. var cache;
  27182. // Lights
  27183. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27184. var parsedLight = parsedData.lights[index];
  27185. var light = BABYLON.Light.Parse(parsedLight, scene);
  27186. log += (index === 0 ? "\n\tLights:" : "");
  27187. log += "\n\t\t" + light.toString(fullDetails);
  27188. }
  27189. // Animations
  27190. if (parsedData.animations) {
  27191. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27192. var parsedAnimation = parsedData.animations[index];
  27193. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27194. scene.animations.push(animation);
  27195. log += (index === 0 ? "\n\tAnimations:" : "");
  27196. log += "\n\t\t" + animation.toString(fullDetails);
  27197. }
  27198. }
  27199. if (parsedData.autoAnimate) {
  27200. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27201. }
  27202. // Materials
  27203. if (parsedData.materials) {
  27204. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27205. var parsedMaterial = parsedData.materials[index];
  27206. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27207. log += (index === 0 ? "\n\tMaterials:" : "");
  27208. log += "\n\t\t" + mat.toString(fullDetails);
  27209. }
  27210. }
  27211. if (parsedData.multiMaterials) {
  27212. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27213. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27214. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27215. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27216. log += "\n\t\t" + mmat.toString(fullDetails);
  27217. }
  27218. }
  27219. // Skeletons
  27220. if (parsedData.skeletons) {
  27221. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27222. var parsedSkeleton = parsedData.skeletons[index];
  27223. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27224. log += (index === 0 ? "\n\tSkeletons:" : "");
  27225. log += "\n\t\t" + skeleton.toString(fullDetails);
  27226. }
  27227. }
  27228. // Geometries
  27229. var geometries = parsedData.geometries;
  27230. if (geometries) {
  27231. // Boxes
  27232. var boxes = geometries.boxes;
  27233. if (boxes) {
  27234. for (index = 0, cache = boxes.length; index < cache; index++) {
  27235. var parsedBox = boxes[index];
  27236. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27237. }
  27238. }
  27239. // Spheres
  27240. var spheres = geometries.spheres;
  27241. if (spheres) {
  27242. for (index = 0, cache = spheres.length; index < cache; index++) {
  27243. var parsedSphere = spheres[index];
  27244. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27245. }
  27246. }
  27247. // Cylinders
  27248. var cylinders = geometries.cylinders;
  27249. if (cylinders) {
  27250. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27251. var parsedCylinder = cylinders[index];
  27252. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27253. }
  27254. }
  27255. // Toruses
  27256. var toruses = geometries.toruses;
  27257. if (toruses) {
  27258. for (index = 0, cache = toruses.length; index < cache; index++) {
  27259. var parsedTorus = toruses[index];
  27260. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27261. }
  27262. }
  27263. // Grounds
  27264. var grounds = geometries.grounds;
  27265. if (grounds) {
  27266. for (index = 0, cache = grounds.length; index < cache; index++) {
  27267. var parsedGround = grounds[index];
  27268. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27269. }
  27270. }
  27271. // Planes
  27272. var planes = geometries.planes;
  27273. if (planes) {
  27274. for (index = 0, cache = planes.length; index < cache; index++) {
  27275. var parsedPlane = planes[index];
  27276. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27277. }
  27278. }
  27279. // TorusKnots
  27280. var torusKnots = geometries.torusKnots;
  27281. if (torusKnots) {
  27282. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27283. var parsedTorusKnot = torusKnots[index];
  27284. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27285. }
  27286. }
  27287. // VertexData
  27288. var vertexData = geometries.vertexData;
  27289. if (vertexData) {
  27290. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27291. var parsedVertexData = vertexData[index];
  27292. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27293. }
  27294. }
  27295. }
  27296. // Meshes
  27297. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27298. var parsedMesh = parsedData.meshes[index];
  27299. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27300. log += (index === 0 ? "\n\tMeshes:" : "");
  27301. log += "\n\t\t" + mesh.toString(fullDetails);
  27302. }
  27303. // Cameras
  27304. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27305. var parsedCamera = parsedData.cameras[index];
  27306. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27307. log += (index === 0 ? "\n\tCameras:" : "");
  27308. log += "\n\t\t" + camera.toString(fullDetails);
  27309. }
  27310. if (parsedData.activeCameraID) {
  27311. scene.setActiveCameraByID(parsedData.activeCameraID);
  27312. }
  27313. // Browsing all the graph to connect the dots
  27314. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27315. var camera = scene.cameras[index];
  27316. if (camera._waitingParentId) {
  27317. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27318. camera._waitingParentId = undefined;
  27319. }
  27320. }
  27321. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27322. var light = scene.lights[index];
  27323. if (light._waitingParentId) {
  27324. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27325. light._waitingParentId = undefined;
  27326. }
  27327. }
  27328. // Sounds
  27329. var loadedSounds = [];
  27330. var loadedSound;
  27331. if (BABYLON.AudioEngine && parsedData.sounds) {
  27332. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27333. var parsedSound = parsedData.sounds[index];
  27334. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27335. if (!parsedSound.url)
  27336. parsedSound.url = parsedSound.name;
  27337. if (!loadedSounds[parsedSound.url]) {
  27338. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27339. loadedSounds[parsedSound.url] = loadedSound;
  27340. }
  27341. else {
  27342. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27343. }
  27344. }
  27345. else {
  27346. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27347. }
  27348. }
  27349. }
  27350. loadedSounds = [];
  27351. // Connect parents & children and parse actions
  27352. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27353. var mesh = scene.meshes[index];
  27354. if (mesh._waitingParentId) {
  27355. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27356. mesh._waitingParentId = undefined;
  27357. }
  27358. if (mesh._waitingActions) {
  27359. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27360. mesh._waitingActions = undefined;
  27361. }
  27362. }
  27363. // freeze world matrix application
  27364. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27365. var currentMesh = scene.meshes[index];
  27366. if (currentMesh._waitingFreezeWorldMatrix) {
  27367. currentMesh.freezeWorldMatrix();
  27368. currentMesh._waitingFreezeWorldMatrix = undefined;
  27369. }
  27370. else {
  27371. currentMesh.computeWorldMatrix(true);
  27372. }
  27373. }
  27374. // Particles Systems
  27375. if (parsedData.particleSystems) {
  27376. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27377. var parsedParticleSystem = parsedData.particleSystems[index];
  27378. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27379. }
  27380. }
  27381. // Lens flares
  27382. if (parsedData.lensFlareSystems) {
  27383. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27384. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27385. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27386. }
  27387. }
  27388. // Shadows
  27389. if (parsedData.shadowGenerators) {
  27390. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27391. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27392. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27393. }
  27394. }
  27395. // Actions (scene)
  27396. if (parsedData.actions) {
  27397. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27398. }
  27399. // Finish
  27400. return true;
  27401. }
  27402. catch (err) {
  27403. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  27404. log = null;
  27405. throw err;
  27406. }
  27407. finally {
  27408. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27409. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27410. }
  27411. }
  27412. }
  27413. });
  27414. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27415. })(BABYLON || (BABYLON = {}));
  27416. var BABYLON;
  27417. (function (BABYLON) {
  27418. var SpriteManager = (function () {
  27419. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  27420. if (epsilon === void 0) { epsilon = 0.01; }
  27421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27422. this.name = name;
  27423. this.sprites = new Array();
  27424. this.renderingGroupId = 0;
  27425. this.layerMask = 0x0FFFFFFF;
  27426. this.fogEnabled = true;
  27427. this.isPickable = false;
  27428. /**
  27429. * An event triggered when the manager is disposed.
  27430. * @type {BABYLON.Observable}
  27431. */
  27432. this.onDisposeObservable = new BABYLON.Observable();
  27433. this._vertexBuffers = {};
  27434. this._capacity = capacity;
  27435. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  27436. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27437. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27438. if (cellSize.width && cellSize.height) {
  27439. this.cellWidth = cellSize.width;
  27440. this.cellHeight = cellSize.height;
  27441. }
  27442. else if (cellSize !== undefined) {
  27443. this.cellWidth = cellSize;
  27444. this.cellHeight = cellSize;
  27445. }
  27446. else {
  27447. return;
  27448. }
  27449. this._scene = scene;
  27450. this._scene.spriteManagers.push(this);
  27451. var indices = [];
  27452. var index = 0;
  27453. for (var count = 0; count < capacity; count++) {
  27454. indices.push(index);
  27455. indices.push(index + 1);
  27456. indices.push(index + 2);
  27457. indices.push(index);
  27458. indices.push(index + 2);
  27459. indices.push(index + 3);
  27460. index += 4;
  27461. }
  27462. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27463. // VBO
  27464. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  27465. this._vertexData = new Float32Array(capacity * 16 * 4);
  27466. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  27467. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  27468. var options = this._buffer.createVertexBuffer("options", 4, 4);
  27469. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  27470. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  27471. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27472. this._vertexBuffers["options"] = options;
  27473. this._vertexBuffers["cellInfo"] = cellInfo;
  27474. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27475. // Effects
  27476. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  27477. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  27478. }
  27479. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  27480. set: function (callback) {
  27481. if (this._onDisposeObserver) {
  27482. this.onDisposeObservable.remove(this._onDisposeObserver);
  27483. }
  27484. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27485. },
  27486. enumerable: true,
  27487. configurable: true
  27488. });
  27489. Object.defineProperty(SpriteManager.prototype, "texture", {
  27490. get: function () {
  27491. return this._spriteTexture;
  27492. },
  27493. set: function (value) {
  27494. this._spriteTexture = value;
  27495. },
  27496. enumerable: true,
  27497. configurable: true
  27498. });
  27499. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  27500. var arrayOffset = index * 16;
  27501. if (offsetX === 0)
  27502. offsetX = this._epsilon;
  27503. else if (offsetX === 1)
  27504. offsetX = 1 - this._epsilon;
  27505. if (offsetY === 0)
  27506. offsetY = this._epsilon;
  27507. else if (offsetY === 1)
  27508. offsetY = 1 - this._epsilon;
  27509. this._vertexData[arrayOffset] = sprite.position.x;
  27510. this._vertexData[arrayOffset + 1] = sprite.position.y;
  27511. this._vertexData[arrayOffset + 2] = sprite.position.z;
  27512. this._vertexData[arrayOffset + 3] = sprite.angle;
  27513. this._vertexData[arrayOffset + 4] = sprite.width;
  27514. this._vertexData[arrayOffset + 5] = sprite.height;
  27515. this._vertexData[arrayOffset + 6] = offsetX;
  27516. this._vertexData[arrayOffset + 7] = offsetY;
  27517. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  27518. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  27519. var offset = (sprite.cellIndex / rowSize) >> 0;
  27520. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  27521. this._vertexData[arrayOffset + 11] = offset;
  27522. // Color
  27523. this._vertexData[arrayOffset + 12] = sprite.color.r;
  27524. this._vertexData[arrayOffset + 13] = sprite.color.g;
  27525. this._vertexData[arrayOffset + 14] = sprite.color.b;
  27526. this._vertexData[arrayOffset + 15] = sprite.color.a;
  27527. };
  27528. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  27529. var count = Math.min(this._capacity, this.sprites.length);
  27530. var min = BABYLON.Vector3.Zero();
  27531. var max = BABYLON.Vector3.Zero();
  27532. var distance = Number.MAX_VALUE;
  27533. var currentSprite;
  27534. var cameraSpacePosition = BABYLON.Vector3.Zero();
  27535. var cameraView = camera.getViewMatrix();
  27536. for (var index = 0; index < count; index++) {
  27537. var sprite = this.sprites[index];
  27538. if (!sprite) {
  27539. continue;
  27540. }
  27541. if (predicate) {
  27542. if (!predicate(sprite)) {
  27543. continue;
  27544. }
  27545. }
  27546. else if (!sprite.isPickable) {
  27547. continue;
  27548. }
  27549. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  27550. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  27551. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  27552. if (ray.intersectsBoxMinMax(min, max)) {
  27553. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  27554. if (distance > currentDistance) {
  27555. distance = currentDistance;
  27556. currentSprite = sprite;
  27557. if (fastCheck) {
  27558. break;
  27559. }
  27560. }
  27561. }
  27562. }
  27563. if (currentSprite) {
  27564. var result = new BABYLON.PickingInfo();
  27565. result.hit = true;
  27566. result.pickedSprite = currentSprite;
  27567. result.distance = distance;
  27568. return result;
  27569. }
  27570. return null;
  27571. };
  27572. SpriteManager.prototype.render = function () {
  27573. // Check
  27574. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  27575. return;
  27576. var engine = this._scene.getEngine();
  27577. var baseSize = this._spriteTexture.getBaseSize();
  27578. // Sprites
  27579. var deltaTime = engine.getDeltaTime();
  27580. var max = Math.min(this._capacity, this.sprites.length);
  27581. var rowSize = baseSize.width / this.cellWidth;
  27582. var offset = 0;
  27583. for (var index = 0; index < max; index++) {
  27584. var sprite = this.sprites[index];
  27585. if (!sprite) {
  27586. continue;
  27587. }
  27588. sprite._animate(deltaTime);
  27589. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  27590. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  27591. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  27592. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  27593. }
  27594. this._buffer.update(this._vertexData);
  27595. // Render
  27596. var effect = this._effectBase;
  27597. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27598. effect = this._effectFog;
  27599. }
  27600. engine.enableEffect(effect);
  27601. var viewMatrix = this._scene.getViewMatrix();
  27602. effect.setTexture("diffuseSampler", this._spriteTexture);
  27603. effect.setMatrix("view", viewMatrix);
  27604. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27605. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  27606. // Fog
  27607. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27608. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  27609. effect.setColor3("vFogColor", this._scene.fogColor);
  27610. }
  27611. // VBOs
  27612. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27613. // Draw order
  27614. engine.setDepthFunctionToLessOrEqual();
  27615. effect.setBool("alphaTest", true);
  27616. engine.setColorWrite(false);
  27617. engine.draw(true, 0, max * 6);
  27618. engine.setColorWrite(true);
  27619. effect.setBool("alphaTest", false);
  27620. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27621. engine.draw(true, 0, max * 6);
  27622. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27623. };
  27624. SpriteManager.prototype.dispose = function () {
  27625. if (this._buffer) {
  27626. this._buffer.dispose();
  27627. this._buffer = null;
  27628. }
  27629. if (this._indexBuffer) {
  27630. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27631. this._indexBuffer = null;
  27632. }
  27633. if (this._spriteTexture) {
  27634. this._spriteTexture.dispose();
  27635. this._spriteTexture = null;
  27636. }
  27637. // Remove from scene
  27638. var index = this._scene.spriteManagers.indexOf(this);
  27639. this._scene.spriteManagers.splice(index, 1);
  27640. // Callback
  27641. this.onDisposeObservable.notifyObservers(this);
  27642. this.onDisposeObservable.clear();
  27643. };
  27644. return SpriteManager;
  27645. }());
  27646. BABYLON.SpriteManager = SpriteManager;
  27647. })(BABYLON || (BABYLON = {}));
  27648. var BABYLON;
  27649. (function (BABYLON) {
  27650. var Sprite = (function () {
  27651. function Sprite(name, manager) {
  27652. this.name = name;
  27653. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27654. this.width = 1.0;
  27655. this.height = 1.0;
  27656. this.angle = 0;
  27657. this.cellIndex = 0;
  27658. this.invertU = 0;
  27659. this.invertV = 0;
  27660. this.animations = new Array();
  27661. this.isPickable = false;
  27662. this._animationStarted = false;
  27663. this._loopAnimation = false;
  27664. this._fromIndex = 0;
  27665. this._toIndex = 0;
  27666. this._delay = 0;
  27667. this._direction = 1;
  27668. this._frameCount = 0;
  27669. this._time = 0;
  27670. this._manager = manager;
  27671. this._manager.sprites.push(this);
  27672. this.position = BABYLON.Vector3.Zero();
  27673. }
  27674. Object.defineProperty(Sprite.prototype, "size", {
  27675. get: function () {
  27676. return this.width;
  27677. },
  27678. set: function (value) {
  27679. this.width = value;
  27680. this.height = value;
  27681. },
  27682. enumerable: true,
  27683. configurable: true
  27684. });
  27685. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  27686. this._fromIndex = from;
  27687. this._toIndex = to;
  27688. this._loopAnimation = loop;
  27689. this._delay = delay;
  27690. this._animationStarted = true;
  27691. this._direction = from < to ? 1 : -1;
  27692. this.cellIndex = from;
  27693. this._time = 0;
  27694. this._onAnimationEnd = onAnimationEnd;
  27695. };
  27696. Sprite.prototype.stopAnimation = function () {
  27697. this._animationStarted = false;
  27698. };
  27699. Sprite.prototype._animate = function (deltaTime) {
  27700. if (!this._animationStarted)
  27701. return;
  27702. this._time += deltaTime;
  27703. if (this._time > this._delay) {
  27704. this._time = this._time % this._delay;
  27705. this.cellIndex += this._direction;
  27706. if (this.cellIndex === this._toIndex) {
  27707. if (this._loopAnimation) {
  27708. this.cellIndex = this._fromIndex;
  27709. }
  27710. else {
  27711. this._animationStarted = false;
  27712. if (this._onAnimationEnd) {
  27713. this._onAnimationEnd();
  27714. }
  27715. if (this.disposeWhenFinishedAnimating) {
  27716. this.dispose();
  27717. }
  27718. }
  27719. }
  27720. }
  27721. };
  27722. Sprite.prototype.dispose = function () {
  27723. for (var i = 0; i < this._manager.sprites.length; i++) {
  27724. if (this._manager.sprites[i] == this) {
  27725. this._manager.sprites.splice(i, 1);
  27726. }
  27727. }
  27728. };
  27729. return Sprite;
  27730. }());
  27731. BABYLON.Sprite = Sprite;
  27732. })(BABYLON || (BABYLON = {}));
  27733. var BABYLON;
  27734. (function (BABYLON) {
  27735. var Layer = (function () {
  27736. function Layer(name, imgUrl, scene, isBackground, color) {
  27737. this.name = name;
  27738. this.scale = new BABYLON.Vector2(1, 1);
  27739. this.offset = new BABYLON.Vector2(0, 0);
  27740. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  27741. this._vertexBuffers = {};
  27742. // Events
  27743. /**
  27744. * An event triggered when the layer is disposed.
  27745. * @type {BABYLON.Observable}
  27746. */
  27747. this.onDisposeObservable = new BABYLON.Observable();
  27748. /**
  27749. * An event triggered before rendering the scene
  27750. * @type {BABYLON.Observable}
  27751. */
  27752. this.onBeforeRenderObservable = new BABYLON.Observable();
  27753. /**
  27754. * An event triggered after rendering the scene
  27755. * @type {BABYLON.Observable}
  27756. */
  27757. this.onAfterRenderObservable = new BABYLON.Observable();
  27758. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  27759. this.isBackground = isBackground === undefined ? true : isBackground;
  27760. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  27761. this._scene = scene;
  27762. this._scene.layers.push(this);
  27763. var engine = scene.getEngine();
  27764. // VBO
  27765. var vertices = [];
  27766. vertices.push(1, 1);
  27767. vertices.push(-1, 1);
  27768. vertices.push(-1, -1);
  27769. vertices.push(1, -1);
  27770. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27771. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  27772. // Indices
  27773. var indices = [];
  27774. indices.push(0);
  27775. indices.push(1);
  27776. indices.push(2);
  27777. indices.push(0);
  27778. indices.push(2);
  27779. indices.push(3);
  27780. this._indexBuffer = engine.createIndexBuffer(indices);
  27781. // Effects
  27782. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  27783. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  27784. }
  27785. Object.defineProperty(Layer.prototype, "onDispose", {
  27786. set: function (callback) {
  27787. if (this._onDisposeObserver) {
  27788. this.onDisposeObservable.remove(this._onDisposeObserver);
  27789. }
  27790. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27791. },
  27792. enumerable: true,
  27793. configurable: true
  27794. });
  27795. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  27796. set: function (callback) {
  27797. if (this._onBeforeRenderObserver) {
  27798. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27799. }
  27800. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27801. },
  27802. enumerable: true,
  27803. configurable: true
  27804. });
  27805. Object.defineProperty(Layer.prototype, "onAfterRender", {
  27806. set: function (callback) {
  27807. if (this._onAfterRenderObserver) {
  27808. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27809. }
  27810. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27811. },
  27812. enumerable: true,
  27813. configurable: true
  27814. });
  27815. Layer.prototype.render = function () {
  27816. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  27817. // Check
  27818. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  27819. return;
  27820. var engine = this._scene.getEngine();
  27821. this.onBeforeRenderObservable.notifyObservers(this);
  27822. // Render
  27823. engine.enableEffect(currentEffect);
  27824. engine.setState(false);
  27825. // Texture
  27826. currentEffect.setTexture("textureSampler", this.texture);
  27827. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  27828. // Color
  27829. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  27830. // Scale / offset
  27831. currentEffect.setVector2("offset", this.offset);
  27832. currentEffect.setVector2("scale", this.scale);
  27833. // VBOs
  27834. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  27835. // Draw order
  27836. if (!this.alphaTest) {
  27837. engine.setAlphaMode(this.alphaBlendingMode);
  27838. engine.draw(true, 0, 6);
  27839. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27840. }
  27841. else {
  27842. engine.draw(true, 0, 6);
  27843. }
  27844. this.onAfterRenderObservable.notifyObservers(this);
  27845. };
  27846. Layer.prototype.dispose = function () {
  27847. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27848. if (vertexBuffer) {
  27849. vertexBuffer.dispose();
  27850. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27851. }
  27852. if (this._indexBuffer) {
  27853. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27854. this._indexBuffer = null;
  27855. }
  27856. if (this.texture) {
  27857. this.texture.dispose();
  27858. this.texture = null;
  27859. }
  27860. // Remove from scene
  27861. var index = this._scene.layers.indexOf(this);
  27862. this._scene.layers.splice(index, 1);
  27863. // Callback
  27864. this.onDisposeObservable.notifyObservers(this);
  27865. this.onDisposeObservable.clear();
  27866. this.onAfterRenderObservable.clear();
  27867. this.onBeforeRenderObservable.clear();
  27868. };
  27869. return Layer;
  27870. }());
  27871. BABYLON.Layer = Layer;
  27872. })(BABYLON || (BABYLON = {}));
  27873. var BABYLON;
  27874. (function (BABYLON) {
  27875. var Particle = (function () {
  27876. function Particle() {
  27877. this.position = BABYLON.Vector3.Zero();
  27878. this.direction = BABYLON.Vector3.Zero();
  27879. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27880. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27881. this.lifeTime = 1.0;
  27882. this.age = 0;
  27883. this.size = 0;
  27884. this.angle = 0;
  27885. this.angularSpeed = 0;
  27886. }
  27887. Particle.prototype.copyTo = function (other) {
  27888. other.position.copyFrom(this.position);
  27889. other.direction.copyFrom(this.direction);
  27890. other.color.copyFrom(this.color);
  27891. other.colorStep.copyFrom(this.colorStep);
  27892. other.lifeTime = this.lifeTime;
  27893. other.age = this.age;
  27894. other.size = this.size;
  27895. other.angle = this.angle;
  27896. other.angularSpeed = this.angularSpeed;
  27897. };
  27898. return Particle;
  27899. }());
  27900. BABYLON.Particle = Particle;
  27901. })(BABYLON || (BABYLON = {}));
  27902. var BABYLON;
  27903. (function (BABYLON) {
  27904. var randomNumber = function (min, max) {
  27905. if (min === max) {
  27906. return (min);
  27907. }
  27908. var random = Math.random();
  27909. return ((random * (max - min)) + min);
  27910. };
  27911. var ParticleSystem = (function () {
  27912. function ParticleSystem(name, capacity, scene, customEffect) {
  27913. var _this = this;
  27914. this.name = name;
  27915. // Members
  27916. this.animations = [];
  27917. this.renderingGroupId = 0;
  27918. this.emitter = null;
  27919. this.emitRate = 10;
  27920. this.manualEmitCount = -1;
  27921. this.updateSpeed = 0.01;
  27922. this.targetStopDuration = 0;
  27923. this.disposeOnStop = false;
  27924. this.minEmitPower = 1;
  27925. this.maxEmitPower = 1;
  27926. this.minLifeTime = 1;
  27927. this.maxLifeTime = 1;
  27928. this.minSize = 1;
  27929. this.maxSize = 1;
  27930. this.minAngularSpeed = 0;
  27931. this.maxAngularSpeed = 0;
  27932. this.layerMask = 0x0FFFFFFF;
  27933. /**
  27934. * An event triggered when the system is disposed.
  27935. * @type {BABYLON.Observable}
  27936. */
  27937. this.onDisposeObservable = new BABYLON.Observable();
  27938. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27939. this.forceDepthWrite = false;
  27940. this.gravity = BABYLON.Vector3.Zero();
  27941. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27942. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27943. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27944. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27945. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27946. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27947. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27948. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27949. this.particles = new Array();
  27950. this._stockParticles = new Array();
  27951. this._newPartsExcess = 0;
  27952. this._vertexBuffers = {};
  27953. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27954. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27955. this._scaledDirection = BABYLON.Vector3.Zero();
  27956. this._scaledGravity = BABYLON.Vector3.Zero();
  27957. this._currentRenderId = -1;
  27958. this._started = false;
  27959. this._stopped = false;
  27960. this._actualFrame = 0;
  27961. this.id = name;
  27962. this._capacity = capacity;
  27963. this._scene = scene;
  27964. this._customEffect = customEffect;
  27965. scene.particleSystems.push(this);
  27966. var indices = [];
  27967. var index = 0;
  27968. for (var count = 0; count < capacity; count++) {
  27969. indices.push(index);
  27970. indices.push(index + 1);
  27971. indices.push(index + 2);
  27972. indices.push(index);
  27973. indices.push(index + 2);
  27974. indices.push(index + 3);
  27975. index += 4;
  27976. }
  27977. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27978. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  27979. this._vertexData = new Float32Array(capacity * 11 * 4);
  27980. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  27981. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  27982. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  27983. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  27984. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27985. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27986. this._vertexBuffers["options"] = options;
  27987. // Default behaviors
  27988. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  27989. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  27990. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  27991. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  27992. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  27993. };
  27994. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  27995. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  27996. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  27997. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  27998. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  27999. };
  28000. this.updateFunction = function (particles) {
  28001. for (var index = 0; index < particles.length; index++) {
  28002. var particle = particles[index];
  28003. particle.age += _this._scaledUpdateSpeed;
  28004. if (particle.age >= particle.lifeTime) {
  28005. _this.recycleParticle(particle);
  28006. index--;
  28007. continue;
  28008. }
  28009. else {
  28010. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  28011. particle.color.addInPlace(_this._scaledColorStep);
  28012. if (particle.color.a < 0)
  28013. particle.color.a = 0;
  28014. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  28015. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  28016. particle.position.addInPlace(_this._scaledDirection);
  28017. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  28018. particle.direction.addInPlace(_this._scaledGravity);
  28019. }
  28020. }
  28021. };
  28022. }
  28023. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  28024. set: function (callback) {
  28025. if (this._onDisposeObserver) {
  28026. this.onDisposeObservable.remove(this._onDisposeObserver);
  28027. }
  28028. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28029. },
  28030. enumerable: true,
  28031. configurable: true
  28032. });
  28033. ParticleSystem.prototype.recycleParticle = function (particle) {
  28034. var lastParticle = this.particles.pop();
  28035. if (lastParticle !== particle) {
  28036. lastParticle.copyTo(particle);
  28037. this._stockParticles.push(lastParticle);
  28038. }
  28039. };
  28040. ParticleSystem.prototype.getCapacity = function () {
  28041. return this._capacity;
  28042. };
  28043. ParticleSystem.prototype.isAlive = function () {
  28044. return this._alive;
  28045. };
  28046. ParticleSystem.prototype.isStarted = function () {
  28047. return this._started;
  28048. };
  28049. ParticleSystem.prototype.start = function () {
  28050. this._started = true;
  28051. this._stopped = false;
  28052. this._actualFrame = 0;
  28053. };
  28054. ParticleSystem.prototype.stop = function () {
  28055. this._stopped = true;
  28056. };
  28057. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28058. var offset = index * 11;
  28059. this._vertexData[offset] = particle.position.x;
  28060. this._vertexData[offset + 1] = particle.position.y;
  28061. this._vertexData[offset + 2] = particle.position.z;
  28062. this._vertexData[offset + 3] = particle.color.r;
  28063. this._vertexData[offset + 4] = particle.color.g;
  28064. this._vertexData[offset + 5] = particle.color.b;
  28065. this._vertexData[offset + 6] = particle.color.a;
  28066. this._vertexData[offset + 7] = particle.angle;
  28067. this._vertexData[offset + 8] = particle.size;
  28068. this._vertexData[offset + 9] = offsetX;
  28069. this._vertexData[offset + 10] = offsetY;
  28070. };
  28071. ParticleSystem.prototype._update = function (newParticles) {
  28072. // Update current
  28073. this._alive = this.particles.length > 0;
  28074. this.updateFunction(this.particles);
  28075. // Add new ones
  28076. var worldMatrix;
  28077. if (this.emitter.position) {
  28078. worldMatrix = this.emitter.getWorldMatrix();
  28079. }
  28080. else {
  28081. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28082. }
  28083. var particle;
  28084. for (var index = 0; index < newParticles; index++) {
  28085. if (this.particles.length === this._capacity) {
  28086. break;
  28087. }
  28088. if (this._stockParticles.length !== 0) {
  28089. particle = this._stockParticles.pop();
  28090. particle.age = 0;
  28091. }
  28092. else {
  28093. particle = new BABYLON.Particle();
  28094. }
  28095. this.particles.push(particle);
  28096. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28097. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28098. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28099. particle.size = randomNumber(this.minSize, this.maxSize);
  28100. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28101. this.startPositionFunction(worldMatrix, particle.position, particle);
  28102. var step = randomNumber(0, 1.0);
  28103. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28104. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28105. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28106. }
  28107. };
  28108. ParticleSystem.prototype._getEffect = function () {
  28109. if (this._customEffect) {
  28110. return this._customEffect;
  28111. }
  28112. ;
  28113. var defines = [];
  28114. if (this._scene.clipPlane) {
  28115. defines.push("#define CLIPPLANE");
  28116. }
  28117. // Effect
  28118. var join = defines.join("\n");
  28119. if (this._cachedDefines !== join) {
  28120. this._cachedDefines = join;
  28121. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28122. }
  28123. return this._effect;
  28124. };
  28125. ParticleSystem.prototype.animate = function () {
  28126. if (!this._started)
  28127. return;
  28128. var effect = this._getEffect();
  28129. // Check
  28130. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28131. return;
  28132. if (this._currentRenderId === this._scene.getRenderId()) {
  28133. return;
  28134. }
  28135. this._currentRenderId = this._scene.getRenderId();
  28136. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28137. // determine the number of particles we need to create
  28138. var newParticles;
  28139. if (this.manualEmitCount > -1) {
  28140. newParticles = this.manualEmitCount;
  28141. this._newPartsExcess = 0;
  28142. this.manualEmitCount = 0;
  28143. }
  28144. else {
  28145. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28146. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28147. }
  28148. if (this._newPartsExcess > 1.0) {
  28149. newParticles += this._newPartsExcess >> 0;
  28150. this._newPartsExcess -= this._newPartsExcess >> 0;
  28151. }
  28152. this._alive = false;
  28153. if (!this._stopped) {
  28154. this._actualFrame += this._scaledUpdateSpeed;
  28155. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28156. this.stop();
  28157. }
  28158. else {
  28159. newParticles = 0;
  28160. }
  28161. this._update(newParticles);
  28162. // Stopped?
  28163. if (this._stopped) {
  28164. if (!this._alive) {
  28165. this._started = false;
  28166. if (this.disposeOnStop) {
  28167. this._scene._toBeDisposed.push(this);
  28168. }
  28169. }
  28170. }
  28171. // Update VBO
  28172. var offset = 0;
  28173. for (var index = 0; index < this.particles.length; index++) {
  28174. var particle = this.particles[index];
  28175. this._appendParticleVertex(offset++, particle, 0, 0);
  28176. this._appendParticleVertex(offset++, particle, 1, 0);
  28177. this._appendParticleVertex(offset++, particle, 1, 1);
  28178. this._appendParticleVertex(offset++, particle, 0, 1);
  28179. }
  28180. this._vertexBuffer.update(this._vertexData);
  28181. };
  28182. ParticleSystem.prototype.render = function () {
  28183. var effect = this._getEffect();
  28184. // Check
  28185. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28186. return 0;
  28187. var engine = this._scene.getEngine();
  28188. // Render
  28189. engine.enableEffect(effect);
  28190. engine.setState(false);
  28191. var viewMatrix = this._scene.getViewMatrix();
  28192. effect.setTexture("diffuseSampler", this.particleTexture);
  28193. effect.setMatrix("view", viewMatrix);
  28194. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28195. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28196. if (this._scene.clipPlane) {
  28197. var clipPlane = this._scene.clipPlane;
  28198. var invView = viewMatrix.clone();
  28199. invView.invert();
  28200. effect.setMatrix("invView", invView);
  28201. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28202. }
  28203. // VBOs
  28204. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28205. // Draw order
  28206. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28207. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28208. }
  28209. else {
  28210. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28211. }
  28212. if (this.forceDepthWrite) {
  28213. engine.setDepthWrite(true);
  28214. }
  28215. engine.draw(true, 0, this.particles.length * 6);
  28216. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28217. return this.particles.length;
  28218. };
  28219. ParticleSystem.prototype.dispose = function () {
  28220. if (this._vertexBuffer) {
  28221. this._vertexBuffer.dispose();
  28222. this._vertexBuffer = null;
  28223. }
  28224. if (this._indexBuffer) {
  28225. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28226. this._indexBuffer = null;
  28227. }
  28228. if (this.particleTexture) {
  28229. this.particleTexture.dispose();
  28230. this.particleTexture = null;
  28231. }
  28232. // Remove from scene
  28233. var index = this._scene.particleSystems.indexOf(this);
  28234. this._scene.particleSystems.splice(index, 1);
  28235. // Callback
  28236. this.onDisposeObservable.notifyObservers(this);
  28237. this.onDisposeObservable.clear();
  28238. };
  28239. // Clone
  28240. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28241. var result = new ParticleSystem(name, this._capacity, this._scene);
  28242. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28243. if (newEmitter === undefined) {
  28244. newEmitter = this.emitter;
  28245. }
  28246. result.emitter = newEmitter;
  28247. if (this.particleTexture) {
  28248. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28249. }
  28250. result.start();
  28251. return result;
  28252. };
  28253. ParticleSystem.prototype.serialize = function () {
  28254. var serializationObject = {};
  28255. serializationObject.name = this.name;
  28256. serializationObject.id = this.id;
  28257. // Emitter
  28258. if (this.emitter.position) {
  28259. serializationObject.emitterId = this.emitter.id;
  28260. }
  28261. else {
  28262. serializationObject.emitter = this.emitter.asArray();
  28263. }
  28264. serializationObject.capacity = this.getCapacity();
  28265. if (this.particleTexture) {
  28266. serializationObject.textureName = this.particleTexture.name;
  28267. }
  28268. // Animations
  28269. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28270. // Particle system
  28271. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28272. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28273. serializationObject.minSize = this.minSize;
  28274. serializationObject.maxSize = this.maxSize;
  28275. serializationObject.minEmitPower = this.minEmitPower;
  28276. serializationObject.maxEmitPower = this.maxEmitPower;
  28277. serializationObject.minLifeTime = this.minLifeTime;
  28278. serializationObject.maxLifeTime = this.maxLifeTime;
  28279. serializationObject.emitRate = this.emitRate;
  28280. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28281. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28282. serializationObject.gravity = this.gravity.asArray();
  28283. serializationObject.direction1 = this.direction1.asArray();
  28284. serializationObject.direction2 = this.direction2.asArray();
  28285. serializationObject.color1 = this.color1.asArray();
  28286. serializationObject.color2 = this.color2.asArray();
  28287. serializationObject.colorDead = this.colorDead.asArray();
  28288. serializationObject.updateSpeed = this.updateSpeed;
  28289. serializationObject.targetStopDuration = this.targetStopDuration;
  28290. serializationObject.textureMask = this.textureMask.asArray();
  28291. serializationObject.blendMode = this.blendMode;
  28292. return serializationObject;
  28293. };
  28294. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28295. var name = parsedParticleSystem.name;
  28296. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28297. if (parsedParticleSystem.id) {
  28298. particleSystem.id = parsedParticleSystem.id;
  28299. }
  28300. // Texture
  28301. if (parsedParticleSystem.textureName) {
  28302. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28303. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28304. }
  28305. // Emitter
  28306. if (parsedParticleSystem.emitterId) {
  28307. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28308. }
  28309. else {
  28310. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28311. }
  28312. // Animations
  28313. if (parsedParticleSystem.animations) {
  28314. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28315. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28316. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28317. }
  28318. }
  28319. if (parsedParticleSystem.autoAnimate) {
  28320. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28321. }
  28322. // Particle system
  28323. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28324. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28325. particleSystem.minSize = parsedParticleSystem.minSize;
  28326. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28327. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28328. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28329. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28330. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28331. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28332. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28333. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28334. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28335. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28336. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28337. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28338. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28339. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28340. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28341. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28342. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28343. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28344. if (!parsedParticleSystem.preventAutoStart) {
  28345. particleSystem.start();
  28346. }
  28347. return particleSystem;
  28348. };
  28349. // Statics
  28350. ParticleSystem.BLENDMODE_ONEONE = 0;
  28351. ParticleSystem.BLENDMODE_STANDARD = 1;
  28352. return ParticleSystem;
  28353. }());
  28354. BABYLON.ParticleSystem = ParticleSystem;
  28355. })(BABYLON || (BABYLON = {}));
  28356. var BABYLON;
  28357. (function (BABYLON) {
  28358. var AnimationRange = (function () {
  28359. function AnimationRange(name, from, to) {
  28360. this.name = name;
  28361. this.from = from;
  28362. this.to = to;
  28363. }
  28364. AnimationRange.prototype.clone = function () {
  28365. return new AnimationRange(this.name, this.from, this.to);
  28366. };
  28367. return AnimationRange;
  28368. }());
  28369. BABYLON.AnimationRange = AnimationRange;
  28370. /**
  28371. * Composed of a frame, and an action function
  28372. */
  28373. var AnimationEvent = (function () {
  28374. function AnimationEvent(frame, action, onlyOnce) {
  28375. this.frame = frame;
  28376. this.action = action;
  28377. this.onlyOnce = onlyOnce;
  28378. this.isDone = false;
  28379. }
  28380. return AnimationEvent;
  28381. }());
  28382. BABYLON.AnimationEvent = AnimationEvent;
  28383. var PathCursor = (function () {
  28384. function PathCursor(path) {
  28385. this.path = path;
  28386. this._onchange = new Array();
  28387. this.value = 0;
  28388. this.animations = new Array();
  28389. }
  28390. PathCursor.prototype.getPoint = function () {
  28391. var point = this.path.getPointAtLengthPosition(this.value);
  28392. return new BABYLON.Vector3(point.x, 0, point.y);
  28393. };
  28394. PathCursor.prototype.moveAhead = function (step) {
  28395. if (step === void 0) { step = 0.002; }
  28396. this.move(step);
  28397. return this;
  28398. };
  28399. PathCursor.prototype.moveBack = function (step) {
  28400. if (step === void 0) { step = 0.002; }
  28401. this.move(-step);
  28402. return this;
  28403. };
  28404. PathCursor.prototype.move = function (step) {
  28405. if (Math.abs(step) > 1) {
  28406. throw "step size should be less than 1.";
  28407. }
  28408. this.value += step;
  28409. this.ensureLimits();
  28410. this.raiseOnChange();
  28411. return this;
  28412. };
  28413. PathCursor.prototype.ensureLimits = function () {
  28414. while (this.value > 1) {
  28415. this.value -= 1;
  28416. }
  28417. while (this.value < 0) {
  28418. this.value += 1;
  28419. }
  28420. return this;
  28421. };
  28422. // used by animation engine
  28423. PathCursor.prototype.markAsDirty = function (propertyName) {
  28424. this.ensureLimits();
  28425. this.raiseOnChange();
  28426. return this;
  28427. };
  28428. PathCursor.prototype.raiseOnChange = function () {
  28429. var _this = this;
  28430. this._onchange.forEach(function (f) { return f(_this); });
  28431. return this;
  28432. };
  28433. PathCursor.prototype.onchange = function (f) {
  28434. this._onchange.push(f);
  28435. return this;
  28436. };
  28437. return PathCursor;
  28438. }());
  28439. BABYLON.PathCursor = PathCursor;
  28440. var Animation = (function () {
  28441. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28442. this.name = name;
  28443. this.targetProperty = targetProperty;
  28444. this.framePerSecond = framePerSecond;
  28445. this.dataType = dataType;
  28446. this.loopMode = loopMode;
  28447. this.enableBlending = enableBlending;
  28448. this._offsetsCache = {};
  28449. this._highLimitsCache = {};
  28450. this._stopped = false;
  28451. this._blendingFactor = 0;
  28452. // The set of event that will be linked to this animation
  28453. this._events = new Array();
  28454. this.allowMatricesInterpolation = false;
  28455. this.blendingSpeed = 0.01;
  28456. this._ranges = {};
  28457. this.targetPropertyPath = targetProperty.split(".");
  28458. this.dataType = dataType;
  28459. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28460. }
  28461. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28462. var dataType = undefined;
  28463. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28464. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28465. }
  28466. else if (from instanceof BABYLON.Quaternion) {
  28467. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28468. }
  28469. else if (from instanceof BABYLON.Vector3) {
  28470. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28471. }
  28472. else if (from instanceof BABYLON.Vector2) {
  28473. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28474. }
  28475. else if (from instanceof BABYLON.Color3) {
  28476. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28477. }
  28478. else if (from instanceof BABYLON.Size) {
  28479. dataType = Animation.ANIMATIONTYPE_SIZE;
  28480. }
  28481. if (dataType == undefined) {
  28482. return null;
  28483. }
  28484. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28485. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28486. animation.setKeys(keys);
  28487. if (easingFunction !== undefined) {
  28488. animation.setEasingFunction(easingFunction);
  28489. }
  28490. return animation;
  28491. };
  28492. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28493. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28494. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28495. };
  28496. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28497. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28498. node.animations.push(animation);
  28499. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28500. };
  28501. // Methods
  28502. /**
  28503. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28504. */
  28505. Animation.prototype.toString = function (fullDetails) {
  28506. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28507. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28508. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28509. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28510. if (fullDetails) {
  28511. ret += ", Ranges: {";
  28512. var first = true;
  28513. for (var name in this._ranges) {
  28514. if (first) {
  28515. ret += ", ";
  28516. first = false;
  28517. }
  28518. ret += name;
  28519. }
  28520. ret += "}";
  28521. }
  28522. return ret;
  28523. };
  28524. /**
  28525. * Add an event to this animation.
  28526. */
  28527. Animation.prototype.addEvent = function (event) {
  28528. this._events.push(event);
  28529. };
  28530. /**
  28531. * Remove all events found at the given frame
  28532. * @param frame
  28533. */
  28534. Animation.prototype.removeEvents = function (frame) {
  28535. for (var index = 0; index < this._events.length; index++) {
  28536. if (this._events[index].frame === frame) {
  28537. this._events.splice(index, 1);
  28538. index--;
  28539. }
  28540. }
  28541. };
  28542. Animation.prototype.createRange = function (name, from, to) {
  28543. // check name not already in use; could happen for bones after serialized
  28544. if (!this._ranges[name]) {
  28545. this._ranges[name] = new AnimationRange(name, from, to);
  28546. }
  28547. };
  28548. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28549. if (deleteFrames === void 0) { deleteFrames = true; }
  28550. if (this._ranges[name]) {
  28551. if (deleteFrames) {
  28552. var from = this._ranges[name].from;
  28553. var to = this._ranges[name].to;
  28554. // this loop MUST go high to low for multiple splices to work
  28555. for (var key = this._keys.length - 1; key >= 0; key--) {
  28556. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28557. this._keys.splice(key, 1);
  28558. }
  28559. }
  28560. }
  28561. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28562. }
  28563. };
  28564. Animation.prototype.getRange = function (name) {
  28565. return this._ranges[name];
  28566. };
  28567. Animation.prototype.reset = function () {
  28568. this._offsetsCache = {};
  28569. this._highLimitsCache = {};
  28570. this.currentFrame = 0;
  28571. this._blendingFactor = 0;
  28572. this._originalBlendValue = null;
  28573. };
  28574. Animation.prototype.isStopped = function () {
  28575. return this._stopped;
  28576. };
  28577. Animation.prototype.getKeys = function () {
  28578. return this._keys;
  28579. };
  28580. Animation.prototype.getHighestFrame = function () {
  28581. var ret = 0;
  28582. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28583. if (ret < this._keys[key].frame) {
  28584. ret = this._keys[key].frame;
  28585. }
  28586. }
  28587. return ret;
  28588. };
  28589. Animation.prototype.getEasingFunction = function () {
  28590. return this._easingFunction;
  28591. };
  28592. Animation.prototype.setEasingFunction = function (easingFunction) {
  28593. this._easingFunction = easingFunction;
  28594. };
  28595. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28596. return startValue + (endValue - startValue) * gradient;
  28597. };
  28598. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28599. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28600. };
  28601. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28602. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28603. };
  28604. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28605. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28606. };
  28607. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28608. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28609. };
  28610. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28611. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28612. };
  28613. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28614. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28615. };
  28616. Animation.prototype.clone = function () {
  28617. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28618. if (this._keys) {
  28619. clone.setKeys(this._keys);
  28620. }
  28621. if (this._ranges) {
  28622. clone._ranges = {};
  28623. for (var name in this._ranges) {
  28624. clone._ranges[name] = this._ranges[name].clone();
  28625. }
  28626. }
  28627. return clone;
  28628. };
  28629. Animation.prototype.setKeys = function (values) {
  28630. this._keys = values.slice(0);
  28631. this._offsetsCache = {};
  28632. this._highLimitsCache = {};
  28633. };
  28634. Animation.prototype._getKeyValue = function (value) {
  28635. if (typeof value === "function") {
  28636. return value();
  28637. }
  28638. return value;
  28639. };
  28640. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28641. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28642. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28643. }
  28644. this.currentFrame = currentFrame;
  28645. // Try to get a hash to find the right key
  28646. 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));
  28647. if (this._keys[startKey].frame >= currentFrame) {
  28648. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  28649. startKey--;
  28650. }
  28651. }
  28652. for (var key = startKey; key < this._keys.length; key++) {
  28653. if (this._keys[key + 1].frame >= currentFrame) {
  28654. var startValue = this._getKeyValue(this._keys[key].value);
  28655. var endValue = this._getKeyValue(this._keys[key + 1].value);
  28656. // gradient : percent of currentFrame between the frame inf and the frame sup
  28657. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  28658. // check for easingFunction and correction of gradient
  28659. if (this._easingFunction != null) {
  28660. gradient = this._easingFunction.ease(gradient);
  28661. }
  28662. switch (this.dataType) {
  28663. // Float
  28664. case Animation.ANIMATIONTYPE_FLOAT:
  28665. switch (loopMode) {
  28666. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28667. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28668. return this.floatInterpolateFunction(startValue, endValue, gradient);
  28669. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28670. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  28671. }
  28672. break;
  28673. // Quaternion
  28674. case Animation.ANIMATIONTYPE_QUATERNION:
  28675. var quaternion = null;
  28676. switch (loopMode) {
  28677. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28678. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28679. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28680. break;
  28681. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28682. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28683. break;
  28684. }
  28685. return quaternion;
  28686. // Vector3
  28687. case Animation.ANIMATIONTYPE_VECTOR3:
  28688. switch (loopMode) {
  28689. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28690. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28691. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  28692. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28693. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28694. }
  28695. // Vector2
  28696. case Animation.ANIMATIONTYPE_VECTOR2:
  28697. switch (loopMode) {
  28698. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28699. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28700. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  28701. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28702. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28703. }
  28704. // Size
  28705. case Animation.ANIMATIONTYPE_SIZE:
  28706. switch (loopMode) {
  28707. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28708. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28709. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28710. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28711. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28712. }
  28713. // Color3
  28714. case Animation.ANIMATIONTYPE_COLOR3:
  28715. switch (loopMode) {
  28716. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28717. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28718. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28719. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28720. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28721. }
  28722. // Matrix
  28723. case Animation.ANIMATIONTYPE_MATRIX:
  28724. switch (loopMode) {
  28725. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28726. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28727. if (this.allowMatricesInterpolation) {
  28728. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28729. }
  28730. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28731. return startValue;
  28732. }
  28733. default:
  28734. break;
  28735. }
  28736. break;
  28737. }
  28738. }
  28739. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28740. };
  28741. Animation.prototype.setValue = function (currentValue, blend) {
  28742. if (blend === void 0) { blend = false; }
  28743. // Set value
  28744. var path;
  28745. var destination;
  28746. if (this.targetPropertyPath.length > 1) {
  28747. var property = this._target[this.targetPropertyPath[0]];
  28748. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28749. property = property[this.targetPropertyPath[index]];
  28750. }
  28751. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28752. destination = property;
  28753. }
  28754. else {
  28755. path = this.targetPropertyPath[0];
  28756. destination = this._target;
  28757. }
  28758. // Blending
  28759. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28760. if (!this._originalBlendValue) {
  28761. if (destination[path].clone) {
  28762. this._originalBlendValue = destination[path].clone();
  28763. }
  28764. else {
  28765. this._originalBlendValue = destination[path];
  28766. }
  28767. }
  28768. if (this._originalBlendValue.prototype) {
  28769. if (this._originalBlendValue.prototype.Lerp) {
  28770. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28771. }
  28772. else {
  28773. destination[path] = currentValue;
  28774. }
  28775. }
  28776. else if (this._originalBlendValue.m) {
  28777. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28778. }
  28779. else {
  28780. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28781. }
  28782. this._blendingFactor += this.blendingSpeed;
  28783. }
  28784. else {
  28785. destination[path] = currentValue;
  28786. }
  28787. if (this._target.markAsDirty) {
  28788. this._target.markAsDirty(this.targetProperty);
  28789. }
  28790. };
  28791. Animation.prototype.goToFrame = function (frame) {
  28792. if (frame < this._keys[0].frame) {
  28793. frame = this._keys[0].frame;
  28794. }
  28795. else if (frame > this._keys[this._keys.length - 1].frame) {
  28796. frame = this._keys[this._keys.length - 1].frame;
  28797. }
  28798. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28799. this.setValue(currentValue);
  28800. };
  28801. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28802. if (blend === void 0) { blend = false; }
  28803. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28804. this._stopped = true;
  28805. return false;
  28806. }
  28807. var returnValue = true;
  28808. // Adding a start key at frame 0 if missing
  28809. if (this._keys[0].frame !== 0) {
  28810. var newKey = { frame: 0, value: this._keys[0].value };
  28811. this._keys.splice(0, 0, newKey);
  28812. }
  28813. // Check limits
  28814. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28815. from = this._keys[0].frame;
  28816. }
  28817. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28818. to = this._keys[this._keys.length - 1].frame;
  28819. }
  28820. // Compute ratio
  28821. var range = to - from;
  28822. var offsetValue;
  28823. // ratio represents the frame delta between from and to
  28824. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28825. var highLimitValue = 0;
  28826. if (ratio > range && !loop) {
  28827. returnValue = false;
  28828. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28829. }
  28830. else {
  28831. // Get max value if required
  28832. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28833. var keyOffset = to.toString() + from.toString();
  28834. if (!this._offsetsCache[keyOffset]) {
  28835. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28836. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28837. switch (this.dataType) {
  28838. // Float
  28839. case Animation.ANIMATIONTYPE_FLOAT:
  28840. this._offsetsCache[keyOffset] = toValue - fromValue;
  28841. break;
  28842. // Quaternion
  28843. case Animation.ANIMATIONTYPE_QUATERNION:
  28844. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28845. break;
  28846. // Vector3
  28847. case Animation.ANIMATIONTYPE_VECTOR3:
  28848. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28849. // Vector2
  28850. case Animation.ANIMATIONTYPE_VECTOR2:
  28851. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28852. // Size
  28853. case Animation.ANIMATIONTYPE_SIZE:
  28854. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28855. // Color3
  28856. case Animation.ANIMATIONTYPE_COLOR3:
  28857. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28858. default:
  28859. break;
  28860. }
  28861. this._highLimitsCache[keyOffset] = toValue;
  28862. }
  28863. highLimitValue = this._highLimitsCache[keyOffset];
  28864. offsetValue = this._offsetsCache[keyOffset];
  28865. }
  28866. }
  28867. if (offsetValue === undefined) {
  28868. switch (this.dataType) {
  28869. // Float
  28870. case Animation.ANIMATIONTYPE_FLOAT:
  28871. offsetValue = 0;
  28872. break;
  28873. // Quaternion
  28874. case Animation.ANIMATIONTYPE_QUATERNION:
  28875. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28876. break;
  28877. // Vector3
  28878. case Animation.ANIMATIONTYPE_VECTOR3:
  28879. offsetValue = BABYLON.Vector3.Zero();
  28880. break;
  28881. // Vector2
  28882. case Animation.ANIMATIONTYPE_VECTOR2:
  28883. offsetValue = BABYLON.Vector2.Zero();
  28884. break;
  28885. // Size
  28886. case Animation.ANIMATIONTYPE_SIZE:
  28887. offsetValue = BABYLON.Size.Zero();
  28888. break;
  28889. // Color3
  28890. case Animation.ANIMATIONTYPE_COLOR3:
  28891. offsetValue = BABYLON.Color3.Black();
  28892. }
  28893. }
  28894. // Compute value
  28895. var repeatCount = (ratio / range) >> 0;
  28896. var currentFrame = returnValue ? from + ratio % range : to;
  28897. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28898. // Set value
  28899. this.setValue(currentValue);
  28900. // Check events
  28901. for (var index = 0; index < this._events.length; index++) {
  28902. if (currentFrame >= this._events[index].frame) {
  28903. var event = this._events[index];
  28904. if (!event.isDone) {
  28905. // If event should be done only once, remove it.
  28906. if (event.onlyOnce) {
  28907. this._events.splice(index, 1);
  28908. index--;
  28909. }
  28910. event.isDone = true;
  28911. event.action();
  28912. } // Don't do anything if the event has already be done.
  28913. }
  28914. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28915. // reset event, the animation is looping
  28916. this._events[index].isDone = false;
  28917. }
  28918. }
  28919. if (!returnValue) {
  28920. this._stopped = true;
  28921. }
  28922. return returnValue;
  28923. };
  28924. Animation.prototype.serialize = function () {
  28925. var serializationObject = {};
  28926. serializationObject.name = this.name;
  28927. serializationObject.property = this.targetProperty;
  28928. serializationObject.framePerSecond = this.framePerSecond;
  28929. serializationObject.dataType = this.dataType;
  28930. serializationObject.loopBehavior = this.loopMode;
  28931. var dataType = this.dataType;
  28932. serializationObject.keys = [];
  28933. var keys = this.getKeys();
  28934. for (var index = 0; index < keys.length; index++) {
  28935. var animationKey = keys[index];
  28936. var key = {};
  28937. key.frame = animationKey.frame;
  28938. switch (dataType) {
  28939. case Animation.ANIMATIONTYPE_FLOAT:
  28940. key.values = [animationKey.value];
  28941. break;
  28942. case Animation.ANIMATIONTYPE_QUATERNION:
  28943. case Animation.ANIMATIONTYPE_MATRIX:
  28944. case Animation.ANIMATIONTYPE_VECTOR3:
  28945. case Animation.ANIMATIONTYPE_COLOR3:
  28946. key.values = animationKey.value.asArray();
  28947. break;
  28948. }
  28949. serializationObject.keys.push(key);
  28950. }
  28951. serializationObject.ranges = [];
  28952. for (var name in this._ranges) {
  28953. var range = {};
  28954. range.name = name;
  28955. range.from = this._ranges[name].from;
  28956. range.to = this._ranges[name].to;
  28957. serializationObject.ranges.push(range);
  28958. }
  28959. return serializationObject;
  28960. };
  28961. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28962. get: function () {
  28963. return Animation._ANIMATIONTYPE_FLOAT;
  28964. },
  28965. enumerable: true,
  28966. configurable: true
  28967. });
  28968. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28969. get: function () {
  28970. return Animation._ANIMATIONTYPE_VECTOR3;
  28971. },
  28972. enumerable: true,
  28973. configurable: true
  28974. });
  28975. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28976. get: function () {
  28977. return Animation._ANIMATIONTYPE_VECTOR2;
  28978. },
  28979. enumerable: true,
  28980. configurable: true
  28981. });
  28982. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28983. get: function () {
  28984. return Animation._ANIMATIONTYPE_SIZE;
  28985. },
  28986. enumerable: true,
  28987. configurable: true
  28988. });
  28989. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28990. get: function () {
  28991. return Animation._ANIMATIONTYPE_QUATERNION;
  28992. },
  28993. enumerable: true,
  28994. configurable: true
  28995. });
  28996. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28997. get: function () {
  28998. return Animation._ANIMATIONTYPE_MATRIX;
  28999. },
  29000. enumerable: true,
  29001. configurable: true
  29002. });
  29003. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29004. get: function () {
  29005. return Animation._ANIMATIONTYPE_COLOR3;
  29006. },
  29007. enumerable: true,
  29008. configurable: true
  29009. });
  29010. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29011. get: function () {
  29012. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29013. },
  29014. enumerable: true,
  29015. configurable: true
  29016. });
  29017. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29018. get: function () {
  29019. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29020. },
  29021. enumerable: true,
  29022. configurable: true
  29023. });
  29024. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29025. get: function () {
  29026. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29027. },
  29028. enumerable: true,
  29029. configurable: true
  29030. });
  29031. Animation.Parse = function (parsedAnimation) {
  29032. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29033. var dataType = parsedAnimation.dataType;
  29034. var keys = [];
  29035. var data;
  29036. var index;
  29037. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29038. var key = parsedAnimation.keys[index];
  29039. switch (dataType) {
  29040. case Animation.ANIMATIONTYPE_FLOAT:
  29041. data = key.values[0];
  29042. break;
  29043. case Animation.ANIMATIONTYPE_QUATERNION:
  29044. data = BABYLON.Quaternion.FromArray(key.values);
  29045. break;
  29046. case Animation.ANIMATIONTYPE_MATRIX:
  29047. data = BABYLON.Matrix.FromArray(key.values);
  29048. break;
  29049. case Animation.ANIMATIONTYPE_COLOR3:
  29050. data = BABYLON.Color3.FromArray(key.values);
  29051. break;
  29052. case Animation.ANIMATIONTYPE_VECTOR3:
  29053. default:
  29054. data = BABYLON.Vector3.FromArray(key.values);
  29055. break;
  29056. }
  29057. keys.push({
  29058. frame: key.frame,
  29059. value: data
  29060. });
  29061. }
  29062. animation.setKeys(keys);
  29063. if (parsedAnimation.ranges) {
  29064. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29065. data = parsedAnimation.ranges[index];
  29066. animation.createRange(data.name, data.from, data.to);
  29067. }
  29068. }
  29069. return animation;
  29070. };
  29071. Animation.AppendSerializedAnimations = function (source, destination) {
  29072. if (source.animations) {
  29073. destination.animations = [];
  29074. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29075. var animation = source.animations[animationIndex];
  29076. destination.animations.push(animation.serialize());
  29077. }
  29078. }
  29079. };
  29080. // Statics
  29081. Animation._ANIMATIONTYPE_FLOAT = 0;
  29082. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29083. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29084. Animation._ANIMATIONTYPE_MATRIX = 3;
  29085. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29086. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29087. Animation._ANIMATIONTYPE_SIZE = 6;
  29088. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29089. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29090. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29091. return Animation;
  29092. }());
  29093. BABYLON.Animation = Animation;
  29094. })(BABYLON || (BABYLON = {}));
  29095. var BABYLON;
  29096. (function (BABYLON) {
  29097. var Animatable = (function () {
  29098. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29099. if (fromFrame === void 0) { fromFrame = 0; }
  29100. if (toFrame === void 0) { toFrame = 100; }
  29101. if (loopAnimation === void 0) { loopAnimation = false; }
  29102. if (speedRatio === void 0) { speedRatio = 1.0; }
  29103. this.target = target;
  29104. this.fromFrame = fromFrame;
  29105. this.toFrame = toFrame;
  29106. this.loopAnimation = loopAnimation;
  29107. this.speedRatio = speedRatio;
  29108. this.onAnimationEnd = onAnimationEnd;
  29109. this._animations = new Array();
  29110. this._paused = false;
  29111. this.animationStarted = false;
  29112. if (animations) {
  29113. this.appendAnimations(target, animations);
  29114. }
  29115. this._scene = scene;
  29116. scene._activeAnimatables.push(this);
  29117. }
  29118. // Methods
  29119. Animatable.prototype.getAnimations = function () {
  29120. return this._animations;
  29121. };
  29122. Animatable.prototype.appendAnimations = function (target, animations) {
  29123. for (var index = 0; index < animations.length; index++) {
  29124. var animation = animations[index];
  29125. animation._target = target;
  29126. this._animations.push(animation);
  29127. }
  29128. };
  29129. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29130. var animations = this._animations;
  29131. for (var index = 0; index < animations.length; index++) {
  29132. if (animations[index].targetProperty === property) {
  29133. return animations[index];
  29134. }
  29135. }
  29136. return null;
  29137. };
  29138. Animatable.prototype.reset = function () {
  29139. var animations = this._animations;
  29140. for (var index = 0; index < animations.length; index++) {
  29141. animations[index].reset();
  29142. }
  29143. this._localDelayOffset = null;
  29144. this._pausedDelay = null;
  29145. };
  29146. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29147. var animations = this._animations;
  29148. for (var index = 0; index < animations.length; index++) {
  29149. animations[index].enableBlending = true;
  29150. animations[index].blendingSpeed = blendingSpeed;
  29151. }
  29152. };
  29153. Animatable.prototype.disableBlending = function () {
  29154. var animations = this._animations;
  29155. for (var index = 0; index < animations.length; index++) {
  29156. animations[index].enableBlending = false;
  29157. }
  29158. };
  29159. Animatable.prototype.goToFrame = function (frame) {
  29160. var animations = this._animations;
  29161. if (animations[0]) {
  29162. var fps = animations[0].framePerSecond;
  29163. var currentFrame = animations[0].currentFrame;
  29164. var adjustTime = frame - currentFrame;
  29165. var delay = adjustTime * 1000 / fps;
  29166. this._localDelayOffset -= delay;
  29167. }
  29168. for (var index = 0; index < animations.length; index++) {
  29169. animations[index].goToFrame(frame);
  29170. }
  29171. };
  29172. Animatable.prototype.pause = function () {
  29173. if (this._paused) {
  29174. return;
  29175. }
  29176. this._paused = true;
  29177. };
  29178. Animatable.prototype.restart = function () {
  29179. this._paused = false;
  29180. };
  29181. Animatable.prototype.stop = function (animationName) {
  29182. var index = this._scene._activeAnimatables.indexOf(this);
  29183. if (index > -1) {
  29184. var animations = this._animations;
  29185. var numberOfAnimationsStopped = 0;
  29186. for (var index = animations.length - 1; index >= 0; index--) {
  29187. if (typeof animationName === "string" && animations[index].name != animationName) {
  29188. continue;
  29189. }
  29190. animations[index].reset();
  29191. animations.splice(index, 1);
  29192. numberOfAnimationsStopped++;
  29193. }
  29194. if (animations.length == numberOfAnimationsStopped) {
  29195. this._scene._activeAnimatables.splice(index, 1);
  29196. if (this.onAnimationEnd) {
  29197. this.onAnimationEnd();
  29198. }
  29199. }
  29200. }
  29201. };
  29202. Animatable.prototype._animate = function (delay) {
  29203. if (this._paused) {
  29204. this.animationStarted = false;
  29205. if (!this._pausedDelay) {
  29206. this._pausedDelay = delay;
  29207. }
  29208. return true;
  29209. }
  29210. if (!this._localDelayOffset) {
  29211. this._localDelayOffset = delay;
  29212. }
  29213. else if (this._pausedDelay) {
  29214. this._localDelayOffset += delay - this._pausedDelay;
  29215. this._pausedDelay = null;
  29216. }
  29217. // Animating
  29218. var running = false;
  29219. var animations = this._animations;
  29220. var index;
  29221. for (index = 0; index < animations.length; index++) {
  29222. var animation = animations[index];
  29223. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29224. running = running || isRunning;
  29225. }
  29226. this.animationStarted = running;
  29227. if (!running) {
  29228. // Remove from active animatables
  29229. index = this._scene._activeAnimatables.indexOf(this);
  29230. this._scene._activeAnimatables.splice(index, 1);
  29231. }
  29232. if (!running && this.onAnimationEnd) {
  29233. this.onAnimationEnd();
  29234. this.onAnimationEnd = null;
  29235. }
  29236. return running;
  29237. };
  29238. return Animatable;
  29239. }());
  29240. BABYLON.Animatable = Animatable;
  29241. })(BABYLON || (BABYLON = {}));
  29242. var BABYLON;
  29243. (function (BABYLON) {
  29244. var EasingFunction = (function () {
  29245. function EasingFunction() {
  29246. // Properties
  29247. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29248. }
  29249. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29250. get: function () {
  29251. return EasingFunction._EASINGMODE_EASEIN;
  29252. },
  29253. enumerable: true,
  29254. configurable: true
  29255. });
  29256. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29257. get: function () {
  29258. return EasingFunction._EASINGMODE_EASEOUT;
  29259. },
  29260. enumerable: true,
  29261. configurable: true
  29262. });
  29263. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29264. get: function () {
  29265. return EasingFunction._EASINGMODE_EASEINOUT;
  29266. },
  29267. enumerable: true,
  29268. configurable: true
  29269. });
  29270. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29271. var n = Math.min(Math.max(easingMode, 0), 2);
  29272. this._easingMode = n;
  29273. };
  29274. EasingFunction.prototype.getEasingMode = function () {
  29275. return this._easingMode;
  29276. };
  29277. EasingFunction.prototype.easeInCore = function (gradient) {
  29278. throw new Error('You must implement this method');
  29279. };
  29280. EasingFunction.prototype.ease = function (gradient) {
  29281. switch (this._easingMode) {
  29282. case EasingFunction.EASINGMODE_EASEIN:
  29283. return this.easeInCore(gradient);
  29284. case EasingFunction.EASINGMODE_EASEOUT:
  29285. return (1 - this.easeInCore(1 - gradient));
  29286. }
  29287. if (gradient >= 0.5) {
  29288. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29289. }
  29290. return (this.easeInCore(gradient * 2) * 0.5);
  29291. };
  29292. //Statics
  29293. EasingFunction._EASINGMODE_EASEIN = 0;
  29294. EasingFunction._EASINGMODE_EASEOUT = 1;
  29295. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29296. return EasingFunction;
  29297. }());
  29298. BABYLON.EasingFunction = EasingFunction;
  29299. var CircleEase = (function (_super) {
  29300. __extends(CircleEase, _super);
  29301. function CircleEase() {
  29302. _super.apply(this, arguments);
  29303. }
  29304. CircleEase.prototype.easeInCore = function (gradient) {
  29305. gradient = Math.max(0, Math.min(1, gradient));
  29306. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29307. };
  29308. return CircleEase;
  29309. }(EasingFunction));
  29310. BABYLON.CircleEase = CircleEase;
  29311. var BackEase = (function (_super) {
  29312. __extends(BackEase, _super);
  29313. function BackEase(amplitude) {
  29314. if (amplitude === void 0) { amplitude = 1; }
  29315. _super.call(this);
  29316. this.amplitude = amplitude;
  29317. }
  29318. BackEase.prototype.easeInCore = function (gradient) {
  29319. var num = Math.max(0, this.amplitude);
  29320. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29321. };
  29322. return BackEase;
  29323. }(EasingFunction));
  29324. BABYLON.BackEase = BackEase;
  29325. var BounceEase = (function (_super) {
  29326. __extends(BounceEase, _super);
  29327. function BounceEase(bounces, bounciness) {
  29328. if (bounces === void 0) { bounces = 3; }
  29329. if (bounciness === void 0) { bounciness = 2; }
  29330. _super.call(this);
  29331. this.bounces = bounces;
  29332. this.bounciness = bounciness;
  29333. }
  29334. BounceEase.prototype.easeInCore = function (gradient) {
  29335. var y = Math.max(0.0, this.bounces);
  29336. var bounciness = this.bounciness;
  29337. if (bounciness <= 1.0) {
  29338. bounciness = 1.001;
  29339. }
  29340. var num9 = Math.pow(bounciness, y);
  29341. var num5 = 1.0 - bounciness;
  29342. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29343. var num15 = gradient * num4;
  29344. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29345. var num3 = Math.floor(num65);
  29346. var num13 = num3 + 1.0;
  29347. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29348. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29349. var num7 = (num8 + num12) * 0.5;
  29350. var num6 = gradient - num7;
  29351. var num2 = num7 - num8;
  29352. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29353. };
  29354. return BounceEase;
  29355. }(EasingFunction));
  29356. BABYLON.BounceEase = BounceEase;
  29357. var CubicEase = (function (_super) {
  29358. __extends(CubicEase, _super);
  29359. function CubicEase() {
  29360. _super.apply(this, arguments);
  29361. }
  29362. CubicEase.prototype.easeInCore = function (gradient) {
  29363. return (gradient * gradient * gradient);
  29364. };
  29365. return CubicEase;
  29366. }(EasingFunction));
  29367. BABYLON.CubicEase = CubicEase;
  29368. var ElasticEase = (function (_super) {
  29369. __extends(ElasticEase, _super);
  29370. function ElasticEase(oscillations, springiness) {
  29371. if (oscillations === void 0) { oscillations = 3; }
  29372. if (springiness === void 0) { springiness = 3; }
  29373. _super.call(this);
  29374. this.oscillations = oscillations;
  29375. this.springiness = springiness;
  29376. }
  29377. ElasticEase.prototype.easeInCore = function (gradient) {
  29378. var num2;
  29379. var num3 = Math.max(0.0, this.oscillations);
  29380. var num = Math.max(0.0, this.springiness);
  29381. if (num == 0) {
  29382. num2 = gradient;
  29383. }
  29384. else {
  29385. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29386. }
  29387. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29388. };
  29389. return ElasticEase;
  29390. }(EasingFunction));
  29391. BABYLON.ElasticEase = ElasticEase;
  29392. var ExponentialEase = (function (_super) {
  29393. __extends(ExponentialEase, _super);
  29394. function ExponentialEase(exponent) {
  29395. if (exponent === void 0) { exponent = 2; }
  29396. _super.call(this);
  29397. this.exponent = exponent;
  29398. }
  29399. ExponentialEase.prototype.easeInCore = function (gradient) {
  29400. if (this.exponent <= 0) {
  29401. return gradient;
  29402. }
  29403. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29404. };
  29405. return ExponentialEase;
  29406. }(EasingFunction));
  29407. BABYLON.ExponentialEase = ExponentialEase;
  29408. var PowerEase = (function (_super) {
  29409. __extends(PowerEase, _super);
  29410. function PowerEase(power) {
  29411. if (power === void 0) { power = 2; }
  29412. _super.call(this);
  29413. this.power = power;
  29414. }
  29415. PowerEase.prototype.easeInCore = function (gradient) {
  29416. var y = Math.max(0.0, this.power);
  29417. return Math.pow(gradient, y);
  29418. };
  29419. return PowerEase;
  29420. }(EasingFunction));
  29421. BABYLON.PowerEase = PowerEase;
  29422. var QuadraticEase = (function (_super) {
  29423. __extends(QuadraticEase, _super);
  29424. function QuadraticEase() {
  29425. _super.apply(this, arguments);
  29426. }
  29427. QuadraticEase.prototype.easeInCore = function (gradient) {
  29428. return (gradient * gradient);
  29429. };
  29430. return QuadraticEase;
  29431. }(EasingFunction));
  29432. BABYLON.QuadraticEase = QuadraticEase;
  29433. var QuarticEase = (function (_super) {
  29434. __extends(QuarticEase, _super);
  29435. function QuarticEase() {
  29436. _super.apply(this, arguments);
  29437. }
  29438. QuarticEase.prototype.easeInCore = function (gradient) {
  29439. return (gradient * gradient * gradient * gradient);
  29440. };
  29441. return QuarticEase;
  29442. }(EasingFunction));
  29443. BABYLON.QuarticEase = QuarticEase;
  29444. var QuinticEase = (function (_super) {
  29445. __extends(QuinticEase, _super);
  29446. function QuinticEase() {
  29447. _super.apply(this, arguments);
  29448. }
  29449. QuinticEase.prototype.easeInCore = function (gradient) {
  29450. return (gradient * gradient * gradient * gradient * gradient);
  29451. };
  29452. return QuinticEase;
  29453. }(EasingFunction));
  29454. BABYLON.QuinticEase = QuinticEase;
  29455. var SineEase = (function (_super) {
  29456. __extends(SineEase, _super);
  29457. function SineEase() {
  29458. _super.apply(this, arguments);
  29459. }
  29460. SineEase.prototype.easeInCore = function (gradient) {
  29461. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29462. };
  29463. return SineEase;
  29464. }(EasingFunction));
  29465. BABYLON.SineEase = SineEase;
  29466. var BezierCurveEase = (function (_super) {
  29467. __extends(BezierCurveEase, _super);
  29468. function BezierCurveEase(x1, y1, x2, y2) {
  29469. if (x1 === void 0) { x1 = 0; }
  29470. if (y1 === void 0) { y1 = 0; }
  29471. if (x2 === void 0) { x2 = 1; }
  29472. if (y2 === void 0) { y2 = 1; }
  29473. _super.call(this);
  29474. this.x1 = x1;
  29475. this.y1 = y1;
  29476. this.x2 = x2;
  29477. this.y2 = y2;
  29478. }
  29479. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29480. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29481. };
  29482. return BezierCurveEase;
  29483. }(EasingFunction));
  29484. BABYLON.BezierCurveEase = BezierCurveEase;
  29485. })(BABYLON || (BABYLON = {}));
  29486. var BABYLON;
  29487. (function (BABYLON) {
  29488. var Bone = (function (_super) {
  29489. __extends(Bone, _super);
  29490. function Bone(name, skeleton, parentBone, matrix, restPose) {
  29491. _super.call(this, name, skeleton.getScene());
  29492. this.name = name;
  29493. this.children = new Array();
  29494. this.animations = new Array();
  29495. this._worldTransform = new BABYLON.Matrix();
  29496. this._absoluteTransform = new BABYLON.Matrix();
  29497. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  29498. this._scaleMatrix = BABYLON.Matrix.Identity();
  29499. this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  29500. this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  29501. this._syncScaleVector = function () {
  29502. var lm = this.getLocalMatrix();
  29503. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  29504. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  29505. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  29506. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  29507. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  29508. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  29509. this._scaleVector.x = xs * Math.sqrt(xsq);
  29510. this._scaleVector.y = ys * Math.sqrt(ysq);
  29511. this._scaleVector.z = zs * Math.sqrt(zsq);
  29512. if (this._parent) {
  29513. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  29514. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  29515. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  29516. }
  29517. };
  29518. this._skeleton = skeleton;
  29519. this._matrix = matrix;
  29520. this._baseMatrix = matrix;
  29521. this._restPose = restPose ? restPose : matrix.clone();
  29522. skeleton.bones.push(this);
  29523. if (parentBone) {
  29524. this._parent = parentBone;
  29525. parentBone.children.push(this);
  29526. }
  29527. else {
  29528. this._parent = null;
  29529. }
  29530. this._updateDifferenceMatrix();
  29531. }
  29532. // Members
  29533. Bone.prototype.getParent = function () {
  29534. return this._parent;
  29535. };
  29536. Bone.prototype.getLocalMatrix = function () {
  29537. return this._matrix;
  29538. };
  29539. Bone.prototype.getBaseMatrix = function () {
  29540. return this._baseMatrix;
  29541. };
  29542. Bone.prototype.getRestPose = function () {
  29543. return this._restPose;
  29544. };
  29545. Bone.prototype.returnToRest = function () {
  29546. this.updateMatrix(this._restPose.clone());
  29547. };
  29548. Bone.prototype.getWorldMatrix = function () {
  29549. return this._worldTransform;
  29550. };
  29551. Bone.prototype.getInvertedAbsoluteTransform = function () {
  29552. return this._invertedAbsoluteTransform;
  29553. };
  29554. Bone.prototype.getAbsoluteTransform = function () {
  29555. return this._absoluteTransform;
  29556. };
  29557. // Methods
  29558. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  29559. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  29560. this._baseMatrix = matrix.clone();
  29561. this._matrix = matrix.clone();
  29562. this._skeleton._markAsDirty();
  29563. if (updateDifferenceMatrix) {
  29564. this._updateDifferenceMatrix();
  29565. }
  29566. };
  29567. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  29568. if (!rootMatrix) {
  29569. rootMatrix = this._baseMatrix;
  29570. }
  29571. if (this._parent) {
  29572. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29573. }
  29574. else {
  29575. this._absoluteTransform.copyFrom(rootMatrix);
  29576. }
  29577. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  29578. for (var index = 0; index < this.children.length; index++) {
  29579. this.children[index]._updateDifferenceMatrix();
  29580. }
  29581. };
  29582. Bone.prototype.markAsDirty = function () {
  29583. this._currentRenderId++;
  29584. this._skeleton._markAsDirty();
  29585. };
  29586. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  29587. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29588. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  29589. // all animation may be coming from a library skeleton, so may need to create animation
  29590. if (this.animations.length === 0) {
  29591. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  29592. this.animations[0].setKeys([]);
  29593. }
  29594. // get animation info / verify there is such a range from the source bone
  29595. var sourceRange = source.animations[0].getRange(rangeName);
  29596. if (!sourceRange) {
  29597. return false;
  29598. }
  29599. var from = sourceRange.from;
  29600. var to = sourceRange.to;
  29601. var sourceKeys = source.animations[0].getKeys();
  29602. // rescaling prep
  29603. var sourceBoneLength = source.length;
  29604. var sourceParent = source.getParent();
  29605. var parent = this.getParent();
  29606. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  29607. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  29608. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  29609. var destKeys = this.animations[0].getKeys();
  29610. // loop vars declaration
  29611. var orig;
  29612. var origTranslation;
  29613. var mat;
  29614. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  29615. orig = sourceKeys[key];
  29616. if (orig.frame >= from && orig.frame <= to) {
  29617. if (rescaleAsRequired) {
  29618. mat = orig.value.clone();
  29619. // scale based on parent ratio, when bone has parent
  29620. if (parentScalingReqd) {
  29621. origTranslation = mat.getTranslation();
  29622. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  29623. }
  29624. else if (dimensionsScalingReqd) {
  29625. origTranslation = mat.getTranslation();
  29626. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  29627. }
  29628. else {
  29629. mat = orig.value;
  29630. }
  29631. }
  29632. else {
  29633. mat = orig.value;
  29634. }
  29635. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  29636. }
  29637. }
  29638. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  29639. return true;
  29640. };
  29641. Bone.prototype.translate = function (vec) {
  29642. var lm = this.getLocalMatrix();
  29643. lm.m[12] += vec.x;
  29644. lm.m[13] += vec.y;
  29645. lm.m[14] += vec.z;
  29646. this.markAsDirty();
  29647. };
  29648. Bone.prototype.setPosition = function (position) {
  29649. var lm = this.getLocalMatrix();
  29650. lm.m[12] = position.x;
  29651. lm.m[13] = position.y;
  29652. lm.m[14] = position.z;
  29653. this.markAsDirty();
  29654. };
  29655. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  29656. if (mesh === void 0) { mesh = null; }
  29657. this._skeleton.computeAbsoluteTransforms();
  29658. var tmat = BABYLON.Tmp.Matrix[0];
  29659. var vec = BABYLON.Tmp.Vector3[0];
  29660. if (mesh) {
  29661. tmat.copyFrom(this._parent.getAbsoluteTransform());
  29662. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  29663. }
  29664. else {
  29665. tmat.copyFrom(this._parent.getAbsoluteTransform());
  29666. }
  29667. tmat.invert();
  29668. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  29669. var lm = this.getLocalMatrix();
  29670. lm.m[12] = vec.x;
  29671. lm.m[13] = vec.y;
  29672. lm.m[14] = vec.z;
  29673. this.markAsDirty();
  29674. };
  29675. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  29676. if (scaleChildren === void 0) { scaleChildren = false; }
  29677. if (this.animations[0] && !this.animations[0].isStopped()) {
  29678. if (!scaleChildren) {
  29679. this._negateScaleChildren.x = 1 / x;
  29680. this._negateScaleChildren.y = 1 / y;
  29681. this._negateScaleChildren.z = 1 / z;
  29682. }
  29683. this._syncScaleVector();
  29684. }
  29685. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  29686. };
  29687. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  29688. if (scaleChildren === void 0) { scaleChildren = false; }
  29689. var locMat = this.getLocalMatrix();
  29690. var origLocMat = BABYLON.Tmp.Matrix[0];
  29691. origLocMat.copyFrom(locMat);
  29692. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  29693. origLocMatInv.copyFrom(origLocMat);
  29694. origLocMatInv.invert();
  29695. var scaleMat = BABYLON.Tmp.Matrix[2];
  29696. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  29697. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  29698. this._scaleVector.x *= x;
  29699. this._scaleVector.y *= y;
  29700. this._scaleVector.z *= z;
  29701. locMat.multiplyToRef(origLocMatInv, locMat);
  29702. locMat.multiplyToRef(scaleMat, locMat);
  29703. locMat.multiplyToRef(origLocMat, locMat);
  29704. var parent = this.getParent();
  29705. if (parent) {
  29706. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  29707. }
  29708. else {
  29709. this.getAbsoluteTransform().copyFrom(locMat);
  29710. }
  29711. var len = this.children.length;
  29712. scaleMat.invert();
  29713. for (var i = 0; i < len; i++) {
  29714. var child = this.children[i];
  29715. var cm = child.getLocalMatrix();
  29716. cm.multiplyToRef(scaleMat, cm);
  29717. var lm = child.getLocalMatrix();
  29718. lm.m[12] *= x;
  29719. lm.m[13] *= y;
  29720. lm.m[14] *= z;
  29721. }
  29722. this.computeAbsoluteTransforms();
  29723. if (scaleChildren) {
  29724. for (var i = 0; i < len; i++) {
  29725. this.children[i].scale(x, y, z, scaleChildren);
  29726. }
  29727. }
  29728. this.markAsDirty();
  29729. };
  29730. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  29731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29732. if (mesh === void 0) { mesh = null; }
  29733. var rotMat = BABYLON.Tmp.Matrix[0];
  29734. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  29735. var rotMatInv = BABYLON.Tmp.Matrix[1];
  29736. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  29737. rotMatInv.multiplyToRef(rotMat, rotMat);
  29738. this._rotateWithMatrix(rotMat, space, mesh);
  29739. };
  29740. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  29741. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29742. if (mesh === void 0) { mesh = null; }
  29743. var rmat = BABYLON.Tmp.Matrix[0];
  29744. rmat.m[12] = 0;
  29745. rmat.m[13] = 0;
  29746. rmat.m[14] = 0;
  29747. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  29748. this._rotateWithMatrix(rmat, space, mesh);
  29749. };
  29750. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  29751. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29752. if (mesh === void 0) { mesh = null; }
  29753. var rotMat = BABYLON.Tmp.Matrix[0];
  29754. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  29755. var rotMatInv = BABYLON.Tmp.Matrix[1];
  29756. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  29757. rotMatInv.multiplyToRef(rotMat, rotMat);
  29758. this._rotateWithMatrix(rotMat, space, mesh);
  29759. };
  29760. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  29761. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29762. if (mesh === void 0) { mesh = null; }
  29763. var rotMatInv = BABYLON.Tmp.Matrix[1];
  29764. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  29765. rotMatInv.multiplyToRef(rotMat, rotMat);
  29766. this._rotateWithMatrix(rotMat, space, mesh);
  29767. };
  29768. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  29769. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29770. if (mesh === void 0) { mesh = null; }
  29771. var lmat = this.getLocalMatrix();
  29772. var lx = lmat.m[12];
  29773. var ly = lmat.m[13];
  29774. var lz = lmat.m[14];
  29775. var parent = this.getParent();
  29776. var parentScale = BABYLON.Tmp.Matrix[3];
  29777. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  29778. if (parent) {
  29779. if (space == BABYLON.Space.WORLD) {
  29780. if (mesh) {
  29781. parentScale.copyFrom(mesh.getWorldMatrix());
  29782. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  29783. }
  29784. else {
  29785. parentScale.copyFrom(parent.getAbsoluteTransform());
  29786. }
  29787. }
  29788. else {
  29789. parentScale = parent._scaleMatrix;
  29790. }
  29791. parentScaleInv.copyFrom(parentScale);
  29792. parentScaleInv.invert();
  29793. lmat.multiplyToRef(parentScale, lmat);
  29794. lmat.multiplyToRef(rmat, lmat);
  29795. lmat.multiplyToRef(parentScaleInv, lmat);
  29796. }
  29797. else {
  29798. if (space == BABYLON.Space.WORLD && mesh) {
  29799. parentScale.copyFrom(mesh.getWorldMatrix());
  29800. parentScaleInv.copyFrom(parentScale);
  29801. parentScaleInv.invert();
  29802. lmat.multiplyToRef(parentScale, lmat);
  29803. lmat.multiplyToRef(rmat, lmat);
  29804. lmat.multiplyToRef(parentScaleInv, lmat);
  29805. }
  29806. else {
  29807. lmat.multiplyToRef(rmat, lmat);
  29808. }
  29809. }
  29810. lmat.m[12] = lx;
  29811. lmat.m[13] = ly;
  29812. lmat.m[14] = lz;
  29813. this.computeAbsoluteTransforms();
  29814. this.markAsDirty();
  29815. };
  29816. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  29817. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29818. if (mesh === void 0) { mesh = null; }
  29819. if (space == BABYLON.Space.WORLD) {
  29820. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  29821. scaleMatrix.copyFrom(this._scaleMatrix);
  29822. rotMatInv.copyFrom(this.getAbsoluteTransform());
  29823. if (mesh) {
  29824. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  29825. var meshScale = BABYLON.Tmp.Matrix[3];
  29826. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  29827. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  29828. }
  29829. rotMatInv.invert();
  29830. scaleMatrix.m[0] *= -1;
  29831. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  29832. }
  29833. else {
  29834. rotMatInv.copyFrom(this.getLocalMatrix());
  29835. rotMatInv.invert();
  29836. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  29837. scaleMatrix.copyFrom(this._scaleMatrix);
  29838. if (this._parent) {
  29839. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  29840. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  29841. pscaleMatrix.invert();
  29842. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  29843. }
  29844. else {
  29845. scaleMatrix.m[0] *= -1;
  29846. }
  29847. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  29848. }
  29849. };
  29850. Bone.prototype.getScale = function () {
  29851. return this._scaleVector.clone();
  29852. };
  29853. Bone.prototype.getScaleToRef = function (result) {
  29854. result.copyFrom(this._scaleVector);
  29855. };
  29856. Bone.prototype.getAbsolutePosition = function (mesh) {
  29857. if (mesh === void 0) { mesh = null; }
  29858. var pos = BABYLON.Vector3.Zero();
  29859. this.getAbsolutePositionToRef(mesh, pos);
  29860. return pos;
  29861. };
  29862. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  29863. if (mesh === void 0) { mesh = null; }
  29864. this._skeleton.computeAbsoluteTransforms();
  29865. var tmat = BABYLON.Tmp.Matrix[0];
  29866. if (mesh) {
  29867. tmat.copyFrom(this.getAbsoluteTransform());
  29868. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  29869. }
  29870. else {
  29871. tmat = this.getAbsoluteTransform();
  29872. }
  29873. result.x = tmat.m[12];
  29874. result.y = tmat.m[13];
  29875. result.z = tmat.m[14];
  29876. };
  29877. Bone.prototype.computeAbsoluteTransforms = function () {
  29878. if (this._parent) {
  29879. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29880. }
  29881. else {
  29882. this._absoluteTransform.copyFrom(this._matrix);
  29883. var poseMatrix = this._skeleton.getPoseMatrix();
  29884. if (poseMatrix) {
  29885. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  29886. }
  29887. }
  29888. var children = this.children;
  29889. var len = children.length;
  29890. for (var i = 0; i < len; i++) {
  29891. children[i].computeAbsoluteTransforms();
  29892. }
  29893. };
  29894. Bone.prototype.getDirection = function (localAxis) {
  29895. var result = BABYLON.Vector3.Zero();
  29896. this.getDirectionToRef(localAxis, result);
  29897. return result;
  29898. };
  29899. Bone.prototype.getDirectionToRef = function (localAxis, result) {
  29900. this._skeleton.computeAbsoluteTransforms();
  29901. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getAbsoluteTransform(), result);
  29902. if (this._scaleVector.x != 1 || this._scaleVector.y != 1 || this._scaleVector.z != 1) {
  29903. result.normalize();
  29904. }
  29905. };
  29906. return Bone;
  29907. }(BABYLON.Node));
  29908. BABYLON.Bone = Bone;
  29909. })(BABYLON || (BABYLON = {}));
  29910. var BABYLON;
  29911. (function (BABYLON) {
  29912. var Skeleton = (function () {
  29913. function Skeleton(name, id, scene) {
  29914. this.name = name;
  29915. this.id = id;
  29916. this.bones = new Array();
  29917. this.needInitialSkinMatrix = false;
  29918. this._isDirty = true;
  29919. this._meshesWithPoseMatrix = new Array();
  29920. this._identity = BABYLON.Matrix.Identity();
  29921. this._ranges = {};
  29922. this._lastAbsoluteTransformsUpdateId = -1;
  29923. this.bones = [];
  29924. this._scene = scene;
  29925. scene.skeletons.push(this);
  29926. //make sure it will recalculate the matrix next time prepare is called.
  29927. this._isDirty = true;
  29928. }
  29929. // Members
  29930. Skeleton.prototype.getTransformMatrices = function (mesh) {
  29931. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  29932. return mesh._bonesTransformMatrices;
  29933. }
  29934. return this._transformMatrices;
  29935. };
  29936. Skeleton.prototype.getScene = function () {
  29937. return this._scene;
  29938. };
  29939. // Methods
  29940. /**
  29941. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29942. */
  29943. Skeleton.prototype.toString = function (fullDetails) {
  29944. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  29945. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29946. if (fullDetails) {
  29947. ret += ", Ranges: {";
  29948. var first = true;
  29949. for (var name_1 in this._ranges) {
  29950. if (first) {
  29951. ret += ", ";
  29952. first = false;
  29953. }
  29954. ret += name_1;
  29955. }
  29956. ret += "}";
  29957. }
  29958. return ret;
  29959. };
  29960. /**
  29961. * Get bone's index searching by name
  29962. * @param {string} name is bone's name to search for
  29963. * @return {number} Indice of the bone. Returns -1 if not found
  29964. */
  29965. Skeleton.prototype.getBoneIndexByName = function (name) {
  29966. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  29967. if (this.bones[boneIndex].name === name) {
  29968. return boneIndex;
  29969. }
  29970. }
  29971. return -1;
  29972. };
  29973. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  29974. // check name not already in use
  29975. if (!this._ranges[name]) {
  29976. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  29977. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29978. if (this.bones[i].animations[0]) {
  29979. this.bones[i].animations[0].createRange(name, from, to);
  29980. }
  29981. }
  29982. }
  29983. };
  29984. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  29985. if (deleteFrames === void 0) { deleteFrames = true; }
  29986. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29987. if (this.bones[i].animations[0]) {
  29988. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  29989. }
  29990. }
  29991. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29992. };
  29993. Skeleton.prototype.getAnimationRange = function (name) {
  29994. return this._ranges[name];
  29995. };
  29996. /**
  29997. * Returns as an Array, all AnimationRanges defined on this skeleton
  29998. */
  29999. Skeleton.prototype.getAnimationRanges = function () {
  30000. var animationRanges = [];
  30001. var name;
  30002. var i = 0;
  30003. for (name in this._ranges) {
  30004. animationRanges[i] = this._ranges[name];
  30005. i++;
  30006. }
  30007. return animationRanges;
  30008. };
  30009. /**
  30010. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  30011. */
  30012. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  30013. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30014. if (this._ranges[name] || !source.getAnimationRange(name)) {
  30015. return false;
  30016. }
  30017. var ret = true;
  30018. var frameOffset = this._getHighestAnimationFrame() + 1;
  30019. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  30020. var boneDict = {};
  30021. var sourceBones = source.bones;
  30022. var nBones;
  30023. var i;
  30024. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  30025. boneDict[sourceBones[i].name] = sourceBones[i];
  30026. }
  30027. if (this.bones.length !== sourceBones.length) {
  30028. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  30029. ret = false;
  30030. }
  30031. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  30032. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  30033. var boneName = this.bones[i].name;
  30034. var sourceBone = boneDict[boneName];
  30035. if (sourceBone) {
  30036. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  30037. }
  30038. else {
  30039. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  30040. ret = false;
  30041. }
  30042. }
  30043. // do not call createAnimationRange(), since it also is done to bones, which was already done
  30044. var range = source.getAnimationRange(name);
  30045. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  30046. return ret;
  30047. };
  30048. Skeleton.prototype.returnToRest = function () {
  30049. for (var index = 0; index < this.bones.length; index++) {
  30050. this.bones[index].returnToRest();
  30051. }
  30052. };
  30053. Skeleton.prototype._getHighestAnimationFrame = function () {
  30054. var ret = 0;
  30055. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  30056. if (this.bones[i].animations[0]) {
  30057. var highest = this.bones[i].animations[0].getHighestFrame();
  30058. if (ret < highest) {
  30059. ret = highest;
  30060. }
  30061. }
  30062. }
  30063. return ret;
  30064. };
  30065. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  30066. var range = this.getAnimationRange(name);
  30067. if (!range) {
  30068. return null;
  30069. }
  30070. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  30071. };
  30072. Skeleton.prototype._markAsDirty = function () {
  30073. this._isDirty = true;
  30074. };
  30075. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  30076. this._meshesWithPoseMatrix.push(mesh);
  30077. };
  30078. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  30079. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  30080. if (index > -1) {
  30081. this._meshesWithPoseMatrix.splice(index, 1);
  30082. }
  30083. };
  30084. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  30085. for (var index = 0; index < this.bones.length; index++) {
  30086. var bone = this.bones[index];
  30087. var parentBone = bone.getParent();
  30088. if (parentBone) {
  30089. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  30090. }
  30091. else {
  30092. if (initialSkinMatrix) {
  30093. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  30094. }
  30095. else {
  30096. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  30097. }
  30098. }
  30099. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  30100. }
  30101. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  30102. };
  30103. Skeleton.prototype.prepare = function () {
  30104. if (!this._isDirty) {
  30105. return;
  30106. }
  30107. if (this.needInitialSkinMatrix) {
  30108. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  30109. var mesh = this._meshesWithPoseMatrix[index];
  30110. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  30111. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  30112. }
  30113. var poseMatrix = mesh.getPoseMatrix();
  30114. // Prepare bones
  30115. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  30116. var bone = this.bones[boneIndex];
  30117. if (!bone.getParent()) {
  30118. var matrix = bone.getBaseMatrix();
  30119. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  30120. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  30121. }
  30122. }
  30123. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  30124. }
  30125. }
  30126. else {
  30127. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  30128. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  30129. }
  30130. this._computeTransformMatrices(this._transformMatrices, null);
  30131. }
  30132. this._isDirty = false;
  30133. this._scene._activeBones.addCount(this.bones.length, false);
  30134. };
  30135. Skeleton.prototype.getAnimatables = function () {
  30136. if (!this._animatables || this._animatables.length !== this.bones.length) {
  30137. this._animatables = [];
  30138. for (var index = 0; index < this.bones.length; index++) {
  30139. this._animatables.push(this.bones[index]);
  30140. }
  30141. }
  30142. return this._animatables;
  30143. };
  30144. Skeleton.prototype.clone = function (name, id) {
  30145. var result = new Skeleton(name, id || name, this._scene);
  30146. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  30147. for (var index = 0; index < this.bones.length; index++) {
  30148. var source = this.bones[index];
  30149. var parentBone = null;
  30150. if (source.getParent()) {
  30151. var parentIndex = this.bones.indexOf(source.getParent());
  30152. parentBone = result.bones[parentIndex];
  30153. }
  30154. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  30155. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  30156. }
  30157. if (this._ranges) {
  30158. result._ranges = {};
  30159. for (var rangeName in this._ranges) {
  30160. result._ranges[rangeName] = this._ranges[rangeName].clone();
  30161. }
  30162. }
  30163. this._isDirty = true;
  30164. return result;
  30165. };
  30166. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  30167. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  30168. this.bones.forEach(function (bone) {
  30169. bone.animations.forEach(function (animation) {
  30170. animation.enableBlending = true;
  30171. animation.blendingSpeed = blendingSpeed;
  30172. });
  30173. });
  30174. };
  30175. Skeleton.prototype.dispose = function () {
  30176. this._meshesWithPoseMatrix = [];
  30177. // Animations
  30178. this.getScene().stopAnimation(this);
  30179. // Remove from scene
  30180. this.getScene().removeSkeleton(this);
  30181. };
  30182. Skeleton.prototype.serialize = function () {
  30183. var serializationObject = {};
  30184. serializationObject.name = this.name;
  30185. serializationObject.id = this.id;
  30186. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  30187. serializationObject.bones = [];
  30188. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  30189. for (var index = 0; index < this.bones.length; index++) {
  30190. var bone = this.bones[index];
  30191. var serializedBone = {
  30192. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  30193. name: bone.name,
  30194. matrix: bone.getLocalMatrix().toArray(),
  30195. rest: bone.getRestPose().toArray()
  30196. };
  30197. serializationObject.bones.push(serializedBone);
  30198. if (bone.length) {
  30199. serializedBone.length = bone.length;
  30200. }
  30201. if (bone.animations && bone.animations.length > 0) {
  30202. serializedBone.animation = bone.animations[0].serialize();
  30203. }
  30204. serializationObject.ranges = [];
  30205. for (var name in this._ranges) {
  30206. var range = {};
  30207. range.name = name;
  30208. range.from = this._ranges[name].from;
  30209. range.to = this._ranges[name].to;
  30210. serializationObject.ranges.push(range);
  30211. }
  30212. }
  30213. return serializationObject;
  30214. };
  30215. Skeleton.Parse = function (parsedSkeleton, scene) {
  30216. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  30217. if (parsedSkeleton.dimensionsAtRest) {
  30218. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  30219. }
  30220. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  30221. var index;
  30222. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  30223. var parsedBone = parsedSkeleton.bones[index];
  30224. var parentBone = null;
  30225. if (parsedBone.parentBoneIndex > -1) {
  30226. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  30227. }
  30228. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  30229. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  30230. if (parsedBone.length) {
  30231. bone.length = parsedBone.length;
  30232. }
  30233. if (parsedBone.animation) {
  30234. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  30235. }
  30236. }
  30237. // placed after bones, so createAnimationRange can cascade down
  30238. if (parsedSkeleton.ranges) {
  30239. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  30240. var data = parsedSkeleton.ranges[index];
  30241. skeleton.createAnimationRange(data.name, data.from, data.to);
  30242. }
  30243. }
  30244. return skeleton;
  30245. };
  30246. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  30247. if (forceUpdate === void 0) { forceUpdate = false; }
  30248. var renderId = this._scene.getRenderId();
  30249. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  30250. this.bones[0].computeAbsoluteTransforms();
  30251. this._lastAbsoluteTransformsUpdateId = renderId;
  30252. }
  30253. };
  30254. Skeleton.prototype.getPoseMatrix = function () {
  30255. var poseMatrix;
  30256. if (this._meshesWithPoseMatrix.length > 0) {
  30257. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  30258. }
  30259. return poseMatrix;
  30260. };
  30261. return Skeleton;
  30262. }());
  30263. BABYLON.Skeleton = Skeleton;
  30264. })(BABYLON || (BABYLON = {}));
  30265. var BABYLON;
  30266. (function (BABYLON) {
  30267. var PostProcess = (function () {
  30268. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  30269. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  30270. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  30271. this.name = name;
  30272. this.width = -1;
  30273. this.height = -1;
  30274. /*
  30275. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  30276. Can only be used on a single postprocess or on the last one of a chain.
  30277. */
  30278. this.enablePixelPerfectMode = false;
  30279. this._reusable = false;
  30280. this._textures = new BABYLON.SmartArray(2);
  30281. this._currentRenderTextureInd = 0;
  30282. this._scaleRatio = new BABYLON.Vector2(1, 1);
  30283. // Events
  30284. /**
  30285. * An event triggered when the postprocess is activated.
  30286. * @type {BABYLON.Observable}
  30287. */
  30288. this.onActivateObservable = new BABYLON.Observable();
  30289. /**
  30290. * An event triggered when the postprocess changes its size.
  30291. * @type {BABYLON.Observable}
  30292. */
  30293. this.onSizeChangedObservable = new BABYLON.Observable();
  30294. /**
  30295. * An event triggered when the postprocess applies its effect.
  30296. * @type {BABYLON.Observable}
  30297. */
  30298. this.onApplyObservable = new BABYLON.Observable();
  30299. /**
  30300. * An event triggered before rendering the postprocess
  30301. * @type {BABYLON.Observable}
  30302. */
  30303. this.onBeforeRenderObservable = new BABYLON.Observable();
  30304. /**
  30305. * An event triggered after rendering the postprocess
  30306. * @type {BABYLON.Observable}
  30307. */
  30308. this.onAfterRenderObservable = new BABYLON.Observable();
  30309. if (camera != null) {
  30310. this._camera = camera;
  30311. this._scene = camera.getScene();
  30312. camera.attachPostProcess(this);
  30313. this._engine = this._scene.getEngine();
  30314. }
  30315. else {
  30316. this._engine = engine;
  30317. }
  30318. this._options = options;
  30319. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  30320. this._reusable = reusable || false;
  30321. this._textureType = textureType;
  30322. this._samplers = samplers || [];
  30323. this._samplers.push("textureSampler");
  30324. this._fragmentUrl = fragmentUrl;
  30325. this._parameters = parameters || [];
  30326. this._parameters.push("scale");
  30327. this.updateEffect(defines);
  30328. }
  30329. Object.defineProperty(PostProcess.prototype, "onActivate", {
  30330. set: function (callback) {
  30331. if (this._onActivateObserver) {
  30332. this.onActivateObservable.remove(this._onActivateObserver);
  30333. }
  30334. this._onActivateObserver = this.onActivateObservable.add(callback);
  30335. },
  30336. enumerable: true,
  30337. configurable: true
  30338. });
  30339. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  30340. set: function (callback) {
  30341. if (this._onSizeChangedObserver) {
  30342. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  30343. }
  30344. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  30345. },
  30346. enumerable: true,
  30347. configurable: true
  30348. });
  30349. Object.defineProperty(PostProcess.prototype, "onApply", {
  30350. set: function (callback) {
  30351. if (this._onApplyObserver) {
  30352. this.onApplyObservable.remove(this._onApplyObserver);
  30353. }
  30354. this._onApplyObserver = this.onApplyObservable.add(callback);
  30355. },
  30356. enumerable: true,
  30357. configurable: true
  30358. });
  30359. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  30360. set: function (callback) {
  30361. if (this._onBeforeRenderObserver) {
  30362. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  30363. }
  30364. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  30365. },
  30366. enumerable: true,
  30367. configurable: true
  30368. });
  30369. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  30370. set: function (callback) {
  30371. if (this._onAfterRenderObserver) {
  30372. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  30373. }
  30374. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  30375. },
  30376. enumerable: true,
  30377. configurable: true
  30378. });
  30379. PostProcess.prototype.updateEffect = function (defines) {
  30380. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  30381. };
  30382. PostProcess.prototype.isReusable = function () {
  30383. return this._reusable;
  30384. };
  30385. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  30386. PostProcess.prototype.markTextureDirty = function () {
  30387. this.width = -1;
  30388. };
  30389. PostProcess.prototype.activate = function (camera, sourceTexture) {
  30390. camera = camera || this._camera;
  30391. var scene = camera.getScene();
  30392. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  30393. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  30394. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  30395. var desiredWidth = this._options.width || requiredWidth;
  30396. var desiredHeight = this._options.height || requiredHeight;
  30397. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  30398. if (!this._options.width) {
  30399. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  30400. }
  30401. if (!this._options.height) {
  30402. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  30403. }
  30404. }
  30405. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  30406. if (this._textures.length > 0) {
  30407. for (var i = 0; i < this._textures.length; i++) {
  30408. this._engine._releaseTexture(this._textures.data[i]);
  30409. }
  30410. this._textures.reset();
  30411. }
  30412. this.width = desiredWidth;
  30413. this.height = desiredHeight;
  30414. var textureSize = { width: this.width, height: this.height };
  30415. var textureOptions = {
  30416. generateMipMaps: false,
  30417. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  30418. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  30419. samplingMode: this.renderTargetSamplingMode,
  30420. type: this._textureType
  30421. };
  30422. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  30423. if (this._reusable) {
  30424. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  30425. }
  30426. this.onSizeChangedObservable.notifyObservers(this);
  30427. }
  30428. if (this.enablePixelPerfectMode) {
  30429. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  30430. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  30431. }
  30432. else {
  30433. this._scaleRatio.copyFromFloats(1, 1);
  30434. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  30435. }
  30436. this.onActivateObservable.notifyObservers(camera);
  30437. // Clear
  30438. if (this.clearColor) {
  30439. this._engine.clear(this.clearColor, true, true, true);
  30440. }
  30441. else {
  30442. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  30443. }
  30444. if (this._reusable) {
  30445. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  30446. }
  30447. };
  30448. Object.defineProperty(PostProcess.prototype, "isSupported", {
  30449. get: function () {
  30450. return this._effect.isSupported;
  30451. },
  30452. enumerable: true,
  30453. configurable: true
  30454. });
  30455. PostProcess.prototype.apply = function () {
  30456. // Check
  30457. if (!this._effect.isReady())
  30458. return null;
  30459. // States
  30460. this._engine.enableEffect(this._effect);
  30461. this._engine.setState(false);
  30462. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30463. this._engine.setDepthBuffer(false);
  30464. this._engine.setDepthWrite(false);
  30465. // Texture
  30466. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  30467. // Parameters
  30468. this._effect.setVector2("scale", this._scaleRatio);
  30469. this.onApplyObservable.notifyObservers(this._effect);
  30470. return this._effect;
  30471. };
  30472. PostProcess.prototype.dispose = function (camera) {
  30473. camera = camera || this._camera;
  30474. if (this._textures.length > 0) {
  30475. for (var i = 0; i < this._textures.length; i++) {
  30476. this._engine._releaseTexture(this._textures.data[i]);
  30477. }
  30478. this._textures.reset();
  30479. }
  30480. if (!camera) {
  30481. return;
  30482. }
  30483. camera.detachPostProcess(this);
  30484. var index = camera._postProcesses.indexOf(this);
  30485. if (index === 0 && camera._postProcesses.length > 0) {
  30486. this._camera._postProcesses[0].markTextureDirty();
  30487. }
  30488. this.onActivateObservable.clear();
  30489. this.onAfterRenderObservable.clear();
  30490. this.onApplyObservable.clear();
  30491. this.onBeforeRenderObservable.clear();
  30492. this.onSizeChangedObservable.clear();
  30493. };
  30494. return PostProcess;
  30495. }());
  30496. BABYLON.PostProcess = PostProcess;
  30497. })(BABYLON || (BABYLON = {}));
  30498. var BABYLON;
  30499. (function (BABYLON) {
  30500. var PostProcessManager = (function () {
  30501. function PostProcessManager(scene) {
  30502. this._vertexBuffers = {};
  30503. this._scene = scene;
  30504. }
  30505. PostProcessManager.prototype._prepareBuffers = function () {
  30506. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30507. return;
  30508. }
  30509. // VBO
  30510. var vertices = [];
  30511. vertices.push(1, 1);
  30512. vertices.push(-1, 1);
  30513. vertices.push(-1, -1);
  30514. vertices.push(1, -1);
  30515. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30516. // Indices
  30517. var indices = [];
  30518. indices.push(0);
  30519. indices.push(1);
  30520. indices.push(2);
  30521. indices.push(0);
  30522. indices.push(2);
  30523. indices.push(3);
  30524. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30525. };
  30526. // Methods
  30527. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  30528. var postProcesses = this._scene.activeCamera._postProcesses;
  30529. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30530. return false;
  30531. }
  30532. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  30533. return true;
  30534. };
  30535. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  30536. var engine = this._scene.getEngine();
  30537. for (var index = 0; index < postProcesses.length; index++) {
  30538. if (index < postProcesses.length - 1) {
  30539. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30540. }
  30541. else {
  30542. if (targetTexture) {
  30543. engine.bindFramebuffer(targetTexture);
  30544. }
  30545. else {
  30546. engine.restoreDefaultFramebuffer();
  30547. }
  30548. }
  30549. var pp = postProcesses[index];
  30550. var effect = pp.apply();
  30551. if (effect) {
  30552. pp.onBeforeRenderObservable.notifyObservers(effect);
  30553. // VBOs
  30554. this._prepareBuffers();
  30555. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30556. // Draw order
  30557. engine.draw(true, 0, 6);
  30558. pp.onAfterRenderObservable.notifyObservers(effect);
  30559. }
  30560. }
  30561. // Restore depth buffer
  30562. engine.setDepthBuffer(true);
  30563. engine.setDepthWrite(true);
  30564. };
  30565. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  30566. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30567. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30568. return;
  30569. }
  30570. var engine = this._scene.getEngine();
  30571. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30572. if (index < len - 1) {
  30573. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30574. }
  30575. else {
  30576. if (targetTexture) {
  30577. engine.bindFramebuffer(targetTexture, faceIndex);
  30578. }
  30579. else {
  30580. engine.restoreDefaultFramebuffer();
  30581. }
  30582. }
  30583. if (doNotPresent) {
  30584. break;
  30585. }
  30586. var pp = postProcesses[index];
  30587. var effect = pp.apply();
  30588. if (effect) {
  30589. pp.onBeforeRenderObservable.notifyObservers(effect);
  30590. // VBOs
  30591. this._prepareBuffers();
  30592. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30593. // Draw order
  30594. engine.draw(true, 0, 6);
  30595. pp.onAfterRenderObservable.notifyObservers(effect);
  30596. }
  30597. }
  30598. // Restore depth buffer
  30599. engine.setDepthBuffer(true);
  30600. engine.setDepthWrite(true);
  30601. };
  30602. PostProcessManager.prototype.dispose = function () {
  30603. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30604. if (buffer) {
  30605. buffer.dispose();
  30606. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30607. }
  30608. if (this._indexBuffer) {
  30609. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30610. this._indexBuffer = null;
  30611. }
  30612. };
  30613. return PostProcessManager;
  30614. }());
  30615. BABYLON.PostProcessManager = PostProcessManager;
  30616. })(BABYLON || (BABYLON = {}));
  30617. var BABYLON;
  30618. (function (BABYLON) {
  30619. var PassPostProcess = (function (_super) {
  30620. __extends(PassPostProcess, _super);
  30621. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  30622. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  30623. }
  30624. return PassPostProcess;
  30625. }(BABYLON.PostProcess));
  30626. BABYLON.PassPostProcess = PassPostProcess;
  30627. })(BABYLON || (BABYLON = {}));
  30628. var BABYLON;
  30629. (function (BABYLON) {
  30630. /**
  30631. * This is a holder class for the physics joint created by the physics plugin.
  30632. * It holds a set of functions to control the underlying joint.
  30633. */
  30634. var PhysicsJoint = (function () {
  30635. function PhysicsJoint(type, jointData) {
  30636. this.type = type;
  30637. this.jointData = jointData;
  30638. jointData.nativeParams = jointData.nativeParams || {};
  30639. }
  30640. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  30641. get: function () {
  30642. return this._physicsJoint;
  30643. },
  30644. set: function (newJoint) {
  30645. if (this._physicsJoint) {
  30646. }
  30647. this._physicsJoint = newJoint;
  30648. },
  30649. enumerable: true,
  30650. configurable: true
  30651. });
  30652. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  30653. set: function (physicsPlugin) {
  30654. this._physicsPlugin = physicsPlugin;
  30655. },
  30656. enumerable: true,
  30657. configurable: true
  30658. });
  30659. /**
  30660. * Execute a function that is physics-plugin specific.
  30661. * @param {Function} func the function that will be executed.
  30662. * It accepts two parameters: the physics world and the physics joint.
  30663. */
  30664. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  30665. func(this._physicsPlugin.world, this._physicsJoint);
  30666. };
  30667. //TODO check if the native joints are the same
  30668. //Joint Types
  30669. PhysicsJoint.DistanceJoint = 0;
  30670. PhysicsJoint.HingeJoint = 1;
  30671. PhysicsJoint.BallAndSocketJoint = 2;
  30672. PhysicsJoint.WheelJoint = 3;
  30673. PhysicsJoint.SliderJoint = 4;
  30674. //OIMO
  30675. PhysicsJoint.PrismaticJoint = 5;
  30676. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  30677. PhysicsJoint.UniversalJoint = 6;
  30678. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  30679. //Cannon
  30680. //Similar to a Ball-Joint. Different in params
  30681. PhysicsJoint.PointToPointJoint = 8;
  30682. //Cannon only at the moment
  30683. PhysicsJoint.SpringJoint = 9;
  30684. PhysicsJoint.LockJoint = 10;
  30685. return PhysicsJoint;
  30686. }());
  30687. BABYLON.PhysicsJoint = PhysicsJoint;
  30688. /**
  30689. * A class representing a physics distance joint.
  30690. */
  30691. var DistanceJoint = (function (_super) {
  30692. __extends(DistanceJoint, _super);
  30693. function DistanceJoint(jointData) {
  30694. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  30695. }
  30696. /**
  30697. * Update the predefined distance.
  30698. */
  30699. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  30700. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  30701. };
  30702. return DistanceJoint;
  30703. }(PhysicsJoint));
  30704. BABYLON.DistanceJoint = DistanceJoint;
  30705. var MotorEnabledJoint = (function (_super) {
  30706. __extends(MotorEnabledJoint, _super);
  30707. function MotorEnabledJoint(type, jointData) {
  30708. _super.call(this, type, jointData);
  30709. }
  30710. /**
  30711. * Set the motor values.
  30712. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30713. * @param {number} force the force to apply
  30714. * @param {number} maxForce max force for this motor.
  30715. */
  30716. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  30717. this._physicsPlugin.setMotor(this, force, maxForce);
  30718. };
  30719. /**
  30720. * Set the motor's limits.
  30721. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30722. */
  30723. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30724. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30725. };
  30726. return MotorEnabledJoint;
  30727. }(PhysicsJoint));
  30728. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  30729. /**
  30730. * This class represents a single hinge physics joint
  30731. */
  30732. var HingeJoint = (function (_super) {
  30733. __extends(HingeJoint, _super);
  30734. function HingeJoint(jointData) {
  30735. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  30736. }
  30737. /**
  30738. * Set the motor values.
  30739. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30740. * @param {number} force the force to apply
  30741. * @param {number} maxForce max force for this motor.
  30742. */
  30743. HingeJoint.prototype.setMotor = function (force, maxForce) {
  30744. this._physicsPlugin.setMotor(this, force, maxForce);
  30745. };
  30746. /**
  30747. * Set the motor's limits.
  30748. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30749. */
  30750. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30751. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30752. };
  30753. return HingeJoint;
  30754. }(MotorEnabledJoint));
  30755. BABYLON.HingeJoint = HingeJoint;
  30756. /**
  30757. * This class represents a dual hinge physics joint (same as wheel joint)
  30758. */
  30759. var Hinge2Joint = (function (_super) {
  30760. __extends(Hinge2Joint, _super);
  30761. function Hinge2Joint(jointData) {
  30762. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  30763. }
  30764. /**
  30765. * Set the motor values.
  30766. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30767. * @param {number} force the force to apply
  30768. * @param {number} maxForce max force for this motor.
  30769. * @param {motorIndex} the motor's index, 0 or 1.
  30770. */
  30771. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  30772. if (motorIndex === void 0) { motorIndex = 0; }
  30773. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  30774. };
  30775. /**
  30776. * Set the motor limits.
  30777. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30778. * @param {number} upperLimit the upper limit
  30779. * @param {number} lowerLimit lower limit
  30780. * @param {motorIndex} the motor's index, 0 or 1.
  30781. */
  30782. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  30783. if (motorIndex === void 0) { motorIndex = 0; }
  30784. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  30785. };
  30786. return Hinge2Joint;
  30787. }(MotorEnabledJoint));
  30788. BABYLON.Hinge2Joint = Hinge2Joint;
  30789. })(BABYLON || (BABYLON = {}));
  30790. var BABYLON;
  30791. (function (BABYLON) {
  30792. var PhysicsImpostor = (function () {
  30793. function PhysicsImpostor(object, type, _options, _scene) {
  30794. var _this = this;
  30795. if (_options === void 0) { _options = { mass: 0 }; }
  30796. this.object = object;
  30797. this.type = type;
  30798. this._options = _options;
  30799. this._scene = _scene;
  30800. this._bodyUpdateRequired = false;
  30801. this._onBeforePhysicsStepCallbacks = new Array();
  30802. this._onAfterPhysicsStepCallbacks = new Array();
  30803. this._onPhysicsCollideCallbacks = [];
  30804. this._deltaPosition = BABYLON.Vector3.Zero();
  30805. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  30806. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  30807. /**
  30808. * this function is executed by the physics engine.
  30809. */
  30810. this.beforeStep = function () {
  30811. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  30812. //conjugate deltaRotation
  30813. if (_this._deltaRotationConjugated) {
  30814. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  30815. }
  30816. else {
  30817. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  30818. }
  30819. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  30820. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  30821. func(_this);
  30822. });
  30823. };
  30824. /**
  30825. * this function is executed by the physics engine.
  30826. */
  30827. this.afterStep = function () {
  30828. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  30829. func(_this);
  30830. });
  30831. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  30832. _this.object.position.addInPlace(_this._deltaPosition);
  30833. if (_this._deltaRotation) {
  30834. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  30835. }
  30836. };
  30837. //event and body object due to cannon's event-based architecture.
  30838. this.onCollide = function (e) {
  30839. if (!_this._onPhysicsCollideCallbacks.length)
  30840. return;
  30841. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  30842. if (otherImpostor) {
  30843. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  30844. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  30845. }).forEach(function (obj) {
  30846. obj.callback(_this, otherImpostor);
  30847. });
  30848. }
  30849. };
  30850. //sanity check!
  30851. if (!this.object) {
  30852. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  30853. return;
  30854. }
  30855. //legacy support for old syntax.
  30856. if (!this._scene && object.getScene) {
  30857. this._scene = object.getScene();
  30858. }
  30859. this._physicsEngine = this._scene.getPhysicsEngine();
  30860. if (!this._physicsEngine) {
  30861. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  30862. }
  30863. else {
  30864. //set the object's quaternion, if not set
  30865. if (!this.object.rotationQuaternion) {
  30866. if (this.object.rotation) {
  30867. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  30868. }
  30869. else {
  30870. this.object.rotationQuaternion = new BABYLON.Quaternion();
  30871. }
  30872. }
  30873. //default options params
  30874. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  30875. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  30876. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  30877. this._joints = [];
  30878. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  30879. if (!this.object.parent) {
  30880. this._init();
  30881. }
  30882. }
  30883. }
  30884. /**
  30885. * This function will completly initialize this impostor.
  30886. * It will create a new body - but only if this mesh has no parent.
  30887. * If it has, this impostor will not be used other than to define the impostor
  30888. * of the child mesh.
  30889. */
  30890. PhysicsImpostor.prototype._init = function () {
  30891. this._physicsEngine.removeImpostor(this);
  30892. this.physicsBody = null;
  30893. this._parent = this._parent || this._getPhysicsParent();
  30894. if (!this.parent) {
  30895. this._physicsEngine.addImpostor(this);
  30896. }
  30897. };
  30898. PhysicsImpostor.prototype._getPhysicsParent = function () {
  30899. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  30900. var parentMesh = this.object.parent;
  30901. return parentMesh.physicsImpostor;
  30902. }
  30903. return;
  30904. };
  30905. /**
  30906. * Should a new body be generated.
  30907. */
  30908. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  30909. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  30910. };
  30911. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  30912. this.forceUpdate();
  30913. };
  30914. /**
  30915. * Force a regeneration of this or the parent's impostor's body.
  30916. * Use under cautious - This will remove all joints already implemented.
  30917. */
  30918. PhysicsImpostor.prototype.forceUpdate = function () {
  30919. this._init();
  30920. if (this.parent) {
  30921. this.parent.forceUpdate();
  30922. }
  30923. };
  30924. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  30925. /*public get mesh(): AbstractMesh {
  30926. return this._mesh;
  30927. }*/
  30928. /**
  30929. * Gets the body that holds this impostor. Either its own, or its parent.
  30930. */
  30931. get: function () {
  30932. return this._parent ? this._parent.physicsBody : this._physicsBody;
  30933. },
  30934. /**
  30935. * Set the physics body. Used mainly by the physics engine/plugin
  30936. */
  30937. set: function (physicsBody) {
  30938. if (this._physicsBody) {
  30939. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  30940. }
  30941. this._physicsBody = physicsBody;
  30942. this.resetUpdateFlags();
  30943. },
  30944. enumerable: true,
  30945. configurable: true
  30946. });
  30947. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  30948. get: function () {
  30949. return this._parent;
  30950. },
  30951. set: function (value) {
  30952. this._parent = value;
  30953. },
  30954. enumerable: true,
  30955. configurable: true
  30956. });
  30957. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  30958. this._bodyUpdateRequired = false;
  30959. };
  30960. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  30961. if (this.object.getBoundingInfo) {
  30962. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  30963. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  30964. }
  30965. else {
  30966. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  30967. }
  30968. };
  30969. PhysicsImpostor.prototype.getObjectCenter = function () {
  30970. if (this.object.getBoundingInfo) {
  30971. return this.object.getBoundingInfo().boundingBox.center;
  30972. }
  30973. else {
  30974. return this.object.position;
  30975. }
  30976. };
  30977. /**
  30978. * Get a specific parametes from the options parameter.
  30979. */
  30980. PhysicsImpostor.prototype.getParam = function (paramName) {
  30981. return this._options[paramName];
  30982. };
  30983. /**
  30984. * Sets a specific parameter in the options given to the physics plugin
  30985. */
  30986. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  30987. this._options[paramName] = value;
  30988. this._bodyUpdateRequired = true;
  30989. };
  30990. /**
  30991. * Specifically change the body's mass option. Won't recreate the physics body object
  30992. */
  30993. PhysicsImpostor.prototype.setMass = function (mass) {
  30994. if (this.getParam("mass") !== mass) {
  30995. this.setParam("mass", mass);
  30996. }
  30997. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  30998. };
  30999. PhysicsImpostor.prototype.getLinearVelocity = function () {
  31000. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  31001. };
  31002. /**
  31003. * Set the body's linear velocity.
  31004. */
  31005. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  31006. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  31007. };
  31008. PhysicsImpostor.prototype.getAngularVelocity = function () {
  31009. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  31010. };
  31011. /**
  31012. * Set the body's linear velocity.
  31013. */
  31014. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  31015. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  31016. };
  31017. /**
  31018. * Execute a function with the physics plugin native code.
  31019. * Provide a function the will have two variables - the world object and the physics body object.
  31020. */
  31021. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  31022. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  31023. };
  31024. /**
  31025. * Register a function that will be executed before the physics world is stepping forward.
  31026. */
  31027. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  31028. this._onBeforePhysicsStepCallbacks.push(func);
  31029. };
  31030. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  31031. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  31032. if (index > -1) {
  31033. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  31034. }
  31035. else {
  31036. BABYLON.Tools.Warn("Function to remove was not found");
  31037. }
  31038. };
  31039. /**
  31040. * Register a function that will be executed after the physics step
  31041. */
  31042. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  31043. this._onAfterPhysicsStepCallbacks.push(func);
  31044. };
  31045. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  31046. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  31047. if (index > -1) {
  31048. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  31049. }
  31050. else {
  31051. BABYLON.Tools.Warn("Function to remove was not found");
  31052. }
  31053. };
  31054. /**
  31055. * register a function that will be executed when this impostor collides against a different body.
  31056. */
  31057. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  31058. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  31059. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  31060. };
  31061. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  31062. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  31063. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  31064. if (index > -1) {
  31065. this._onPhysicsCollideCallbacks.splice(index, 1);
  31066. }
  31067. else {
  31068. BABYLON.Tools.Warn("Function to remove was not found");
  31069. }
  31070. };
  31071. /**
  31072. * Apply a force
  31073. */
  31074. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  31075. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  31076. };
  31077. /**
  31078. * Apply an impulse
  31079. */
  31080. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  31081. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  31082. };
  31083. /**
  31084. * A help function to create a joint.
  31085. */
  31086. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  31087. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  31088. this.addJoint(otherImpostor, joint);
  31089. };
  31090. /**
  31091. * Add a joint to this impostor with a different impostor.
  31092. */
  31093. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  31094. this._joints.push({
  31095. otherImpostor: otherImpostor,
  31096. joint: joint
  31097. });
  31098. this._physicsEngine.addJoint(this, otherImpostor, joint);
  31099. };
  31100. /**
  31101. * Will keep this body still, in a sleep mode.
  31102. */
  31103. PhysicsImpostor.prototype.sleep = function () {
  31104. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  31105. };
  31106. /**
  31107. * Wake the body up.
  31108. */
  31109. PhysicsImpostor.prototype.wakeUp = function () {
  31110. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  31111. };
  31112. PhysicsImpostor.prototype.clone = function (newObject) {
  31113. if (!newObject)
  31114. return null;
  31115. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  31116. };
  31117. PhysicsImpostor.prototype.dispose = function () {
  31118. var _this = this;
  31119. //no dispose if no physics engine is available.
  31120. if (!this._physicsEngine) {
  31121. return;
  31122. }
  31123. this._joints.forEach(function (j) {
  31124. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  31125. });
  31126. //dispose the physics body
  31127. this._physicsEngine.removeImpostor(this);
  31128. if (this.parent) {
  31129. this.parent.forceUpdate();
  31130. }
  31131. else {
  31132. }
  31133. };
  31134. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  31135. this._deltaPosition.copyFrom(position);
  31136. };
  31137. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  31138. if (!this._deltaRotation) {
  31139. this._deltaRotation = new BABYLON.Quaternion();
  31140. }
  31141. this._deltaRotation.copyFrom(rotation);
  31142. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  31143. };
  31144. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  31145. //Impostor types
  31146. PhysicsImpostor.NoImpostor = 0;
  31147. PhysicsImpostor.SphereImpostor = 1;
  31148. PhysicsImpostor.BoxImpostor = 2;
  31149. PhysicsImpostor.PlaneImpostor = 3;
  31150. PhysicsImpostor.MeshImpostor = 4;
  31151. PhysicsImpostor.CylinderImpostor = 7;
  31152. PhysicsImpostor.ParticleImpostor = 8;
  31153. PhysicsImpostor.HeightmapImpostor = 9;
  31154. return PhysicsImpostor;
  31155. }());
  31156. BABYLON.PhysicsImpostor = PhysicsImpostor;
  31157. })(BABYLON || (BABYLON = {}));
  31158. var BABYLON;
  31159. (function (BABYLON) {
  31160. var PhysicsEngine = (function () {
  31161. function PhysicsEngine(gravity, _physicsPlugin) {
  31162. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  31163. this._physicsPlugin = _physicsPlugin;
  31164. //new methods and parameters
  31165. this._impostors = [];
  31166. this._joints = [];
  31167. if (!this._physicsPlugin.isSupported()) {
  31168. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  31169. + "Please make sure it is included.");
  31170. }
  31171. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  31172. this.setGravity(gravity);
  31173. this.setTimeStep();
  31174. }
  31175. PhysicsEngine.prototype.setGravity = function (gravity) {
  31176. this.gravity = gravity;
  31177. this._physicsPlugin.setGravity(this.gravity);
  31178. };
  31179. /**
  31180. * Set the time step of the physics engine.
  31181. * default is 1/60.
  31182. * To slow it down, enter 1/600 for example.
  31183. * To speed it up, 1/30
  31184. * @param {number} newTimeStep the new timestep to apply to this world.
  31185. */
  31186. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  31187. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  31188. this._physicsPlugin.setTimeStep(newTimeStep);
  31189. };
  31190. PhysicsEngine.prototype.dispose = function () {
  31191. this._impostors.forEach(function (impostor) {
  31192. impostor.dispose();
  31193. });
  31194. this._physicsPlugin.dispose();
  31195. };
  31196. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  31197. return this._physicsPlugin.name;
  31198. };
  31199. /**
  31200. * Adding a new impostor for the impostor tracking.
  31201. * This will be done by the impostor itself.
  31202. * @param {PhysicsImpostor} impostor the impostor to add
  31203. */
  31204. PhysicsEngine.prototype.addImpostor = function (impostor) {
  31205. impostor.uniqueId = this._impostors.push(impostor);
  31206. //if no parent, generate the body
  31207. if (!impostor.parent) {
  31208. this._physicsPlugin.generatePhysicsBody(impostor);
  31209. }
  31210. };
  31211. /**
  31212. * Remove an impostor from the engine.
  31213. * This impostor and its mesh will not longer be updated by the physics engine.
  31214. * @param {PhysicsImpostor} impostor the impostor to remove
  31215. */
  31216. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  31217. var index = this._impostors.indexOf(impostor);
  31218. if (index > -1) {
  31219. var removed = this._impostors.splice(index, 1);
  31220. //Is it needed?
  31221. if (removed.length) {
  31222. //this will also remove it from the world.
  31223. removed[0].physicsBody = null;
  31224. }
  31225. }
  31226. };
  31227. /**
  31228. * Add a joint to the physics engine
  31229. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  31230. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  31231. * @param {PhysicsJoint} the joint that will connect both impostors.
  31232. */
  31233. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  31234. var impostorJoint = {
  31235. mainImpostor: mainImpostor,
  31236. connectedImpostor: connectedImpostor,
  31237. joint: joint
  31238. };
  31239. joint.physicsPlugin = this._physicsPlugin;
  31240. this._joints.push(impostorJoint);
  31241. this._physicsPlugin.generateJoint(impostorJoint);
  31242. };
  31243. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  31244. var matchingJoints = this._joints.filter(function (impostorJoint) {
  31245. return (impostorJoint.connectedImpostor === connectedImpostor
  31246. && impostorJoint.joint === joint
  31247. && impostorJoint.mainImpostor === mainImpostor);
  31248. });
  31249. if (matchingJoints.length) {
  31250. this._physicsPlugin.removeJoint(matchingJoints[0]);
  31251. }
  31252. };
  31253. /**
  31254. * Called by the scene. no need to call it.
  31255. */
  31256. PhysicsEngine.prototype._step = function (delta) {
  31257. var _this = this;
  31258. //check if any mesh has no body / requires an update
  31259. this._impostors.forEach(function (impostor) {
  31260. if (impostor.isBodyInitRequired()) {
  31261. _this._physicsPlugin.generatePhysicsBody(impostor);
  31262. }
  31263. });
  31264. if (delta > 0.1) {
  31265. delta = 0.1;
  31266. }
  31267. else if (delta <= 0) {
  31268. delta = 1.0 / 60.0;
  31269. }
  31270. this._physicsPlugin.executeStep(delta, this._impostors);
  31271. };
  31272. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  31273. return this._physicsPlugin;
  31274. };
  31275. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  31276. for (var i = 0; i < this._impostors.length; ++i) {
  31277. if (this._impostors[i].object === object) {
  31278. return this._impostors[i];
  31279. }
  31280. }
  31281. };
  31282. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  31283. for (var i = 0; i < this._impostors.length; ++i) {
  31284. if (this._impostors[i].physicsBody === body) {
  31285. return this._impostors[i];
  31286. }
  31287. }
  31288. };
  31289. // Statics, Legacy support.
  31290. /**
  31291. * @Deprecated
  31292. *
  31293. */
  31294. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  31295. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  31296. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  31297. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  31298. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  31299. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  31300. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  31301. PhysicsEngine.CapsuleImpostor = -1;
  31302. PhysicsEngine.ConeImpostor = -1;
  31303. PhysicsEngine.ConvexHullImpostor = -1;
  31304. PhysicsEngine.Epsilon = 0.001;
  31305. return PhysicsEngine;
  31306. }());
  31307. BABYLON.PhysicsEngine = PhysicsEngine;
  31308. })(BABYLON || (BABYLON = {}));
  31309. var BABYLON;
  31310. (function (BABYLON) {
  31311. var VertexData = (function () {
  31312. function VertexData() {
  31313. }
  31314. VertexData.prototype.set = function (data, kind) {
  31315. switch (kind) {
  31316. case BABYLON.VertexBuffer.PositionKind:
  31317. this.positions = data;
  31318. break;
  31319. case BABYLON.VertexBuffer.NormalKind:
  31320. this.normals = data;
  31321. break;
  31322. case BABYLON.VertexBuffer.UVKind:
  31323. this.uvs = data;
  31324. break;
  31325. case BABYLON.VertexBuffer.UV2Kind:
  31326. this.uvs2 = data;
  31327. break;
  31328. case BABYLON.VertexBuffer.UV3Kind:
  31329. this.uvs3 = data;
  31330. break;
  31331. case BABYLON.VertexBuffer.UV4Kind:
  31332. this.uvs4 = data;
  31333. break;
  31334. case BABYLON.VertexBuffer.UV5Kind:
  31335. this.uvs5 = data;
  31336. break;
  31337. case BABYLON.VertexBuffer.UV6Kind:
  31338. this.uvs6 = data;
  31339. break;
  31340. case BABYLON.VertexBuffer.ColorKind:
  31341. this.colors = data;
  31342. break;
  31343. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31344. this.matricesIndices = data;
  31345. break;
  31346. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31347. this.matricesWeights = data;
  31348. break;
  31349. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31350. this.matricesIndicesExtra = data;
  31351. break;
  31352. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31353. this.matricesWeightsExtra = data;
  31354. break;
  31355. }
  31356. };
  31357. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31358. this._applyTo(mesh, updatable);
  31359. };
  31360. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31361. this._applyTo(geometry, updatable);
  31362. };
  31363. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31364. this._update(mesh);
  31365. };
  31366. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31367. this._update(geometry);
  31368. };
  31369. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31370. if (this.positions) {
  31371. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31372. }
  31373. if (this.normals) {
  31374. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31375. }
  31376. if (this.uvs) {
  31377. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31378. }
  31379. if (this.uvs2) {
  31380. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31381. }
  31382. if (this.uvs3) {
  31383. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31384. }
  31385. if (this.uvs4) {
  31386. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31387. }
  31388. if (this.uvs5) {
  31389. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31390. }
  31391. if (this.uvs6) {
  31392. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31393. }
  31394. if (this.colors) {
  31395. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31396. }
  31397. if (this.matricesIndices) {
  31398. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31399. }
  31400. if (this.matricesWeights) {
  31401. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31402. }
  31403. if (this.matricesIndicesExtra) {
  31404. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31405. }
  31406. if (this.matricesWeightsExtra) {
  31407. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31408. }
  31409. if (this.indices) {
  31410. meshOrGeometry.setIndices(this.indices);
  31411. }
  31412. };
  31413. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31414. if (this.positions) {
  31415. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31416. }
  31417. if (this.normals) {
  31418. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31419. }
  31420. if (this.uvs) {
  31421. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31422. }
  31423. if (this.uvs2) {
  31424. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31425. }
  31426. if (this.uvs3) {
  31427. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31428. }
  31429. if (this.uvs4) {
  31430. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31431. }
  31432. if (this.uvs5) {
  31433. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31434. }
  31435. if (this.uvs6) {
  31436. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31437. }
  31438. if (this.colors) {
  31439. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31440. }
  31441. if (this.matricesIndices) {
  31442. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31443. }
  31444. if (this.matricesWeights) {
  31445. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31446. }
  31447. if (this.matricesIndicesExtra) {
  31448. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31449. }
  31450. if (this.matricesWeightsExtra) {
  31451. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31452. }
  31453. if (this.indices) {
  31454. meshOrGeometry.setIndices(this.indices);
  31455. }
  31456. };
  31457. VertexData.prototype.transform = function (matrix) {
  31458. var transformed = BABYLON.Vector3.Zero();
  31459. var index;
  31460. if (this.positions) {
  31461. var position = BABYLON.Vector3.Zero();
  31462. for (index = 0; index < this.positions.length; index += 3) {
  31463. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31464. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31465. this.positions[index] = transformed.x;
  31466. this.positions[index + 1] = transformed.y;
  31467. this.positions[index + 2] = transformed.z;
  31468. }
  31469. }
  31470. if (this.normals) {
  31471. var normal = BABYLON.Vector3.Zero();
  31472. for (index = 0; index < this.normals.length; index += 3) {
  31473. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31474. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31475. this.normals[index] = transformed.x;
  31476. this.normals[index + 1] = transformed.y;
  31477. this.normals[index + 2] = transformed.z;
  31478. }
  31479. }
  31480. };
  31481. VertexData.prototype.merge = function (other) {
  31482. if (other.indices) {
  31483. if (!this.indices) {
  31484. this.indices = [];
  31485. }
  31486. var offset = this.positions ? this.positions.length / 3 : 0;
  31487. for (var index = 0; index < other.indices.length; index++) {
  31488. //TODO check type - if Int32Array!
  31489. this.indices.push(other.indices[index] + offset);
  31490. }
  31491. }
  31492. this.positions = this._mergeElement(this.positions, other.positions);
  31493. this.normals = this._mergeElement(this.normals, other.normals);
  31494. this.uvs = this._mergeElement(this.uvs, other.uvs);
  31495. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  31496. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  31497. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  31498. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  31499. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  31500. this.colors = this._mergeElement(this.colors, other.colors);
  31501. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  31502. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  31503. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  31504. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  31505. };
  31506. VertexData.prototype._mergeElement = function (source, other) {
  31507. if (!other)
  31508. return source;
  31509. if (!source)
  31510. return other;
  31511. var len = other.length + source.length;
  31512. var isSrcTypedArray = source instanceof Float32Array;
  31513. var isOthTypedArray = other instanceof Float32Array;
  31514. // use non-loop method when the source is Float32Array
  31515. if (isSrcTypedArray) {
  31516. var ret32 = new Float32Array(len);
  31517. ret32.set(source);
  31518. ret32.set(other, source.length);
  31519. return ret32;
  31520. }
  31521. else if (!isOthTypedArray) {
  31522. return source.concat(other);
  31523. }
  31524. else {
  31525. var ret = source.slice(0); // copy source to a separate array
  31526. for (var i = 0, len = other.length; i < len; i++) {
  31527. ret.push(other[i]);
  31528. }
  31529. return ret;
  31530. }
  31531. };
  31532. VertexData.prototype.serialize = function () {
  31533. var serializationObject = this.serialize();
  31534. if (this.positions) {
  31535. serializationObject.positions = this.positions;
  31536. }
  31537. if (this.normals) {
  31538. serializationObject.normals = this.normals;
  31539. }
  31540. if (this.uvs) {
  31541. serializationObject.uvs = this.uvs;
  31542. }
  31543. if (this.uvs2) {
  31544. serializationObject.uvs2 = this.uvs2;
  31545. }
  31546. if (this.uvs3) {
  31547. serializationObject.uvs3 = this.uvs3;
  31548. }
  31549. if (this.uvs4) {
  31550. serializationObject.uvs4 = this.uvs4;
  31551. }
  31552. if (this.uvs5) {
  31553. serializationObject.uvs5 = this.uvs5;
  31554. }
  31555. if (this.uvs6) {
  31556. serializationObject.uvs6 = this.uvs6;
  31557. }
  31558. if (this.colors) {
  31559. serializationObject.colors = this.colors;
  31560. }
  31561. if (this.matricesIndices) {
  31562. serializationObject.matricesIndices = this.matricesIndices;
  31563. serializationObject.matricesIndices._isExpanded = true;
  31564. }
  31565. if (this.matricesWeights) {
  31566. serializationObject.matricesWeights = this.matricesWeights;
  31567. }
  31568. if (this.matricesIndicesExtra) {
  31569. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  31570. serializationObject.matricesIndicesExtra._isExpanded = true;
  31571. }
  31572. if (this.matricesWeightsExtra) {
  31573. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  31574. }
  31575. serializationObject.indices = this.indices;
  31576. return serializationObject;
  31577. };
  31578. // Statics
  31579. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  31580. return VertexData._ExtractFrom(mesh, copyWhenShared);
  31581. };
  31582. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  31583. return VertexData._ExtractFrom(geometry, copyWhenShared);
  31584. };
  31585. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  31586. var result = new VertexData();
  31587. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31588. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  31589. }
  31590. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31591. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  31592. }
  31593. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31594. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  31595. }
  31596. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31597. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  31598. }
  31599. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31600. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  31601. }
  31602. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31603. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  31604. }
  31605. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31606. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  31607. }
  31608. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31609. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  31610. }
  31611. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31612. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  31613. }
  31614. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31615. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  31616. }
  31617. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31618. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  31619. }
  31620. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  31621. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  31622. }
  31623. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  31624. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  31625. }
  31626. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  31627. return result;
  31628. };
  31629. VertexData.CreateRibbon = function (options) {
  31630. var pathArray = options.pathArray;
  31631. var closeArray = options.closeArray || false;
  31632. var closePath = options.closePath || false;
  31633. var invertUV = options.invertUV || false;
  31634. var defaultOffset = Math.floor(pathArray[0].length / 2);
  31635. var offset = options.offset || defaultOffset;
  31636. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  31637. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31638. var positions = [];
  31639. var indices = [];
  31640. var normals = [];
  31641. var uvs = [];
  31642. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  31643. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  31644. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  31645. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  31646. var minlg; // minimal length among all paths from pathArray
  31647. var lg = []; // array of path lengths : nb of vertex per path
  31648. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  31649. var p; // path iterator
  31650. var i; // point iterator
  31651. var j; // point iterator
  31652. // if single path in pathArray
  31653. if (pathArray.length < 2) {
  31654. var ar1 = [];
  31655. var ar2 = [];
  31656. for (i = 0; i < pathArray[0].length - offset; i++) {
  31657. ar1.push(pathArray[0][i]);
  31658. ar2.push(pathArray[0][i + offset]);
  31659. }
  31660. pathArray = [ar1, ar2];
  31661. }
  31662. // positions and horizontal distances (u)
  31663. var idc = 0;
  31664. var closePathCorr = (closePath) ? 1 : 0;
  31665. var path;
  31666. var l;
  31667. minlg = pathArray[0].length;
  31668. var vectlg;
  31669. var dist;
  31670. for (p = 0; p < pathArray.length; p++) {
  31671. uTotalDistance[p] = 0;
  31672. us[p] = [0];
  31673. path = pathArray[p];
  31674. l = path.length;
  31675. minlg = (minlg < l) ? minlg : l;
  31676. j = 0;
  31677. while (j < l) {
  31678. positions.push(path[j].x, path[j].y, path[j].z);
  31679. if (j > 0) {
  31680. vectlg = path[j].subtract(path[j - 1]).length();
  31681. dist = vectlg + uTotalDistance[p];
  31682. us[p].push(dist);
  31683. uTotalDistance[p] = dist;
  31684. }
  31685. j++;
  31686. }
  31687. if (closePath) {
  31688. j--;
  31689. positions.push(path[0].x, path[0].y, path[0].z);
  31690. vectlg = path[j].subtract(path[0]).length();
  31691. dist = vectlg + uTotalDistance[p];
  31692. us[p].push(dist);
  31693. uTotalDistance[p] = dist;
  31694. }
  31695. lg[p] = l + closePathCorr;
  31696. idx[p] = idc;
  31697. idc += (l + closePathCorr);
  31698. }
  31699. // vertical distances (v)
  31700. var path1;
  31701. var path2;
  31702. var vertex1;
  31703. var vertex2;
  31704. for (i = 0; i < minlg + closePathCorr; i++) {
  31705. vTotalDistance[i] = 0;
  31706. vs[i] = [0];
  31707. for (p = 0; p < pathArray.length - 1; p++) {
  31708. path1 = pathArray[p];
  31709. path2 = pathArray[p + 1];
  31710. if (i === minlg) {
  31711. vertex1 = path1[0];
  31712. vertex2 = path2[0];
  31713. }
  31714. else {
  31715. vertex1 = path1[i];
  31716. vertex2 = path2[i];
  31717. }
  31718. vectlg = vertex2.subtract(vertex1).length();
  31719. dist = vectlg + vTotalDistance[i];
  31720. vs[i].push(dist);
  31721. vTotalDistance[i] = dist;
  31722. }
  31723. if (closeArray) {
  31724. path1 = pathArray[p];
  31725. path2 = pathArray[0];
  31726. if (i === minlg) {
  31727. vertex2 = path2[0];
  31728. }
  31729. vectlg = vertex2.subtract(vertex1).length();
  31730. dist = vectlg + vTotalDistance[i];
  31731. vTotalDistance[i] = dist;
  31732. }
  31733. }
  31734. // uvs
  31735. var u;
  31736. var v;
  31737. for (p = 0; p < pathArray.length; p++) {
  31738. for (i = 0; i < minlg + closePathCorr; i++) {
  31739. u = us[p][i] / uTotalDistance[p];
  31740. v = vs[i][p] / vTotalDistance[i];
  31741. if (invertUV) {
  31742. uvs.push(v, u);
  31743. }
  31744. else {
  31745. uvs.push(u, v);
  31746. }
  31747. }
  31748. }
  31749. // indices
  31750. p = 0; // path index
  31751. var pi = 0; // positions array index
  31752. var l1 = lg[p] - 1; // path1 length
  31753. var l2 = lg[p + 1] - 1; // path2 length
  31754. var min = (l1 < l2) ? l1 : l2; // current path stop index
  31755. var shft = idx[1] - idx[0]; // shift
  31756. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  31757. while (pi <= min && p < path1nb) {
  31758. // 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
  31759. indices.push(pi, pi + shft, pi + 1);
  31760. indices.push(pi + shft + 1, pi + 1, pi + shft);
  31761. pi += 1;
  31762. if (pi === min) {
  31763. p++;
  31764. if (p === lg.length - 1) {
  31765. shft = idx[0] - idx[p];
  31766. l1 = lg[p] - 1;
  31767. l2 = lg[0] - 1;
  31768. }
  31769. else {
  31770. shft = idx[p + 1] - idx[p];
  31771. l1 = lg[p] - 1;
  31772. l2 = lg[p + 1] - 1;
  31773. }
  31774. pi = idx[p];
  31775. min = (l1 < l2) ? l1 + pi : l2 + pi;
  31776. }
  31777. }
  31778. // normals
  31779. VertexData.ComputeNormals(positions, indices, normals);
  31780. if (closePath) {
  31781. var indexFirst = 0;
  31782. var indexLast = 0;
  31783. for (p = 0; p < pathArray.length; p++) {
  31784. indexFirst = idx[p] * 3;
  31785. if (p + 1 < pathArray.length) {
  31786. indexLast = (idx[p + 1] - 1) * 3;
  31787. }
  31788. else {
  31789. indexLast = normals.length - 3;
  31790. }
  31791. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  31792. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  31793. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  31794. normals[indexLast] = normals[indexFirst];
  31795. normals[indexLast + 1] = normals[indexFirst + 1];
  31796. normals[indexLast + 2] = normals[indexFirst + 2];
  31797. }
  31798. }
  31799. // sides
  31800. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31801. // Result
  31802. var vertexData = new VertexData();
  31803. vertexData.indices = indices;
  31804. vertexData.positions = positions;
  31805. vertexData.normals = normals;
  31806. vertexData.uvs = uvs;
  31807. if (closePath) {
  31808. vertexData._idx = idx;
  31809. }
  31810. return vertexData;
  31811. };
  31812. VertexData.CreateBox = function (options) {
  31813. var normalsSource = [
  31814. new BABYLON.Vector3(0, 0, 1),
  31815. new BABYLON.Vector3(0, 0, -1),
  31816. new BABYLON.Vector3(1, 0, 0),
  31817. new BABYLON.Vector3(-1, 0, 0),
  31818. new BABYLON.Vector3(0, 1, 0),
  31819. new BABYLON.Vector3(0, -1, 0)
  31820. ];
  31821. var indices = [];
  31822. var positions = [];
  31823. var normals = [];
  31824. var uvs = [];
  31825. var width = options.width || options.size || 1;
  31826. var height = options.height || options.size || 1;
  31827. var depth = options.depth || options.size || 1;
  31828. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31829. var faceUV = options.faceUV || new Array(6);
  31830. var faceColors = options.faceColors;
  31831. var colors = [];
  31832. // default face colors and UV if undefined
  31833. for (var f = 0; f < 6; f++) {
  31834. if (faceUV[f] === undefined) {
  31835. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31836. }
  31837. if (faceColors && faceColors[f] === undefined) {
  31838. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31839. }
  31840. }
  31841. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31842. // Create each face in turn.
  31843. for (var index = 0; index < normalsSource.length; index++) {
  31844. var normal = normalsSource[index];
  31845. // Get two vectors perpendicular to the face normal and to each other.
  31846. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31847. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31848. // Six indices (two triangles) per face.
  31849. var verticesLength = positions.length / 3;
  31850. indices.push(verticesLength);
  31851. indices.push(verticesLength + 1);
  31852. indices.push(verticesLength + 2);
  31853. indices.push(verticesLength);
  31854. indices.push(verticesLength + 2);
  31855. indices.push(verticesLength + 3);
  31856. // Four vertices per face.
  31857. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31858. positions.push(vertex.x, vertex.y, vertex.z);
  31859. normals.push(normal.x, normal.y, normal.z);
  31860. uvs.push(faceUV[index].z, faceUV[index].w);
  31861. if (faceColors) {
  31862. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31863. }
  31864. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31865. positions.push(vertex.x, vertex.y, vertex.z);
  31866. normals.push(normal.x, normal.y, normal.z);
  31867. uvs.push(faceUV[index].x, faceUV[index].w);
  31868. if (faceColors) {
  31869. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31870. }
  31871. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31872. positions.push(vertex.x, vertex.y, vertex.z);
  31873. normals.push(normal.x, normal.y, normal.z);
  31874. uvs.push(faceUV[index].x, faceUV[index].y);
  31875. if (faceColors) {
  31876. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31877. }
  31878. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31879. positions.push(vertex.x, vertex.y, vertex.z);
  31880. normals.push(normal.x, normal.y, normal.z);
  31881. uvs.push(faceUV[index].z, faceUV[index].y);
  31882. if (faceColors) {
  31883. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31884. }
  31885. }
  31886. // sides
  31887. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31888. // Result
  31889. var vertexData = new VertexData();
  31890. vertexData.indices = indices;
  31891. vertexData.positions = positions;
  31892. vertexData.normals = normals;
  31893. vertexData.uvs = uvs;
  31894. if (faceColors) {
  31895. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31896. vertexData.colors = totalColors;
  31897. }
  31898. return vertexData;
  31899. };
  31900. VertexData.CreateSphere = function (options) {
  31901. var segments = options.segments || 32;
  31902. var diameterX = options.diameterX || options.diameter || 1;
  31903. var diameterY = options.diameterY || options.diameter || 1;
  31904. var diameterZ = options.diameterZ || options.diameter || 1;
  31905. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31906. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31907. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31908. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31909. var totalZRotationSteps = 2 + segments;
  31910. var totalYRotationSteps = 2 * totalZRotationSteps;
  31911. var indices = [];
  31912. var positions = [];
  31913. var normals = [];
  31914. var uvs = [];
  31915. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31916. var normalizedZ = zRotationStep / totalZRotationSteps;
  31917. var angleZ = normalizedZ * Math.PI * slice;
  31918. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31919. var normalizedY = yRotationStep / totalYRotationSteps;
  31920. var angleY = normalizedY * Math.PI * 2 * arc;
  31921. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31922. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31923. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31924. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31925. var vertex = complete.multiply(radius);
  31926. var normal = complete.divide(radius).normalize();
  31927. positions.push(vertex.x, vertex.y, vertex.z);
  31928. normals.push(normal.x, normal.y, normal.z);
  31929. uvs.push(normalizedY, normalizedZ);
  31930. }
  31931. if (zRotationStep > 0) {
  31932. var verticesCount = positions.length / 3;
  31933. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31934. indices.push((firstIndex));
  31935. indices.push((firstIndex + 1));
  31936. indices.push(firstIndex + totalYRotationSteps + 1);
  31937. indices.push((firstIndex + totalYRotationSteps + 1));
  31938. indices.push((firstIndex + 1));
  31939. indices.push((firstIndex + totalYRotationSteps + 2));
  31940. }
  31941. }
  31942. }
  31943. // Sides
  31944. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31945. // Result
  31946. var vertexData = new VertexData();
  31947. vertexData.indices = indices;
  31948. vertexData.positions = positions;
  31949. vertexData.normals = normals;
  31950. vertexData.uvs = uvs;
  31951. return vertexData;
  31952. };
  31953. // Cylinder and cone
  31954. VertexData.CreateCylinder = function (options) {
  31955. var height = options.height || 2;
  31956. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31957. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31958. var tessellation = options.tessellation || 24;
  31959. var subdivisions = options.subdivisions || 1;
  31960. var hasRings = options.hasRings;
  31961. var enclose = options.enclose;
  31962. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31963. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31964. var faceUV = options.faceUV || new Array(3);
  31965. var faceColors = options.faceColors;
  31966. // default face colors and UV if undefined
  31967. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31968. var ringNb = (hasRings) ? subdivisions : 1;
  31969. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31970. var f;
  31971. for (f = 0; f < surfaceNb; f++) {
  31972. if (faceColors && faceColors[f] === undefined) {
  31973. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31974. }
  31975. }
  31976. for (f = 0; f < surfaceNb; f++) {
  31977. if (faceUV && faceUV[f] === undefined) {
  31978. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31979. }
  31980. }
  31981. var indices = [];
  31982. var positions = [];
  31983. var normals = [];
  31984. var uvs = [];
  31985. var colors = [];
  31986. var angle_step = Math.PI * 2 * arc / tessellation;
  31987. var angle;
  31988. var h;
  31989. var radius;
  31990. var tan = (diameterBottom - diameterTop) / 2 / height;
  31991. var ringVertex = BABYLON.Vector3.Zero();
  31992. var ringNormal = BABYLON.Vector3.Zero();
  31993. var ringFirstVertex = BABYLON.Vector3.Zero();
  31994. var ringFirstNormal = BABYLON.Vector3.Zero();
  31995. var quadNormal = BABYLON.Vector3.Zero();
  31996. var Y = BABYLON.Axis.Y;
  31997. // positions, normals, uvs
  31998. var i;
  31999. var j;
  32000. var r;
  32001. var ringIdx = 1;
  32002. var s = 1; // surface index
  32003. var cs = 0;
  32004. var v = 0;
  32005. for (i = 0; i <= subdivisions; i++) {
  32006. h = i / subdivisions;
  32007. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32008. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32009. for (r = 0; r < ringIdx; r++) {
  32010. if (hasRings) {
  32011. s += r;
  32012. }
  32013. if (enclose) {
  32014. s += 2 * r;
  32015. }
  32016. for (j = 0; j <= tessellation; j++) {
  32017. angle = j * angle_step;
  32018. // position
  32019. ringVertex.x = Math.cos(-angle) * radius;
  32020. ringVertex.y = -height / 2 + h * height;
  32021. ringVertex.z = Math.sin(-angle) * radius;
  32022. // normal
  32023. if (diameterTop === 0 && i === subdivisions) {
  32024. // if no top cap, reuse former normals
  32025. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32026. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32027. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32028. }
  32029. else {
  32030. ringNormal.x = ringVertex.x;
  32031. ringNormal.z = ringVertex.z;
  32032. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32033. ringNormal.normalize();
  32034. }
  32035. // keep first ring vertex values for enclose
  32036. if (j === 0) {
  32037. ringFirstVertex.copyFrom(ringVertex);
  32038. ringFirstNormal.copyFrom(ringNormal);
  32039. }
  32040. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32041. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32042. if (hasRings) {
  32043. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32044. }
  32045. else {
  32046. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32047. }
  32048. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32049. if (faceColors) {
  32050. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32051. }
  32052. }
  32053. // if enclose, add four vertices and their dedicated normals
  32054. if (arc !== 1 && enclose) {
  32055. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32056. positions.push(0, ringVertex.y, 0);
  32057. positions.push(0, ringVertex.y, 0);
  32058. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32059. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32060. quadNormal.normalize();
  32061. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32062. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32063. quadNormal.normalize();
  32064. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32065. if (hasRings) {
  32066. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32067. }
  32068. else {
  32069. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32070. }
  32071. uvs.push(faceUV[s + 1].x, v);
  32072. uvs.push(faceUV[s + 1].z, v);
  32073. if (hasRings) {
  32074. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32075. }
  32076. else {
  32077. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32078. }
  32079. uvs.push(faceUV[s + 2].x, v);
  32080. uvs.push(faceUV[s + 2].z, v);
  32081. if (faceColors) {
  32082. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32083. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32084. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32085. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32086. }
  32087. }
  32088. if (cs !== s) {
  32089. cs = s;
  32090. }
  32091. }
  32092. }
  32093. // indices
  32094. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32095. var s;
  32096. i = 0;
  32097. for (s = 0; s < subdivisions; s++) {
  32098. for (j = 0; j < tessellation; j++) {
  32099. var i0 = i * (e + 1) + j;
  32100. var i1 = (i + 1) * (e + 1) + j;
  32101. var i2 = i * (e + 1) + (j + 1);
  32102. var i3 = (i + 1) * (e + 1) + (j + 1);
  32103. indices.push(i0, i1, i2);
  32104. indices.push(i3, i2, i1);
  32105. }
  32106. if (arc !== 1 && enclose) {
  32107. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32108. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32109. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32110. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32111. }
  32112. i = (hasRings) ? (i + 2) : (i + 1);
  32113. }
  32114. // Caps
  32115. var createCylinderCap = function (isTop) {
  32116. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32117. if (radius === 0) {
  32118. return;
  32119. }
  32120. // Cap positions, normals & uvs
  32121. var angle;
  32122. var circleVector;
  32123. var i;
  32124. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32125. var c;
  32126. if (faceColors) {
  32127. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32128. }
  32129. // cap center
  32130. var vbase = positions.length / 3;
  32131. var offset = isTop ? height / 2 : -height / 2;
  32132. var center = new BABYLON.Vector3(0, offset, 0);
  32133. positions.push(center.x, center.y, center.z);
  32134. normals.push(0, isTop ? 1 : -1, 0);
  32135. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32136. if (faceColors) {
  32137. colors.push(c.r, c.g, c.b, c.a);
  32138. }
  32139. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32140. for (i = 0; i <= tessellation; i++) {
  32141. angle = Math.PI * 2 * i * arc / tessellation;
  32142. var cos = Math.cos(-angle);
  32143. var sin = Math.sin(-angle);
  32144. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32145. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32146. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32147. normals.push(0, isTop ? 1 : -1, 0);
  32148. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32149. if (faceColors) {
  32150. colors.push(c.r, c.g, c.b, c.a);
  32151. }
  32152. }
  32153. // Cap indices
  32154. for (i = 0; i < tessellation; i++) {
  32155. if (!isTop) {
  32156. indices.push(vbase);
  32157. indices.push(vbase + (i + 1));
  32158. indices.push(vbase + (i + 2));
  32159. }
  32160. else {
  32161. indices.push(vbase);
  32162. indices.push(vbase + (i + 2));
  32163. indices.push(vbase + (i + 1));
  32164. }
  32165. }
  32166. };
  32167. // add caps to geometry
  32168. createCylinderCap(false);
  32169. createCylinderCap(true);
  32170. // Sides
  32171. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32172. var vertexData = new VertexData();
  32173. vertexData.indices = indices;
  32174. vertexData.positions = positions;
  32175. vertexData.normals = normals;
  32176. vertexData.uvs = uvs;
  32177. if (faceColors) {
  32178. vertexData.colors = colors;
  32179. }
  32180. return vertexData;
  32181. };
  32182. VertexData.CreateTorus = function (options) {
  32183. var indices = [];
  32184. var positions = [];
  32185. var normals = [];
  32186. var uvs = [];
  32187. var diameter = options.diameter || 1;
  32188. var thickness = options.thickness || 0.5;
  32189. var tessellation = options.tessellation || 16;
  32190. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32191. var stride = tessellation + 1;
  32192. for (var i = 0; i <= tessellation; i++) {
  32193. var u = i / tessellation;
  32194. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32195. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32196. for (var j = 0; j <= tessellation; j++) {
  32197. var v = 1 - j / tessellation;
  32198. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32199. var dx = Math.cos(innerAngle);
  32200. var dy = Math.sin(innerAngle);
  32201. // Create a vertex.
  32202. var normal = new BABYLON.Vector3(dx, dy, 0);
  32203. var position = normal.scale(thickness / 2);
  32204. var textureCoordinate = new BABYLON.Vector2(u, v);
  32205. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32206. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32207. positions.push(position.x, position.y, position.z);
  32208. normals.push(normal.x, normal.y, normal.z);
  32209. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32210. // And create indices for two triangles.
  32211. var nextI = (i + 1) % stride;
  32212. var nextJ = (j + 1) % stride;
  32213. indices.push(i * stride + j);
  32214. indices.push(i * stride + nextJ);
  32215. indices.push(nextI * stride + j);
  32216. indices.push(i * stride + nextJ);
  32217. indices.push(nextI * stride + nextJ);
  32218. indices.push(nextI * stride + j);
  32219. }
  32220. }
  32221. // Sides
  32222. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32223. // Result
  32224. var vertexData = new VertexData();
  32225. vertexData.indices = indices;
  32226. vertexData.positions = positions;
  32227. vertexData.normals = normals;
  32228. vertexData.uvs = uvs;
  32229. return vertexData;
  32230. };
  32231. VertexData.CreateLineSystem = function (options) {
  32232. var indices = [];
  32233. var positions = [];
  32234. var lines = options.lines;
  32235. var idx = 0;
  32236. for (var l = 0; l < lines.length; l++) {
  32237. var points = lines[l];
  32238. for (var index = 0; index < points.length; index++) {
  32239. positions.push(points[index].x, points[index].y, points[index].z);
  32240. if (index > 0) {
  32241. indices.push(idx - 1);
  32242. indices.push(idx);
  32243. }
  32244. idx++;
  32245. }
  32246. }
  32247. var vertexData = new VertexData();
  32248. vertexData.indices = indices;
  32249. vertexData.positions = positions;
  32250. return vertexData;
  32251. };
  32252. VertexData.CreateDashedLines = function (options) {
  32253. var dashSize = options.dashSize || 3;
  32254. var gapSize = options.gapSize || 1;
  32255. var dashNb = options.dashNb || 200;
  32256. var points = options.points;
  32257. var positions = new Array();
  32258. var indices = new Array();
  32259. var curvect = BABYLON.Vector3.Zero();
  32260. var lg = 0;
  32261. var nb = 0;
  32262. var shft = 0;
  32263. var dashshft = 0;
  32264. var curshft = 0;
  32265. var idx = 0;
  32266. var i = 0;
  32267. for (i = 0; i < points.length - 1; i++) {
  32268. points[i + 1].subtractToRef(points[i], curvect);
  32269. lg += curvect.length();
  32270. }
  32271. shft = lg / dashNb;
  32272. dashshft = dashSize * shft / (dashSize + gapSize);
  32273. for (i = 0; i < points.length - 1; i++) {
  32274. points[i + 1].subtractToRef(points[i], curvect);
  32275. nb = Math.floor(curvect.length() / shft);
  32276. curvect.normalize();
  32277. for (var j = 0; j < nb; j++) {
  32278. curshft = shft * j;
  32279. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32280. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32281. indices.push(idx, idx + 1);
  32282. idx += 2;
  32283. }
  32284. }
  32285. // Result
  32286. var vertexData = new VertexData();
  32287. vertexData.positions = positions;
  32288. vertexData.indices = indices;
  32289. return vertexData;
  32290. };
  32291. VertexData.CreateGround = function (options) {
  32292. var indices = [];
  32293. var positions = [];
  32294. var normals = [];
  32295. var uvs = [];
  32296. var row, col;
  32297. var width = options.width || 1;
  32298. var height = options.height || 1;
  32299. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32300. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32301. for (row = 0; row <= subdivisionsY; row++) {
  32302. for (col = 0; col <= subdivisionsX; col++) {
  32303. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32304. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32305. positions.push(position.x, position.y, position.z);
  32306. normals.push(normal.x, normal.y, normal.z);
  32307. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  32308. }
  32309. }
  32310. for (row = 0; row < subdivisionsY; row++) {
  32311. for (col = 0; col < subdivisionsX; col++) {
  32312. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32313. indices.push(col + 1 + row * (subdivisionsX + 1));
  32314. indices.push(col + row * (subdivisionsX + 1));
  32315. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32316. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32317. indices.push(col + row * (subdivisionsX + 1));
  32318. }
  32319. }
  32320. // Result
  32321. var vertexData = new VertexData();
  32322. vertexData.indices = indices;
  32323. vertexData.positions = positions;
  32324. vertexData.normals = normals;
  32325. vertexData.uvs = uvs;
  32326. return vertexData;
  32327. };
  32328. VertexData.CreateTiledGround = function (options) {
  32329. var xmin = options.xmin || -1.0;
  32330. var zmin = options.zmin || -1.0;
  32331. var xmax = options.xmax || 1.0;
  32332. var zmax = options.zmax || 1.0;
  32333. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32334. var precision = options.precision || { w: 1, h: 1 };
  32335. var indices = [];
  32336. var positions = [];
  32337. var normals = [];
  32338. var uvs = [];
  32339. var row, col, tileRow, tileCol;
  32340. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32341. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32342. precision.w = (precision.w < 1) ? 1 : precision.w;
  32343. precision.h = (precision.h < 1) ? 1 : precision.h;
  32344. var tileSize = {
  32345. 'w': (xmax - xmin) / subdivisions.w,
  32346. 'h': (zmax - zmin) / subdivisions.h
  32347. };
  32348. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32349. // Indices
  32350. var base = positions.length / 3;
  32351. var rowLength = precision.w + 1;
  32352. for (row = 0; row < precision.h; row++) {
  32353. for (col = 0; col < precision.w; col++) {
  32354. var square = [
  32355. base + col + row * rowLength,
  32356. base + (col + 1) + row * rowLength,
  32357. base + (col + 1) + (row + 1) * rowLength,
  32358. base + col + (row + 1) * rowLength
  32359. ];
  32360. indices.push(square[1]);
  32361. indices.push(square[2]);
  32362. indices.push(square[3]);
  32363. indices.push(square[0]);
  32364. indices.push(square[1]);
  32365. indices.push(square[3]);
  32366. }
  32367. }
  32368. // Position, normals and uvs
  32369. var position = BABYLON.Vector3.Zero();
  32370. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32371. for (row = 0; row <= precision.h; row++) {
  32372. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32373. for (col = 0; col <= precision.w; col++) {
  32374. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32375. position.y = 0;
  32376. positions.push(position.x, position.y, position.z);
  32377. normals.push(normal.x, normal.y, normal.z);
  32378. uvs.push(col / precision.w, row / precision.h);
  32379. }
  32380. }
  32381. }
  32382. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  32383. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  32384. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  32385. }
  32386. }
  32387. // Result
  32388. var vertexData = new VertexData();
  32389. vertexData.indices = indices;
  32390. vertexData.positions = positions;
  32391. vertexData.normals = normals;
  32392. vertexData.uvs = uvs;
  32393. return vertexData;
  32394. };
  32395. VertexData.CreateGroundFromHeightMap = function (options) {
  32396. var indices = [];
  32397. var positions = [];
  32398. var normals = [];
  32399. var uvs = [];
  32400. var row, col;
  32401. // Vertices
  32402. for (row = 0; row <= options.subdivisions; row++) {
  32403. for (col = 0; col <= options.subdivisions; col++) {
  32404. 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));
  32405. // Compute height
  32406. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  32407. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  32408. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  32409. var r = options.buffer[pos] / 255.0;
  32410. var g = options.buffer[pos + 1] / 255.0;
  32411. var b = options.buffer[pos + 2] / 255.0;
  32412. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32413. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  32414. // Add vertex
  32415. positions.push(position.x, position.y, position.z);
  32416. normals.push(0, 0, 0);
  32417. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  32418. }
  32419. }
  32420. // Indices
  32421. for (row = 0; row < options.subdivisions; row++) {
  32422. for (col = 0; col < options.subdivisions; col++) {
  32423. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32424. indices.push(col + 1 + row * (options.subdivisions + 1));
  32425. indices.push(col + row * (options.subdivisions + 1));
  32426. indices.push(col + (row + 1) * (options.subdivisions + 1));
  32427. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32428. indices.push(col + row * (options.subdivisions + 1));
  32429. }
  32430. }
  32431. // Normals
  32432. VertexData.ComputeNormals(positions, indices, normals);
  32433. // Result
  32434. var vertexData = new VertexData();
  32435. vertexData.indices = indices;
  32436. vertexData.positions = positions;
  32437. vertexData.normals = normals;
  32438. vertexData.uvs = uvs;
  32439. return vertexData;
  32440. };
  32441. VertexData.CreatePlane = function (options) {
  32442. var indices = [];
  32443. var positions = [];
  32444. var normals = [];
  32445. var uvs = [];
  32446. var width = options.width || options.size || 1;
  32447. var height = options.height || options.size || 1;
  32448. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32449. // Vertices
  32450. var halfWidth = width / 2.0;
  32451. var halfHeight = height / 2.0;
  32452. positions.push(-halfWidth, -halfHeight, 0);
  32453. normals.push(0, 0, -1.0);
  32454. uvs.push(0.0, 0.0);
  32455. positions.push(halfWidth, -halfHeight, 0);
  32456. normals.push(0, 0, -1.0);
  32457. uvs.push(1.0, 0.0);
  32458. positions.push(halfWidth, halfHeight, 0);
  32459. normals.push(0, 0, -1.0);
  32460. uvs.push(1.0, 1.0);
  32461. positions.push(-halfWidth, halfHeight, 0);
  32462. normals.push(0, 0, -1.0);
  32463. uvs.push(0.0, 1.0);
  32464. // Indices
  32465. indices.push(0);
  32466. indices.push(1);
  32467. indices.push(2);
  32468. indices.push(0);
  32469. indices.push(2);
  32470. indices.push(3);
  32471. // Sides
  32472. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32473. // Result
  32474. var vertexData = new VertexData();
  32475. vertexData.indices = indices;
  32476. vertexData.positions = positions;
  32477. vertexData.normals = normals;
  32478. vertexData.uvs = uvs;
  32479. return vertexData;
  32480. };
  32481. VertexData.CreateDisc = function (options) {
  32482. var positions = [];
  32483. var indices = [];
  32484. var normals = [];
  32485. var uvs = [];
  32486. var radius = options.radius || 0.5;
  32487. var tessellation = options.tessellation || 64;
  32488. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32489. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32490. // positions and uvs
  32491. positions.push(0, 0, 0); // disc center first
  32492. uvs.push(0.5, 0.5);
  32493. var theta = Math.PI * 2 * arc;
  32494. var step = theta / tessellation;
  32495. for (var a = 0; a < theta; a += step) {
  32496. var x = Math.cos(a);
  32497. var y = Math.sin(a);
  32498. var u = (x + 1) / 2;
  32499. var v = (1 - y) / 2;
  32500. positions.push(radius * x, radius * y, 0);
  32501. uvs.push(u, v);
  32502. }
  32503. if (arc === 1) {
  32504. positions.push(positions[3], positions[4], positions[5]); // close the circle
  32505. uvs.push(uvs[2], uvs[3]);
  32506. }
  32507. //indices
  32508. var vertexNb = positions.length / 3;
  32509. for (var i = 1; i < vertexNb - 1; i++) {
  32510. indices.push(i + 1, 0, i);
  32511. }
  32512. // result
  32513. VertexData.ComputeNormals(positions, indices, normals);
  32514. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32515. var vertexData = new VertexData();
  32516. vertexData.indices = indices;
  32517. vertexData.positions = positions;
  32518. vertexData.normals = normals;
  32519. vertexData.uvs = uvs;
  32520. return vertexData;
  32521. };
  32522. VertexData.CreateIcoSphere = function (options) {
  32523. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32524. var radius = options.radius || 1;
  32525. var flat = (options.flat === undefined) ? true : options.flat;
  32526. var subdivisions = options.subdivisions || 4;
  32527. var radiusX = options.radiusX || radius;
  32528. var radiusY = options.radiusY || radius;
  32529. var radiusZ = options.radiusZ || radius;
  32530. var t = (1 + Math.sqrt(5)) / 2;
  32531. // 12 vertex x,y,z
  32532. var ico_vertices = [
  32533. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  32534. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  32535. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  32536. ];
  32537. // index of 3 vertex makes a face of icopshere
  32538. var ico_indices = [
  32539. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  32540. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  32541. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  32542. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  32543. ];
  32544. // vertex for uv have aliased position, not for UV
  32545. var vertices_unalias_id = [
  32546. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  32547. // vertex alias
  32548. 0,
  32549. 2,
  32550. 3,
  32551. 3,
  32552. 3,
  32553. 4,
  32554. 7,
  32555. 8,
  32556. 9,
  32557. 9,
  32558. 10,
  32559. 11 // 23: B + 12
  32560. ];
  32561. // uv as integer step (not pixels !)
  32562. var ico_vertexuv = [
  32563. 5, 1, 3, 1, 6, 4, 0, 0,
  32564. 5, 3, 4, 2, 2, 2, 4, 0,
  32565. 2, 0, 1, 1, 6, 0, 6, 2,
  32566. // vertex alias (for same vertex on different faces)
  32567. 0, 4,
  32568. 3, 3,
  32569. 4, 4,
  32570. 3, 1,
  32571. 4, 2,
  32572. 4, 4,
  32573. 0, 2,
  32574. 1, 1,
  32575. 2, 2,
  32576. 3, 3,
  32577. 1, 3,
  32578. 2, 4 // 23: B + 12
  32579. ];
  32580. // Vertices[0, 1, ...9, A, B] : position on UV plane
  32581. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  32582. // First island of uv mapping
  32583. // v = 4h 3+ 2
  32584. // v = 3h 9+ 4
  32585. // v = 2h 9+ 5 B
  32586. // v = 1h 9 1 0
  32587. // v = 0h 3 8 7 A
  32588. // u = 0 1 2 3 4 5 6 *a
  32589. // Second island of uv mapping
  32590. // v = 4h 0+ B+ 4+
  32591. // v = 3h A+ 2+
  32592. // v = 2h 7+ 6 3+
  32593. // v = 1h 8+ 3+
  32594. // v = 0h
  32595. // u = 0 1 2 3 4 5 6 *a
  32596. // Face layout on texture UV mapping
  32597. // ============
  32598. // \ 4 /\ 16 / ======
  32599. // \ / \ / /\ 11 /
  32600. // \/ 7 \/ / \ /
  32601. // ======= / 10 \/
  32602. // /\ 17 /\ =======
  32603. // / \ / \ \ 15 /\
  32604. // / 8 \/ 12 \ \ / \
  32605. // ============ \/ 6 \
  32606. // \ 18 /\ ============
  32607. // \ / \ \ 5 /\ 0 /
  32608. // \/ 13 \ \ / \ /
  32609. // ======= \/ 1 \/
  32610. // =============
  32611. // /\ 19 /\ 2 /\
  32612. // / \ / \ / \
  32613. // / 14 \/ 9 \/ 3 \
  32614. // ===================
  32615. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  32616. var ustep = 138 / 1024;
  32617. var vstep = 239 / 1024;
  32618. var uoffset = 60 / 1024;
  32619. var voffset = 26 / 1024;
  32620. // Second island should have margin, not to touch the first island
  32621. // avoid any borderline artefact in pixel rounding
  32622. var island_u_offset = -40 / 1024;
  32623. var island_v_offset = +20 / 1024;
  32624. // face is either island 0 or 1 :
  32625. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  32626. var island = [
  32627. 0, 0, 0, 0, 1,
  32628. 0, 0, 1, 1, 0,
  32629. 0, 0, 1, 1, 0,
  32630. 0, 1, 1, 1, 0 // 15 - 19
  32631. ];
  32632. var indices = [];
  32633. var positions = [];
  32634. var normals = [];
  32635. var uvs = [];
  32636. var current_indice = 0;
  32637. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  32638. var face_vertex_pos = new Array(3);
  32639. var face_vertex_uv = new Array(3);
  32640. var v012;
  32641. for (v012 = 0; v012 < 3; v012++) {
  32642. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  32643. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  32644. }
  32645. // create all with normals
  32646. for (var face = 0; face < 20; face++) {
  32647. // 3 vertex per face
  32648. for (v012 = 0; v012 < 3; v012++) {
  32649. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  32650. var v_id = ico_indices[3 * face + v012];
  32651. // vertex have 3D position (x,y,z)
  32652. 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]);
  32653. // Normalize to get normal, then scale to radius
  32654. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  32655. // uv Coordinates from vertex ID
  32656. 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);
  32657. }
  32658. // Subdivide the face (interpolate pos, norm, uv)
  32659. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  32660. // - norm is linear interpolation of vertex corner normal
  32661. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  32662. // - uv is linear interpolation
  32663. //
  32664. // Topology is as below for sub-divide by 2
  32665. // vertex shown as v0,v1,v2
  32666. // interp index is i1 to progress in range [v0,v1[
  32667. // interp index is i2 to progress in range [v0,v2[
  32668. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  32669. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32670. //
  32671. //
  32672. // i2 v2
  32673. // ^ ^
  32674. // / / \
  32675. // / / \
  32676. // / / \
  32677. // / / (0,1) \
  32678. // / #---------\
  32679. // / / \ (0,0)'/ \
  32680. // / / \ / \
  32681. // / / \ / \
  32682. // / / (0,0) \ / (1,0) \
  32683. // / #---------#---------\
  32684. // v0 v1
  32685. //
  32686. // --------------------> i1
  32687. //
  32688. // interp of (i1,i2):
  32689. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32690. // along i1 : lerp(x0,x1, i1/(S-i2))
  32691. //
  32692. // centroid of triangle is needed to get help normal computation
  32693. // (c1,c2) are used for centroid location
  32694. var interp_vertex = function (i1, i2, c1, c2) {
  32695. // vertex is interpolated from
  32696. // - face_vertex_pos[0..2]
  32697. // - face_vertex_uv[0..2]
  32698. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32699. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32700. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32701. pos_interp.normalize();
  32702. var vertex_normal;
  32703. if (flat) {
  32704. // in flat mode, recalculate normal as face centroid normal
  32705. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32706. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32707. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32708. }
  32709. else {
  32710. // in smooth mode, recalculate normal from each single vertex position
  32711. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32712. }
  32713. // Vertex normal need correction due to X,Y,Z radius scaling
  32714. vertex_normal.x /= radiusX;
  32715. vertex_normal.y /= radiusY;
  32716. vertex_normal.z /= radiusZ;
  32717. vertex_normal.normalize();
  32718. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32719. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32720. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32721. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32722. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32723. uvs.push(uv_interp.x, uv_interp.y);
  32724. // push each vertex has member of a face
  32725. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32726. indices.push(current_indice);
  32727. current_indice++;
  32728. };
  32729. for (var i2 = 0; i2 < subdivisions; i2++) {
  32730. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32731. // face : (i1,i2) for /\ :
  32732. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32733. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32734. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32735. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32736. if (i1 + i2 + 1 < subdivisions) {
  32737. // face : (i1,i2)' for \/ :
  32738. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32739. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32740. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32741. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32742. }
  32743. }
  32744. }
  32745. }
  32746. // Sides
  32747. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32748. // Result
  32749. var vertexData = new VertexData();
  32750. vertexData.indices = indices;
  32751. vertexData.positions = positions;
  32752. vertexData.normals = normals;
  32753. vertexData.uvs = uvs;
  32754. return vertexData;
  32755. };
  32756. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32757. VertexData.CreatePolyhedron = function (options) {
  32758. // provided polyhedron types :
  32759. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32760. // 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)
  32761. var polyhedra = [];
  32762. 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]] };
  32763. 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]] };
  32764. polyhedra[2] = {
  32765. 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]],
  32766. 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]]
  32767. };
  32768. polyhedra[3] = {
  32769. 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]],
  32770. 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]]
  32771. };
  32772. polyhedra[4] = {
  32773. 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]],
  32774. 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]]
  32775. };
  32776. 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]] };
  32777. 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]] };
  32778. 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]] };
  32779. 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]] };
  32780. 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]] };
  32781. 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]] };
  32782. 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]] };
  32783. 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]] };
  32784. 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]] };
  32785. polyhedra[14] = {
  32786. 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]],
  32787. 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]]
  32788. };
  32789. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32790. var size = options.size;
  32791. var sizeX = options.sizeX || size || 1;
  32792. var sizeY = options.sizeY || size || 1;
  32793. var sizeZ = options.sizeZ || size || 1;
  32794. var data = options.custom || polyhedra[type];
  32795. var nbfaces = data.face.length;
  32796. var faceUV = options.faceUV || new Array(nbfaces);
  32797. var faceColors = options.faceColors;
  32798. var flat = (options.flat === undefined) ? true : options.flat;
  32799. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32800. var positions = [];
  32801. var indices = [];
  32802. var normals = [];
  32803. var uvs = [];
  32804. var colors = [];
  32805. var index = 0;
  32806. var faceIdx = 0; // face cursor in the array "indexes"
  32807. var indexes = [];
  32808. var i = 0;
  32809. var f = 0;
  32810. var u, v, ang, x, y, tmp;
  32811. // default face colors and UV if undefined
  32812. if (flat) {
  32813. for (f = 0; f < nbfaces; f++) {
  32814. if (faceColors && faceColors[f] === undefined) {
  32815. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32816. }
  32817. if (faceUV && faceUV[f] === undefined) {
  32818. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32819. }
  32820. }
  32821. }
  32822. if (!flat) {
  32823. for (i = 0; i < data.vertex.length; i++) {
  32824. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32825. uvs.push(0, 0);
  32826. }
  32827. for (f = 0; f < nbfaces; f++) {
  32828. for (i = 0; i < data.face[f].length - 2; i++) {
  32829. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32830. }
  32831. }
  32832. }
  32833. else {
  32834. for (f = 0; f < nbfaces; f++) {
  32835. var fl = data.face[f].length; // number of vertices of the current face
  32836. ang = 2 * Math.PI / fl;
  32837. x = 0.5 * Math.tan(ang / 2);
  32838. y = 0.5;
  32839. // positions, uvs, colors
  32840. for (i = 0; i < fl; i++) {
  32841. // positions
  32842. 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);
  32843. indexes.push(index);
  32844. index++;
  32845. // uvs
  32846. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32847. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32848. uvs.push(u, v);
  32849. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32850. y = x * Math.sin(ang) + y * Math.cos(ang);
  32851. x = tmp;
  32852. // colors
  32853. if (faceColors) {
  32854. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32855. }
  32856. }
  32857. // indices from indexes
  32858. for (i = 0; i < fl - 2; i++) {
  32859. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32860. }
  32861. faceIdx += fl;
  32862. }
  32863. }
  32864. VertexData.ComputeNormals(positions, indices, normals);
  32865. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32866. var vertexData = new VertexData();
  32867. vertexData.positions = positions;
  32868. vertexData.indices = indices;
  32869. vertexData.normals = normals;
  32870. vertexData.uvs = uvs;
  32871. if (faceColors && flat) {
  32872. vertexData.colors = colors;
  32873. }
  32874. return vertexData;
  32875. };
  32876. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32877. VertexData.CreateTorusKnot = function (options) {
  32878. var indices = [];
  32879. var positions = [];
  32880. var normals = [];
  32881. var uvs = [];
  32882. var radius = options.radius || 2;
  32883. var tube = options.tube || 0.5;
  32884. var radialSegments = options.radialSegments || 32;
  32885. var tubularSegments = options.tubularSegments || 32;
  32886. var p = options.p || 2;
  32887. var q = options.q || 3;
  32888. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32889. // Helper
  32890. var getPos = function (angle) {
  32891. var cu = Math.cos(angle);
  32892. var su = Math.sin(angle);
  32893. var quOverP = q / p * angle;
  32894. var cs = Math.cos(quOverP);
  32895. var tx = radius * (2 + cs) * 0.5 * cu;
  32896. var ty = radius * (2 + cs) * su * 0.5;
  32897. var tz = radius * Math.sin(quOverP) * 0.5;
  32898. return new BABYLON.Vector3(tx, ty, tz);
  32899. };
  32900. // Vertices
  32901. var i;
  32902. var j;
  32903. for (i = 0; i <= radialSegments; i++) {
  32904. var modI = i % radialSegments;
  32905. var u = modI / radialSegments * 2 * p * Math.PI;
  32906. var p1 = getPos(u);
  32907. var p2 = getPos(u + 0.01);
  32908. var tang = p2.subtract(p1);
  32909. var n = p2.add(p1);
  32910. var bitan = BABYLON.Vector3.Cross(tang, n);
  32911. n = BABYLON.Vector3.Cross(bitan, tang);
  32912. bitan.normalize();
  32913. n.normalize();
  32914. for (j = 0; j < tubularSegments; j++) {
  32915. var modJ = j % tubularSegments;
  32916. var v = modJ / tubularSegments * 2 * Math.PI;
  32917. var cx = -tube * Math.cos(v);
  32918. var cy = tube * Math.sin(v);
  32919. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32920. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32921. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32922. uvs.push(i / radialSegments);
  32923. uvs.push(j / tubularSegments);
  32924. }
  32925. }
  32926. for (i = 0; i < radialSegments; i++) {
  32927. for (j = 0; j < tubularSegments; j++) {
  32928. var jNext = (j + 1) % tubularSegments;
  32929. var a = i * tubularSegments + j;
  32930. var b = (i + 1) * tubularSegments + j;
  32931. var c = (i + 1) * tubularSegments + jNext;
  32932. var d = i * tubularSegments + jNext;
  32933. indices.push(d);
  32934. indices.push(b);
  32935. indices.push(a);
  32936. indices.push(d);
  32937. indices.push(c);
  32938. indices.push(b);
  32939. }
  32940. }
  32941. // Normals
  32942. VertexData.ComputeNormals(positions, indices, normals);
  32943. // Sides
  32944. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32945. // Result
  32946. var vertexData = new VertexData();
  32947. vertexData.indices = indices;
  32948. vertexData.positions = positions;
  32949. vertexData.normals = normals;
  32950. vertexData.uvs = uvs;
  32951. return vertexData;
  32952. };
  32953. // Tools
  32954. /**
  32955. * @param {any} - positions (number[] or Float32Array)
  32956. * @param {any} - indices (number[] or Uint16Array)
  32957. * @param {any} - normals (number[] or Float32Array)
  32958. */
  32959. VertexData.ComputeNormals = function (positions, indices, normals) {
  32960. var index = 0;
  32961. var p1p2x = 0.0;
  32962. var p1p2y = 0.0;
  32963. var p1p2z = 0.0;
  32964. var p3p2x = 0.0;
  32965. var p3p2y = 0.0;
  32966. var p3p2z = 0.0;
  32967. var faceNormalx = 0.0;
  32968. var faceNormaly = 0.0;
  32969. var faceNormalz = 0.0;
  32970. var length = 0.0;
  32971. var i1 = 0;
  32972. var i2 = 0;
  32973. var i3 = 0;
  32974. for (index = 0; index < positions.length; index++) {
  32975. normals[index] = 0.0;
  32976. }
  32977. // indice triplet = 1 face
  32978. var nbFaces = indices.length / 3;
  32979. for (index = 0; index < nbFaces; index++) {
  32980. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  32981. i2 = indices[index * 3 + 1];
  32982. i3 = indices[index * 3 + 2];
  32983. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  32984. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  32985. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  32986. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  32987. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  32988. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  32989. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  32990. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  32991. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  32992. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32993. length = (length === 0) ? 1.0 : length;
  32994. faceNormalx /= length; // normalize this normal
  32995. faceNormaly /= length;
  32996. faceNormalz /= length;
  32997. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  32998. normals[i1 * 3 + 1] += faceNormaly;
  32999. normals[i1 * 3 + 2] += faceNormalz;
  33000. normals[i2 * 3] += faceNormalx;
  33001. normals[i2 * 3 + 1] += faceNormaly;
  33002. normals[i2 * 3 + 2] += faceNormalz;
  33003. normals[i3 * 3] += faceNormalx;
  33004. normals[i3 * 3 + 1] += faceNormaly;
  33005. normals[i3 * 3 + 2] += faceNormalz;
  33006. }
  33007. // last normalization of each normal
  33008. for (index = 0; index < normals.length / 3; index++) {
  33009. faceNormalx = normals[index * 3];
  33010. faceNormaly = normals[index * 3 + 1];
  33011. faceNormalz = normals[index * 3 + 2];
  33012. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33013. length = (length === 0) ? 1.0 : length;
  33014. faceNormalx /= length;
  33015. faceNormaly /= length;
  33016. faceNormalz /= length;
  33017. normals[index * 3] = faceNormalx;
  33018. normals[index * 3 + 1] = faceNormaly;
  33019. normals[index * 3 + 2] = faceNormalz;
  33020. }
  33021. };
  33022. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  33023. var li = indices.length;
  33024. var ln = normals.length;
  33025. var i;
  33026. var n;
  33027. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33028. switch (sideOrientation) {
  33029. case BABYLON.Mesh.FRONTSIDE:
  33030. // nothing changed
  33031. break;
  33032. case BABYLON.Mesh.BACKSIDE:
  33033. var tmp;
  33034. // indices
  33035. for (i = 0; i < li; i += 3) {
  33036. tmp = indices[i];
  33037. indices[i] = indices[i + 2];
  33038. indices[i + 2] = tmp;
  33039. }
  33040. // normals
  33041. for (n = 0; n < ln; n++) {
  33042. normals[n] = -normals[n];
  33043. }
  33044. break;
  33045. case BABYLON.Mesh.DOUBLESIDE:
  33046. // positions
  33047. var lp = positions.length;
  33048. var l = lp / 3;
  33049. for (var p = 0; p < lp; p++) {
  33050. positions[lp + p] = positions[p];
  33051. }
  33052. // indices
  33053. for (i = 0; i < li; i += 3) {
  33054. indices[i + li] = indices[i + 2] + l;
  33055. indices[i + 1 + li] = indices[i + 1] + l;
  33056. indices[i + 2 + li] = indices[i] + l;
  33057. }
  33058. // normals
  33059. for (n = 0; n < ln; n++) {
  33060. normals[ln + n] = -normals[n];
  33061. }
  33062. // uvs
  33063. var lu = uvs.length;
  33064. for (var u = 0; u < lu; u++) {
  33065. uvs[u + lu] = uvs[u];
  33066. }
  33067. break;
  33068. }
  33069. };
  33070. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33071. var vertexData = new VertexData();
  33072. // positions
  33073. var positions = parsedVertexData.positions;
  33074. if (positions) {
  33075. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33076. }
  33077. // normals
  33078. var normals = parsedVertexData.normals;
  33079. if (normals) {
  33080. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33081. }
  33082. // uvs
  33083. var uvs = parsedVertexData.uvs;
  33084. if (uvs) {
  33085. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33086. }
  33087. // uv2s
  33088. var uv2s = parsedVertexData.uv2s;
  33089. if (uv2s) {
  33090. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33091. }
  33092. // uv3s
  33093. var uv3s = parsedVertexData.uv3s;
  33094. if (uv3s) {
  33095. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33096. }
  33097. // uv4s
  33098. var uv4s = parsedVertexData.uv4s;
  33099. if (uv4s) {
  33100. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33101. }
  33102. // uv5s
  33103. var uv5s = parsedVertexData.uv5s;
  33104. if (uv5s) {
  33105. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33106. }
  33107. // uv6s
  33108. var uv6s = parsedVertexData.uv6s;
  33109. if (uv6s) {
  33110. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33111. }
  33112. // colors
  33113. var colors = parsedVertexData.colors;
  33114. if (colors) {
  33115. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33116. }
  33117. // matricesIndices
  33118. var matricesIndices = parsedVertexData.matricesIndices;
  33119. if (matricesIndices) {
  33120. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33121. }
  33122. // matricesWeights
  33123. var matricesWeights = parsedVertexData.matricesWeights;
  33124. if (matricesWeights) {
  33125. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33126. }
  33127. // indices
  33128. var indices = parsedVertexData.indices;
  33129. if (indices) {
  33130. vertexData.indices = indices;
  33131. }
  33132. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33133. };
  33134. return VertexData;
  33135. }());
  33136. BABYLON.VertexData = VertexData;
  33137. })(BABYLON || (BABYLON = {}));
  33138. var BABYLON;
  33139. (function (BABYLON) {
  33140. var Tags = (function () {
  33141. function Tags() {
  33142. }
  33143. Tags.EnableFor = function (obj) {
  33144. obj._tags = obj._tags || {};
  33145. obj.hasTags = function () {
  33146. return Tags.HasTags(obj);
  33147. };
  33148. obj.addTags = function (tagsString) {
  33149. return Tags.AddTagsTo(obj, tagsString);
  33150. };
  33151. obj.removeTags = function (tagsString) {
  33152. return Tags.RemoveTagsFrom(obj, tagsString);
  33153. };
  33154. obj.matchesTagsQuery = function (tagsQuery) {
  33155. return Tags.MatchesQuery(obj, tagsQuery);
  33156. };
  33157. };
  33158. Tags.DisableFor = function (obj) {
  33159. delete obj._tags;
  33160. delete obj.hasTags;
  33161. delete obj.addTags;
  33162. delete obj.removeTags;
  33163. delete obj.matchesTagsQuery;
  33164. };
  33165. Tags.HasTags = function (obj) {
  33166. if (!obj._tags) {
  33167. return false;
  33168. }
  33169. return !BABYLON.Tools.IsEmpty(obj._tags);
  33170. };
  33171. Tags.GetTags = function (obj, asString) {
  33172. if (asString === void 0) { asString = true; }
  33173. if (!obj._tags) {
  33174. return null;
  33175. }
  33176. if (asString) {
  33177. var tagsArray = [];
  33178. for (var tag in obj._tags) {
  33179. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  33180. tagsArray.push(tag);
  33181. }
  33182. }
  33183. return tagsArray.join(" ");
  33184. }
  33185. else {
  33186. return obj._tags;
  33187. }
  33188. };
  33189. // the tags 'true' and 'false' are reserved and cannot be used as tags
  33190. // a tag cannot start with '||', '&&', and '!'
  33191. // it cannot contain whitespaces
  33192. Tags.AddTagsTo = function (obj, tagsString) {
  33193. if (!tagsString) {
  33194. return;
  33195. }
  33196. if (typeof tagsString !== "string") {
  33197. return;
  33198. }
  33199. var tags = tagsString.split(" ");
  33200. tags.forEach(function (tag, index, array) {
  33201. Tags._AddTagTo(obj, tag);
  33202. });
  33203. };
  33204. Tags._AddTagTo = function (obj, tag) {
  33205. tag = tag.trim();
  33206. if (tag === "" || tag === "true" || tag === "false") {
  33207. return;
  33208. }
  33209. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  33210. return;
  33211. }
  33212. Tags.EnableFor(obj);
  33213. obj._tags[tag] = true;
  33214. };
  33215. Tags.RemoveTagsFrom = function (obj, tagsString) {
  33216. if (!Tags.HasTags(obj)) {
  33217. return;
  33218. }
  33219. var tags = tagsString.split(" ");
  33220. for (var t in tags) {
  33221. Tags._RemoveTagFrom(obj, tags[t]);
  33222. }
  33223. };
  33224. Tags._RemoveTagFrom = function (obj, tag) {
  33225. delete obj._tags[tag];
  33226. };
  33227. Tags.MatchesQuery = function (obj, tagsQuery) {
  33228. if (tagsQuery === undefined) {
  33229. return true;
  33230. }
  33231. if (tagsQuery === "") {
  33232. return Tags.HasTags(obj);
  33233. }
  33234. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  33235. };
  33236. return Tags;
  33237. }());
  33238. BABYLON.Tags = Tags;
  33239. })(BABYLON || (BABYLON = {}));
  33240. var BABYLON;
  33241. (function (BABYLON) {
  33242. var Internals;
  33243. (function (Internals) {
  33244. var AndOrNotEvaluator = (function () {
  33245. function AndOrNotEvaluator() {
  33246. }
  33247. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  33248. if (!query.match(/\([^\(\)]*\)/g)) {
  33249. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  33250. }
  33251. else {
  33252. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  33253. // remove parenthesis
  33254. r = r.slice(1, r.length - 1);
  33255. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  33256. });
  33257. }
  33258. if (query === "true") {
  33259. return true;
  33260. }
  33261. if (query === "false") {
  33262. return false;
  33263. }
  33264. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  33265. };
  33266. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  33267. evaluateCallback = evaluateCallback || (function (r) {
  33268. return r === "true" ? true : false;
  33269. });
  33270. var result;
  33271. var or = parenthesisContent.split("||");
  33272. for (var i in or) {
  33273. if (or.hasOwnProperty(i)) {
  33274. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  33275. var and = ori.split("&&");
  33276. if (and.length > 1) {
  33277. for (var j = 0; j < and.length; ++j) {
  33278. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  33279. if (andj !== "true" && andj !== "false") {
  33280. if (andj[0] === "!") {
  33281. result = !evaluateCallback(andj.substring(1));
  33282. }
  33283. else {
  33284. result = evaluateCallback(andj);
  33285. }
  33286. }
  33287. else {
  33288. result = andj === "true" ? true : false;
  33289. }
  33290. if (!result) {
  33291. ori = "false";
  33292. break;
  33293. }
  33294. }
  33295. }
  33296. if (result || ori === "true") {
  33297. result = true;
  33298. break;
  33299. }
  33300. // result equals false (or undefined)
  33301. if (ori !== "true" && ori !== "false") {
  33302. if (ori[0] === "!") {
  33303. result = !evaluateCallback(ori.substring(1));
  33304. }
  33305. else {
  33306. result = evaluateCallback(ori);
  33307. }
  33308. }
  33309. else {
  33310. result = ori === "true" ? true : false;
  33311. }
  33312. }
  33313. }
  33314. // the whole parenthesis scope is replaced by 'true' or 'false'
  33315. return result ? "true" : "false";
  33316. };
  33317. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  33318. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  33319. // remove whitespaces
  33320. r = r.replace(/[\s]/g, function () { return ""; });
  33321. return r.length % 2 ? "!" : "";
  33322. });
  33323. booleanString = booleanString.trim();
  33324. if (booleanString === "!true") {
  33325. booleanString = "false";
  33326. }
  33327. else if (booleanString === "!false") {
  33328. booleanString = "true";
  33329. }
  33330. return booleanString;
  33331. };
  33332. return AndOrNotEvaluator;
  33333. }());
  33334. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  33335. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33336. })(BABYLON || (BABYLON = {}));
  33337. var BABYLON;
  33338. (function (BABYLON) {
  33339. var PostProcessRenderPass = (function () {
  33340. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  33341. this._enabled = true;
  33342. this._refCount = 0;
  33343. this._name = name;
  33344. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  33345. this.setRenderList(renderList);
  33346. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  33347. this._renderTexture.onAfterRenderObservable.add(afterRender);
  33348. this._scene = scene;
  33349. this._renderList = renderList;
  33350. }
  33351. // private
  33352. PostProcessRenderPass.prototype._incRefCount = function () {
  33353. if (this._refCount === 0) {
  33354. this._scene.customRenderTargets.push(this._renderTexture);
  33355. }
  33356. return ++this._refCount;
  33357. };
  33358. PostProcessRenderPass.prototype._decRefCount = function () {
  33359. this._refCount--;
  33360. if (this._refCount <= 0) {
  33361. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  33362. }
  33363. return this._refCount;
  33364. };
  33365. PostProcessRenderPass.prototype._update = function () {
  33366. this.setRenderList(this._renderList);
  33367. };
  33368. // public
  33369. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  33370. this._renderTexture.renderList = renderList;
  33371. };
  33372. PostProcessRenderPass.prototype.getRenderTexture = function () {
  33373. return this._renderTexture;
  33374. };
  33375. return PostProcessRenderPass;
  33376. }());
  33377. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  33378. })(BABYLON || (BABYLON = {}));
  33379. var BABYLON;
  33380. (function (BABYLON) {
  33381. var PostProcessRenderEffect = (function () {
  33382. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  33383. this._engine = engine;
  33384. this._name = name;
  33385. this._singleInstance = singleInstance || true;
  33386. this._getPostProcess = getPostProcess;
  33387. this._cameras = [];
  33388. this._indicesForCamera = [];
  33389. this._postProcesses = {};
  33390. this._renderPasses = {};
  33391. this._renderEffectAsPasses = {};
  33392. }
  33393. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  33394. get: function () {
  33395. for (var index in this._postProcesses) {
  33396. if (!this._postProcesses[index].isSupported) {
  33397. return false;
  33398. }
  33399. }
  33400. return true;
  33401. },
  33402. enumerable: true,
  33403. configurable: true
  33404. });
  33405. PostProcessRenderEffect.prototype._update = function () {
  33406. for (var renderPassName in this._renderPasses) {
  33407. this._renderPasses[renderPassName]._update();
  33408. }
  33409. };
  33410. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  33411. this._renderPasses[renderPass._name] = renderPass;
  33412. this._linkParameters();
  33413. };
  33414. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  33415. delete this._renderPasses[renderPass._name];
  33416. this._linkParameters();
  33417. };
  33418. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  33419. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  33420. this._linkParameters();
  33421. };
  33422. PostProcessRenderEffect.prototype.getPass = function (passName) {
  33423. for (var renderPassName in this._renderPasses) {
  33424. if (renderPassName === passName) {
  33425. return this._renderPasses[passName];
  33426. }
  33427. }
  33428. };
  33429. PostProcessRenderEffect.prototype.emptyPasses = function () {
  33430. this._renderPasses = {};
  33431. this._linkParameters();
  33432. };
  33433. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  33434. var cameraKey;
  33435. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33436. for (var i = 0; i < _cam.length; i++) {
  33437. var camera = _cam[i];
  33438. var cameraName = camera.name;
  33439. if (this._singleInstance) {
  33440. cameraKey = 0;
  33441. }
  33442. else {
  33443. cameraKey = cameraName;
  33444. }
  33445. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  33446. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  33447. if (!this._indicesForCamera[cameraName]) {
  33448. this._indicesForCamera[cameraName] = [];
  33449. }
  33450. this._indicesForCamera[cameraName].push(index);
  33451. if (this._cameras.indexOf(camera) === -1) {
  33452. this._cameras[cameraName] = camera;
  33453. }
  33454. for (var passName in this._renderPasses) {
  33455. this._renderPasses[passName]._incRefCount();
  33456. }
  33457. }
  33458. this._linkParameters();
  33459. };
  33460. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  33461. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33462. for (var i = 0; i < _cam.length; i++) {
  33463. var camera = _cam[i];
  33464. var cameraName = camera.name;
  33465. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  33466. var index = this._cameras.indexOf(cameraName);
  33467. this._indicesForCamera.splice(index, 1);
  33468. this._cameras.splice(index, 1);
  33469. for (var passName in this._renderPasses) {
  33470. this._renderPasses[passName]._decRefCount();
  33471. }
  33472. }
  33473. };
  33474. PostProcessRenderEffect.prototype._enable = function (cameras) {
  33475. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33476. for (var i = 0; i < _cam.length; i++) {
  33477. var camera = _cam[i];
  33478. var cameraName = camera.name;
  33479. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  33480. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  33481. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  33482. }
  33483. }
  33484. for (var passName in this._renderPasses) {
  33485. this._renderPasses[passName]._incRefCount();
  33486. }
  33487. }
  33488. };
  33489. PostProcessRenderEffect.prototype._disable = function (cameras) {
  33490. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33491. for (var i = 0; i < _cam.length; i++) {
  33492. var camera = _cam[i];
  33493. var cameraName = camera.Name;
  33494. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  33495. for (var passName in this._renderPasses) {
  33496. this._renderPasses[passName]._decRefCount();
  33497. }
  33498. }
  33499. };
  33500. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  33501. if (this._singleInstance) {
  33502. return this._postProcesses[0];
  33503. }
  33504. else {
  33505. return this._postProcesses[camera.name];
  33506. }
  33507. };
  33508. PostProcessRenderEffect.prototype._linkParameters = function () {
  33509. var _this = this;
  33510. for (var index in this._postProcesses) {
  33511. if (this.applyParameters) {
  33512. this.applyParameters(this._postProcesses[index]);
  33513. }
  33514. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  33515. _this._linkTextures(effect);
  33516. });
  33517. }
  33518. };
  33519. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  33520. for (var renderPassName in this._renderPasses) {
  33521. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  33522. }
  33523. for (var renderEffectName in this._renderEffectAsPasses) {
  33524. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  33525. }
  33526. };
  33527. return PostProcessRenderEffect;
  33528. }());
  33529. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  33530. })(BABYLON || (BABYLON = {}));
  33531. var BABYLON;
  33532. (function (BABYLON) {
  33533. var PostProcessRenderPipeline = (function () {
  33534. function PostProcessRenderPipeline(engine, name) {
  33535. this._engine = engine;
  33536. this._name = name;
  33537. this._renderEffects = {};
  33538. this._renderEffectsForIsolatedPass = {};
  33539. this._cameras = [];
  33540. }
  33541. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  33542. get: function () {
  33543. for (var renderEffectName in this._renderEffects) {
  33544. if (!this._renderEffects[renderEffectName].isSupported) {
  33545. return false;
  33546. }
  33547. }
  33548. return true;
  33549. },
  33550. enumerable: true,
  33551. configurable: true
  33552. });
  33553. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  33554. this._renderEffects[renderEffect._name] = renderEffect;
  33555. };
  33556. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  33557. var renderEffects = this._renderEffects[renderEffectName];
  33558. if (!renderEffects) {
  33559. return;
  33560. }
  33561. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  33562. };
  33563. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  33564. var renderEffects = this._renderEffects[renderEffectName];
  33565. if (!renderEffects) {
  33566. return;
  33567. }
  33568. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  33569. };
  33570. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  33571. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33572. var indicesToDelete = [];
  33573. var i;
  33574. for (i = 0; i < _cam.length; i++) {
  33575. var camera = _cam[i];
  33576. var cameraName = camera.name;
  33577. if (this._cameras.indexOf(camera) === -1) {
  33578. this._cameras[cameraName] = camera;
  33579. }
  33580. else if (unique) {
  33581. indicesToDelete.push(i);
  33582. }
  33583. }
  33584. for (i = 0; i < indicesToDelete.length; i++) {
  33585. cameras.splice(indicesToDelete[i], 1);
  33586. }
  33587. for (var renderEffectName in this._renderEffects) {
  33588. this._renderEffects[renderEffectName]._attachCameras(_cam);
  33589. }
  33590. };
  33591. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  33592. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33593. for (var renderEffectName in this._renderEffects) {
  33594. this._renderEffects[renderEffectName]._detachCameras(_cam);
  33595. }
  33596. for (var i = 0; i < _cam.length; i++) {
  33597. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  33598. }
  33599. };
  33600. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  33601. var _this = this;
  33602. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33603. var pass = null;
  33604. var renderEffectName;
  33605. for (renderEffectName in this._renderEffects) {
  33606. pass = this._renderEffects[renderEffectName].getPass(passName);
  33607. if (pass != null) {
  33608. break;
  33609. }
  33610. }
  33611. if (pass === null) {
  33612. return;
  33613. }
  33614. for (renderEffectName in this._renderEffects) {
  33615. this._renderEffects[renderEffectName]._disable(_cam);
  33616. }
  33617. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  33618. for (var i = 0; i < _cam.length; i++) {
  33619. var camera = _cam[i];
  33620. var cameraName = camera.name;
  33621. 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); });
  33622. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  33623. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  33624. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  33625. }
  33626. };
  33627. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  33628. var _this = this;
  33629. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33630. for (var i = 0; i < _cam.length; i++) {
  33631. var camera = _cam[i];
  33632. var cameraName = camera.name;
  33633. 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); });
  33634. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  33635. }
  33636. for (var renderEffectName in this._renderEffects) {
  33637. this._renderEffects[renderEffectName]._enable(_cam);
  33638. }
  33639. };
  33640. PostProcessRenderPipeline.prototype._update = function () {
  33641. for (var renderEffectName in this._renderEffects) {
  33642. this._renderEffects[renderEffectName]._update();
  33643. }
  33644. for (var i = 0; i < this._cameras.length; i++) {
  33645. var cameraName = this._cameras[i].name;
  33646. if (this._renderEffectsForIsolatedPass[cameraName]) {
  33647. this._renderEffectsForIsolatedPass[cameraName]._update();
  33648. }
  33649. }
  33650. };
  33651. PostProcessRenderPipeline.prototype.dispose = function () {
  33652. // Must be implemented by children
  33653. };
  33654. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  33655. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  33656. return PostProcessRenderPipeline;
  33657. }());
  33658. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  33659. })(BABYLON || (BABYLON = {}));
  33660. var BABYLON;
  33661. (function (BABYLON) {
  33662. var PostProcessRenderPipelineManager = (function () {
  33663. function PostProcessRenderPipelineManager() {
  33664. this._renderPipelines = {};
  33665. }
  33666. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  33667. this._renderPipelines[renderPipeline._name] = renderPipeline;
  33668. };
  33669. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  33670. var renderPipeline = this._renderPipelines[renderPipelineName];
  33671. if (!renderPipeline) {
  33672. return;
  33673. }
  33674. renderPipeline._attachCameras(cameras, unique);
  33675. };
  33676. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  33677. var renderPipeline = this._renderPipelines[renderPipelineName];
  33678. if (!renderPipeline) {
  33679. return;
  33680. }
  33681. renderPipeline._detachCameras(cameras);
  33682. };
  33683. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33684. var renderPipeline = this._renderPipelines[renderPipelineName];
  33685. if (!renderPipeline) {
  33686. return;
  33687. }
  33688. renderPipeline._enableEffect(renderEffectName, cameras);
  33689. };
  33690. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33691. var renderPipeline = this._renderPipelines[renderPipelineName];
  33692. if (!renderPipeline) {
  33693. return;
  33694. }
  33695. renderPipeline._disableEffect(renderEffectName, cameras);
  33696. };
  33697. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  33698. var renderPipeline = this._renderPipelines[renderPipelineName];
  33699. if (!renderPipeline) {
  33700. return;
  33701. }
  33702. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  33703. };
  33704. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  33705. var renderPipeline = this._renderPipelines[renderPipelineName];
  33706. if (!renderPipeline) {
  33707. return;
  33708. }
  33709. renderPipeline._disableDisplayOnlyPass(cameras);
  33710. };
  33711. PostProcessRenderPipelineManager.prototype.update = function () {
  33712. for (var renderPipelineName in this._renderPipelines) {
  33713. var pipeline = this._renderPipelines[renderPipelineName];
  33714. if (!pipeline.isSupported) {
  33715. pipeline.dispose();
  33716. delete this._renderPipelines[renderPipelineName];
  33717. }
  33718. else {
  33719. pipeline._update();
  33720. }
  33721. }
  33722. };
  33723. return PostProcessRenderPipelineManager;
  33724. }());
  33725. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  33726. })(BABYLON || (BABYLON = {}));
  33727. var BABYLON;
  33728. (function (BABYLON) {
  33729. var BoundingBoxRenderer = (function () {
  33730. function BoundingBoxRenderer(scene) {
  33731. this.frontColor = new BABYLON.Color3(1, 1, 1);
  33732. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  33733. this.showBackLines = true;
  33734. this.renderList = new BABYLON.SmartArray(32);
  33735. this._vertexBuffers = {};
  33736. this._scene = scene;
  33737. }
  33738. BoundingBoxRenderer.prototype._prepareRessources = function () {
  33739. if (this._colorShader) {
  33740. return;
  33741. }
  33742. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  33743. attributes: [BABYLON.VertexBuffer.PositionKind],
  33744. uniforms: ["worldViewProjection", "color"]
  33745. });
  33746. var engine = this._scene.getEngine();
  33747. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  33748. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  33749. 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]);
  33750. };
  33751. BoundingBoxRenderer.prototype.reset = function () {
  33752. this.renderList.reset();
  33753. };
  33754. BoundingBoxRenderer.prototype.render = function () {
  33755. if (this.renderList.length === 0) {
  33756. return;
  33757. }
  33758. this._prepareRessources();
  33759. if (!this._colorShader.isReady()) {
  33760. return;
  33761. }
  33762. var engine = this._scene.getEngine();
  33763. engine.setDepthWrite(false);
  33764. this._colorShader._preBind();
  33765. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  33766. var boundingBox = this.renderList.data[boundingBoxIndex];
  33767. var min = boundingBox.minimum;
  33768. var max = boundingBox.maximum;
  33769. var diff = max.subtract(min);
  33770. var median = min.add(diff.scale(0.5));
  33771. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  33772. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  33773. .multiply(boundingBox.getWorldMatrix());
  33774. // VBOs
  33775. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  33776. if (this.showBackLines) {
  33777. // Back
  33778. engine.setDepthFunctionToGreaterOrEqual();
  33779. this._scene.resetCachedMaterial();
  33780. this._colorShader.setColor4("color", this.backColor.toColor4());
  33781. this._colorShader.bind(worldMatrix);
  33782. // Draw order
  33783. engine.draw(false, 0, 24);
  33784. }
  33785. // Front
  33786. engine.setDepthFunctionToLess();
  33787. this._scene.resetCachedMaterial();
  33788. this._colorShader.setColor4("color", this.frontColor.toColor4());
  33789. this._colorShader.bind(worldMatrix);
  33790. // Draw order
  33791. engine.draw(false, 0, 24);
  33792. }
  33793. this._colorShader.unbind();
  33794. engine.setDepthFunctionToLessOrEqual();
  33795. engine.setDepthWrite(true);
  33796. };
  33797. BoundingBoxRenderer.prototype.dispose = function () {
  33798. if (!this._colorShader) {
  33799. return;
  33800. }
  33801. this._colorShader.dispose();
  33802. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33803. if (buffer) {
  33804. buffer.dispose();
  33805. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33806. }
  33807. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33808. };
  33809. return BoundingBoxRenderer;
  33810. }());
  33811. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  33812. })(BABYLON || (BABYLON = {}));
  33813. var BABYLON;
  33814. (function (BABYLON) {
  33815. var Condition = (function () {
  33816. function Condition(actionManager) {
  33817. this._actionManager = actionManager;
  33818. }
  33819. Condition.prototype.isValid = function () {
  33820. return true;
  33821. };
  33822. Condition.prototype._getProperty = function (propertyPath) {
  33823. return this._actionManager._getProperty(propertyPath);
  33824. };
  33825. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33826. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33827. };
  33828. Condition.prototype.serialize = function () {
  33829. };
  33830. Condition.prototype._serialize = function (serializedCondition) {
  33831. return {
  33832. type: 2,
  33833. children: [],
  33834. name: serializedCondition.name,
  33835. properties: serializedCondition.properties
  33836. };
  33837. };
  33838. return Condition;
  33839. }());
  33840. BABYLON.Condition = Condition;
  33841. var ValueCondition = (function (_super) {
  33842. __extends(ValueCondition, _super);
  33843. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33844. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33845. _super.call(this, actionManager);
  33846. this.propertyPath = propertyPath;
  33847. this.value = value;
  33848. this.operator = operator;
  33849. this._target = target;
  33850. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  33851. this._property = this._getProperty(this.propertyPath);
  33852. }
  33853. Object.defineProperty(ValueCondition, "IsEqual", {
  33854. get: function () {
  33855. return ValueCondition._IsEqual;
  33856. },
  33857. enumerable: true,
  33858. configurable: true
  33859. });
  33860. Object.defineProperty(ValueCondition, "IsDifferent", {
  33861. get: function () {
  33862. return ValueCondition._IsDifferent;
  33863. },
  33864. enumerable: true,
  33865. configurable: true
  33866. });
  33867. Object.defineProperty(ValueCondition, "IsGreater", {
  33868. get: function () {
  33869. return ValueCondition._IsGreater;
  33870. },
  33871. enumerable: true,
  33872. configurable: true
  33873. });
  33874. Object.defineProperty(ValueCondition, "IsLesser", {
  33875. get: function () {
  33876. return ValueCondition._IsLesser;
  33877. },
  33878. enumerable: true,
  33879. configurable: true
  33880. });
  33881. // Methods
  33882. ValueCondition.prototype.isValid = function () {
  33883. switch (this.operator) {
  33884. case ValueCondition.IsGreater:
  33885. return this._effectiveTarget[this._property] > this.value;
  33886. case ValueCondition.IsLesser:
  33887. return this._effectiveTarget[this._property] < this.value;
  33888. case ValueCondition.IsEqual:
  33889. case ValueCondition.IsDifferent:
  33890. var check;
  33891. if (this.value.equals) {
  33892. check = this.value.equals(this._effectiveTarget[this._property]);
  33893. }
  33894. else {
  33895. check = this.value === this._effectiveTarget[this._property];
  33896. }
  33897. return this.operator === ValueCondition.IsEqual ? check : !check;
  33898. }
  33899. return false;
  33900. };
  33901. ValueCondition.prototype.serialize = function () {
  33902. return this._serialize({
  33903. name: "ValueCondition",
  33904. properties: [
  33905. BABYLON.Action._GetTargetProperty(this._target),
  33906. { name: "propertyPath", value: this.propertyPath },
  33907. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33908. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33909. ]
  33910. });
  33911. };
  33912. ValueCondition.GetOperatorName = function (operator) {
  33913. switch (operator) {
  33914. case ValueCondition._IsEqual: return "IsEqual";
  33915. case ValueCondition._IsDifferent: return "IsDifferent";
  33916. case ValueCondition._IsGreater: return "IsGreater";
  33917. case ValueCondition._IsLesser: return "IsLesser";
  33918. default: return "";
  33919. }
  33920. };
  33921. // Statics
  33922. ValueCondition._IsEqual = 0;
  33923. ValueCondition._IsDifferent = 1;
  33924. ValueCondition._IsGreater = 2;
  33925. ValueCondition._IsLesser = 3;
  33926. return ValueCondition;
  33927. }(Condition));
  33928. BABYLON.ValueCondition = ValueCondition;
  33929. var PredicateCondition = (function (_super) {
  33930. __extends(PredicateCondition, _super);
  33931. function PredicateCondition(actionManager, predicate) {
  33932. _super.call(this, actionManager);
  33933. this.predicate = predicate;
  33934. }
  33935. PredicateCondition.prototype.isValid = function () {
  33936. return this.predicate();
  33937. };
  33938. return PredicateCondition;
  33939. }(Condition));
  33940. BABYLON.PredicateCondition = PredicateCondition;
  33941. var StateCondition = (function (_super) {
  33942. __extends(StateCondition, _super);
  33943. function StateCondition(actionManager, target, value) {
  33944. _super.call(this, actionManager);
  33945. this.value = value;
  33946. this._target = target;
  33947. }
  33948. // Methods
  33949. StateCondition.prototype.isValid = function () {
  33950. return this._target.state === this.value;
  33951. };
  33952. StateCondition.prototype.serialize = function () {
  33953. return this._serialize({
  33954. name: "StateCondition",
  33955. properties: [
  33956. BABYLON.Action._GetTargetProperty(this._target),
  33957. { name: "value", value: this.value }
  33958. ]
  33959. });
  33960. };
  33961. return StateCondition;
  33962. }(Condition));
  33963. BABYLON.StateCondition = StateCondition;
  33964. })(BABYLON || (BABYLON = {}));
  33965. var BABYLON;
  33966. (function (BABYLON) {
  33967. var Action = (function () {
  33968. function Action(triggerOptions, condition) {
  33969. this.triggerOptions = triggerOptions;
  33970. if (triggerOptions.parameter) {
  33971. this.trigger = triggerOptions.trigger;
  33972. this._triggerParameter = triggerOptions.parameter;
  33973. }
  33974. else {
  33975. this.trigger = triggerOptions;
  33976. }
  33977. this._nextActiveAction = this;
  33978. this._condition = condition;
  33979. }
  33980. // Methods
  33981. Action.prototype._prepare = function () {
  33982. };
  33983. Action.prototype.getTriggerParameter = function () {
  33984. return this._triggerParameter;
  33985. };
  33986. Action.prototype._executeCurrent = function (evt) {
  33987. if (this._nextActiveAction._condition) {
  33988. var condition = this._nextActiveAction._condition;
  33989. var currentRenderId = this._actionManager.getScene().getRenderId();
  33990. // We cache the current evaluation for the current frame
  33991. if (condition._evaluationId === currentRenderId) {
  33992. if (!condition._currentResult) {
  33993. return;
  33994. }
  33995. }
  33996. else {
  33997. condition._evaluationId = currentRenderId;
  33998. if (!condition.isValid()) {
  33999. condition._currentResult = false;
  34000. return;
  34001. }
  34002. condition._currentResult = true;
  34003. }
  34004. }
  34005. this._nextActiveAction.execute(evt);
  34006. this.skipToNextActiveAction();
  34007. };
  34008. Action.prototype.execute = function (evt) {
  34009. };
  34010. Action.prototype.skipToNextActiveAction = function () {
  34011. if (this._nextActiveAction._child) {
  34012. if (!this._nextActiveAction._child._actionManager) {
  34013. this._nextActiveAction._child._actionManager = this._actionManager;
  34014. }
  34015. this._nextActiveAction = this._nextActiveAction._child;
  34016. }
  34017. else {
  34018. this._nextActiveAction = this;
  34019. }
  34020. };
  34021. Action.prototype.then = function (action) {
  34022. this._child = action;
  34023. action._actionManager = this._actionManager;
  34024. action._prepare();
  34025. return action;
  34026. };
  34027. Action.prototype._getProperty = function (propertyPath) {
  34028. return this._actionManager._getProperty(propertyPath);
  34029. };
  34030. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  34031. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34032. };
  34033. Action.prototype.serialize = function (parent) {
  34034. };
  34035. // Called by BABYLON.Action objects in serialize(...). Internal use
  34036. Action.prototype._serialize = function (serializedAction, parent) {
  34037. var serializationObject = {
  34038. type: 1,
  34039. children: [],
  34040. name: serializedAction.name,
  34041. properties: serializedAction.properties || []
  34042. };
  34043. // Serialize child
  34044. if (this._child) {
  34045. this._child.serialize(serializationObject);
  34046. }
  34047. // Check if "this" has a condition
  34048. if (this._condition) {
  34049. var serializedCondition = this._condition.serialize();
  34050. serializedCondition.children.push(serializationObject);
  34051. if (parent) {
  34052. parent.children.push(serializedCondition);
  34053. }
  34054. return serializedCondition;
  34055. }
  34056. if (parent) {
  34057. parent.children.push(serializationObject);
  34058. }
  34059. return serializationObject;
  34060. };
  34061. Action._SerializeValueAsString = function (value) {
  34062. if (typeof value === "number") {
  34063. return value.toString();
  34064. }
  34065. if (typeof value === "boolean") {
  34066. return value ? "true" : "false";
  34067. }
  34068. if (value instanceof BABYLON.Vector2) {
  34069. return value.x + ", " + value.y;
  34070. }
  34071. if (value instanceof BABYLON.Vector3) {
  34072. return value.x + ", " + value.y + ", " + value.z;
  34073. }
  34074. if (value instanceof BABYLON.Color3) {
  34075. return value.r + ", " + value.g + ", " + value.b;
  34076. }
  34077. if (value instanceof BABYLON.Color4) {
  34078. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  34079. }
  34080. return value; // string
  34081. };
  34082. Action._GetTargetProperty = function (target) {
  34083. return {
  34084. name: "target",
  34085. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  34086. : target instanceof BABYLON.Light ? "LightProperties"
  34087. : target instanceof BABYLON.Camera ? "CameraProperties"
  34088. : "SceneProperties",
  34089. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  34090. };
  34091. };
  34092. return Action;
  34093. }());
  34094. BABYLON.Action = Action;
  34095. })(BABYLON || (BABYLON = {}));
  34096. var BABYLON;
  34097. (function (BABYLON) {
  34098. /**
  34099. * ActionEvent is the event beint sent when an action is triggered.
  34100. */
  34101. var ActionEvent = (function () {
  34102. /**
  34103. * @constructor
  34104. * @param source The mesh or sprite that triggered the action.
  34105. * @param pointerX The X mouse cursor position at the time of the event
  34106. * @param pointerY The Y mouse cursor position at the time of the event
  34107. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  34108. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  34109. */
  34110. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  34111. this.source = source;
  34112. this.pointerX = pointerX;
  34113. this.pointerY = pointerY;
  34114. this.meshUnderPointer = meshUnderPointer;
  34115. this.sourceEvent = sourceEvent;
  34116. this.additionalData = additionalData;
  34117. }
  34118. /**
  34119. * Helper function to auto-create an ActionEvent from a source mesh.
  34120. * @param source The source mesh that triggered the event
  34121. * @param evt {Event} The original (browser) event
  34122. */
  34123. ActionEvent.CreateNew = function (source, evt, additionalData) {
  34124. var scene = source.getScene();
  34125. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  34126. };
  34127. /**
  34128. * Helper function to auto-create an ActionEvent from a source mesh.
  34129. * @param source The source sprite that triggered the event
  34130. * @param scene Scene associated with the sprite
  34131. * @param evt {Event} The original (browser) event
  34132. */
  34133. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  34134. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  34135. };
  34136. /**
  34137. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  34138. * @param scene the scene where the event occurred
  34139. * @param evt {Event} The original (browser) event
  34140. */
  34141. ActionEvent.CreateNewFromScene = function (scene, evt) {
  34142. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  34143. };
  34144. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  34145. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  34146. };
  34147. return ActionEvent;
  34148. }());
  34149. BABYLON.ActionEvent = ActionEvent;
  34150. /**
  34151. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  34152. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  34153. */
  34154. var ActionManager = (function () {
  34155. function ActionManager(scene) {
  34156. // Members
  34157. this.actions = new Array();
  34158. this.hoverCursor = '';
  34159. this._scene = scene;
  34160. scene._actionManagers.push(this);
  34161. }
  34162. Object.defineProperty(ActionManager, "NothingTrigger", {
  34163. get: function () {
  34164. return ActionManager._NothingTrigger;
  34165. },
  34166. enumerable: true,
  34167. configurable: true
  34168. });
  34169. Object.defineProperty(ActionManager, "OnPickTrigger", {
  34170. get: function () {
  34171. return ActionManager._OnPickTrigger;
  34172. },
  34173. enumerable: true,
  34174. configurable: true
  34175. });
  34176. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  34177. get: function () {
  34178. return ActionManager._OnLeftPickTrigger;
  34179. },
  34180. enumerable: true,
  34181. configurable: true
  34182. });
  34183. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  34184. get: function () {
  34185. return ActionManager._OnRightPickTrigger;
  34186. },
  34187. enumerable: true,
  34188. configurable: true
  34189. });
  34190. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  34191. get: function () {
  34192. return ActionManager._OnCenterPickTrigger;
  34193. },
  34194. enumerable: true,
  34195. configurable: true
  34196. });
  34197. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  34198. get: function () {
  34199. return ActionManager._OnPickDownTrigger;
  34200. },
  34201. enumerable: true,
  34202. configurable: true
  34203. });
  34204. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  34205. get: function () {
  34206. return ActionManager._OnPickUpTrigger;
  34207. },
  34208. enumerable: true,
  34209. configurable: true
  34210. });
  34211. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  34212. /// This trigger will only be raised if you also declared a OnPickDown
  34213. get: function () {
  34214. return ActionManager._OnPickOutTrigger;
  34215. },
  34216. enumerable: true,
  34217. configurable: true
  34218. });
  34219. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  34220. get: function () {
  34221. return ActionManager._OnLongPressTrigger;
  34222. },
  34223. enumerable: true,
  34224. configurable: true
  34225. });
  34226. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  34227. get: function () {
  34228. return ActionManager._OnPointerOverTrigger;
  34229. },
  34230. enumerable: true,
  34231. configurable: true
  34232. });
  34233. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  34234. get: function () {
  34235. return ActionManager._OnPointerOutTrigger;
  34236. },
  34237. enumerable: true,
  34238. configurable: true
  34239. });
  34240. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  34241. get: function () {
  34242. return ActionManager._OnEveryFrameTrigger;
  34243. },
  34244. enumerable: true,
  34245. configurable: true
  34246. });
  34247. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  34248. get: function () {
  34249. return ActionManager._OnIntersectionEnterTrigger;
  34250. },
  34251. enumerable: true,
  34252. configurable: true
  34253. });
  34254. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  34255. get: function () {
  34256. return ActionManager._OnIntersectionExitTrigger;
  34257. },
  34258. enumerable: true,
  34259. configurable: true
  34260. });
  34261. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  34262. get: function () {
  34263. return ActionManager._OnKeyDownTrigger;
  34264. },
  34265. enumerable: true,
  34266. configurable: true
  34267. });
  34268. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  34269. get: function () {
  34270. return ActionManager._OnKeyUpTrigger;
  34271. },
  34272. enumerable: true,
  34273. configurable: true
  34274. });
  34275. // Methods
  34276. ActionManager.prototype.dispose = function () {
  34277. var index = this._scene._actionManagers.indexOf(this);
  34278. if (index > -1) {
  34279. this._scene._actionManagers.splice(index, 1);
  34280. }
  34281. };
  34282. ActionManager.prototype.getScene = function () {
  34283. return this._scene;
  34284. };
  34285. /**
  34286. * Does this action manager handles actions of any of the given triggers
  34287. * @param {number[]} triggers - the triggers to be tested
  34288. * @return {boolean} whether one (or more) of the triggers is handeled
  34289. */
  34290. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  34291. for (var index = 0; index < this.actions.length; index++) {
  34292. var action = this.actions[index];
  34293. if (triggers.indexOf(action.trigger) > -1) {
  34294. return true;
  34295. }
  34296. }
  34297. return false;
  34298. };
  34299. /**
  34300. * Does this action manager handles actions of a given trigger
  34301. * @param {number} trigger - the trigger to be tested
  34302. * @return {boolean} whether the trigger is handeled
  34303. */
  34304. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  34305. for (var index = 0; index < this.actions.length; index++) {
  34306. var action = this.actions[index];
  34307. if (action.trigger === trigger) {
  34308. return true;
  34309. }
  34310. }
  34311. return false;
  34312. };
  34313. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  34314. /**
  34315. * Does this action manager has pointer triggers
  34316. * @return {boolean} whether or not it has pointer triggers
  34317. */
  34318. get: function () {
  34319. for (var index = 0; index < this.actions.length; index++) {
  34320. var action = this.actions[index];
  34321. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  34322. return true;
  34323. }
  34324. }
  34325. return false;
  34326. },
  34327. enumerable: true,
  34328. configurable: true
  34329. });
  34330. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  34331. /**
  34332. * Does this action manager has pick triggers
  34333. * @return {boolean} whether or not it has pick triggers
  34334. */
  34335. get: function () {
  34336. for (var index = 0; index < this.actions.length; index++) {
  34337. var action = this.actions[index];
  34338. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  34339. return true;
  34340. }
  34341. }
  34342. return false;
  34343. },
  34344. enumerable: true,
  34345. configurable: true
  34346. });
  34347. /**
  34348. * Registers an action to this action manager
  34349. * @param {BABYLON.Action} action - the action to be registered
  34350. * @return {BABYLON.Action} the action amended (prepared) after registration
  34351. */
  34352. ActionManager.prototype.registerAction = function (action) {
  34353. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  34354. if (this.getScene().actionManager !== this) {
  34355. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  34356. return null;
  34357. }
  34358. }
  34359. this.actions.push(action);
  34360. action._actionManager = this;
  34361. action._prepare();
  34362. return action;
  34363. };
  34364. /**
  34365. * Process a specific trigger
  34366. * @param {number} trigger - the trigger to process
  34367. * @param evt {BABYLON.ActionEvent} the event details to be processed
  34368. */
  34369. ActionManager.prototype.processTrigger = function (trigger, evt) {
  34370. for (var index = 0; index < this.actions.length; index++) {
  34371. var action = this.actions[index];
  34372. if (action.trigger === trigger) {
  34373. if (trigger === ActionManager.OnKeyUpTrigger
  34374. || trigger === ActionManager.OnKeyDownTrigger) {
  34375. var parameter = action.getTriggerParameter();
  34376. if (parameter) {
  34377. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  34378. var actualkey = String.fromCharCode(unicode).toLowerCase();
  34379. if (actualkey !== parameter.toLowerCase()) {
  34380. continue;
  34381. }
  34382. }
  34383. }
  34384. action._executeCurrent(evt);
  34385. }
  34386. }
  34387. };
  34388. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  34389. var properties = propertyPath.split(".");
  34390. for (var index = 0; index < properties.length - 1; index++) {
  34391. target = target[properties[index]];
  34392. }
  34393. return target;
  34394. };
  34395. ActionManager.prototype._getProperty = function (propertyPath) {
  34396. var properties = propertyPath.split(".");
  34397. return properties[properties.length - 1];
  34398. };
  34399. ActionManager.prototype.serialize = function (name) {
  34400. var root = {
  34401. children: [],
  34402. name: name,
  34403. type: 3,
  34404. properties: [] // Empty for root but required
  34405. };
  34406. for (var i = 0; i < this.actions.length; i++) {
  34407. var triggerObject = {
  34408. type: 0,
  34409. children: [],
  34410. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  34411. properties: []
  34412. };
  34413. var triggerOptions = this.actions[i].triggerOptions;
  34414. if (triggerOptions && typeof triggerOptions !== "number") {
  34415. if (triggerOptions.parameter instanceof BABYLON.Node) {
  34416. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  34417. }
  34418. else {
  34419. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  34420. }
  34421. }
  34422. // Serialize child action, recursively
  34423. this.actions[i].serialize(triggerObject);
  34424. // Add serialized trigger
  34425. root.children.push(triggerObject);
  34426. }
  34427. return root;
  34428. };
  34429. ActionManager.Parse = function (parsedActions, object, scene) {
  34430. var actionManager = new BABYLON.ActionManager(scene);
  34431. if (object === null)
  34432. scene.actionManager = actionManager;
  34433. else
  34434. object.actionManager = actionManager;
  34435. // instanciate a new object
  34436. var instanciate = function (name, params) {
  34437. var newInstance = Object.create(BABYLON[name].prototype);
  34438. newInstance.constructor.apply(newInstance, params);
  34439. return newInstance;
  34440. };
  34441. var parseParameter = function (name, value, target, propertyPath) {
  34442. if (propertyPath === null) {
  34443. // String, boolean or float
  34444. var floatValue = parseFloat(value);
  34445. if (value === "true" || value === "false")
  34446. return value === "true";
  34447. else
  34448. return isNaN(floatValue) ? value : floatValue;
  34449. }
  34450. var effectiveTarget = propertyPath.split(".");
  34451. var values = value.split(",");
  34452. // Get effective Target
  34453. for (var i = 0; i < effectiveTarget.length; i++) {
  34454. target = target[effectiveTarget[i]];
  34455. }
  34456. // Return appropriate value with its type
  34457. if (typeof (target) === "boolean")
  34458. return values[0] === "true";
  34459. if (typeof (target) === "string")
  34460. return values[0];
  34461. // Parameters with multiple values such as Vector3 etc.
  34462. var split = new Array();
  34463. for (var i = 0; i < values.length; i++)
  34464. split.push(parseFloat(values[i]));
  34465. if (target instanceof BABYLON.Vector3)
  34466. return BABYLON.Vector3.FromArray(split);
  34467. if (target instanceof BABYLON.Vector4)
  34468. return BABYLON.Vector4.FromArray(split);
  34469. if (target instanceof BABYLON.Color3)
  34470. return BABYLON.Color3.FromArray(split);
  34471. if (target instanceof BABYLON.Color4)
  34472. return BABYLON.Color4.FromArray(split);
  34473. return parseFloat(values[0]);
  34474. };
  34475. // traverse graph per trigger
  34476. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  34477. if (combineArray === void 0) { combineArray = null; }
  34478. if (parsedAction.detached)
  34479. return;
  34480. var parameters = new Array();
  34481. var target = null;
  34482. var propertyPath = null;
  34483. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  34484. // Parameters
  34485. if (parsedAction.type === 2)
  34486. parameters.push(actionManager);
  34487. else
  34488. parameters.push(trigger);
  34489. if (combine) {
  34490. var actions = new Array();
  34491. for (var j = 0; j < parsedAction.combine.length; j++) {
  34492. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  34493. }
  34494. parameters.push(actions);
  34495. }
  34496. else {
  34497. for (var i = 0; i < parsedAction.properties.length; i++) {
  34498. var value = parsedAction.properties[i].value;
  34499. var name = parsedAction.properties[i].name;
  34500. var targetType = parsedAction.properties[i].targetType;
  34501. if (name === "target")
  34502. if (targetType !== null && targetType === "SceneProperties")
  34503. value = target = scene;
  34504. else
  34505. value = target = scene.getNodeByName(value);
  34506. else if (name === "parent")
  34507. value = scene.getNodeByName(value);
  34508. else if (name === "sound")
  34509. value = scene.getSoundByName(value);
  34510. else if (name !== "propertyPath") {
  34511. if (parsedAction.type === 2 && name === "operator")
  34512. value = BABYLON.ValueCondition[value];
  34513. else
  34514. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  34515. }
  34516. else {
  34517. propertyPath = value;
  34518. }
  34519. parameters.push(value);
  34520. }
  34521. }
  34522. if (combineArray === null) {
  34523. parameters.push(condition);
  34524. }
  34525. else {
  34526. parameters.push(null);
  34527. }
  34528. // If interpolate value action
  34529. if (parsedAction.name === "InterpolateValueAction") {
  34530. var param = parameters[parameters.length - 2];
  34531. parameters[parameters.length - 1] = param;
  34532. parameters[parameters.length - 2] = condition;
  34533. }
  34534. // Action or condition(s) and not CombineAction
  34535. var newAction = instanciate(parsedAction.name, parameters);
  34536. if (newAction instanceof BABYLON.Condition && condition !== null) {
  34537. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  34538. if (action)
  34539. action.then(nothing);
  34540. else
  34541. actionManager.registerAction(nothing);
  34542. action = nothing;
  34543. }
  34544. if (combineArray === null) {
  34545. if (newAction instanceof BABYLON.Condition) {
  34546. condition = newAction;
  34547. newAction = action;
  34548. }
  34549. else {
  34550. condition = null;
  34551. if (action)
  34552. action.then(newAction);
  34553. else
  34554. actionManager.registerAction(newAction);
  34555. }
  34556. }
  34557. else {
  34558. combineArray.push(newAction);
  34559. }
  34560. for (var i = 0; i < parsedAction.children.length; i++)
  34561. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  34562. };
  34563. // triggers
  34564. for (var i = 0; i < parsedActions.children.length; i++) {
  34565. var triggerParams;
  34566. var trigger = parsedActions.children[i];
  34567. if (trigger.properties.length > 0) {
  34568. var param = trigger.properties[0].value;
  34569. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  34570. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  34571. }
  34572. else
  34573. triggerParams = BABYLON.ActionManager[trigger.name];
  34574. for (var j = 0; j < trigger.children.length; j++) {
  34575. if (!trigger.detached)
  34576. traverse(trigger.children[j], triggerParams, null, null);
  34577. }
  34578. }
  34579. };
  34580. ActionManager.GetTriggerName = function (trigger) {
  34581. switch (trigger) {
  34582. case 0: return "NothingTrigger";
  34583. case 1: return "OnPickTrigger";
  34584. case 2: return "OnLeftPickTrigger";
  34585. case 3: return "OnRightPickTrigger";
  34586. case 4: return "OnCenterPickTrigger";
  34587. case 5: return "OnPickDownTrigger";
  34588. case 6: return "OnPickUpTrigger";
  34589. case 7: return "OnLongPressTrigger";
  34590. case 8: return "OnPointerOverTrigger";
  34591. case 9: return "OnPointerOutTrigger";
  34592. case 10: return "OnEveryFrameTrigger";
  34593. case 11: return "OnIntersectionEnterTrigger";
  34594. case 12: return "OnIntersectionExitTrigger";
  34595. case 13: return "OnKeyDownTrigger";
  34596. case 14: return "OnKeyUpTrigger";
  34597. case 15: return "OnPickOutTrigger";
  34598. default: return "";
  34599. }
  34600. };
  34601. // Statics
  34602. ActionManager._NothingTrigger = 0;
  34603. ActionManager._OnPickTrigger = 1;
  34604. ActionManager._OnLeftPickTrigger = 2;
  34605. ActionManager._OnRightPickTrigger = 3;
  34606. ActionManager._OnCenterPickTrigger = 4;
  34607. ActionManager._OnPickDownTrigger = 5;
  34608. ActionManager._OnPickUpTrigger = 6;
  34609. ActionManager._OnLongPressTrigger = 7;
  34610. ActionManager._OnPointerOverTrigger = 8;
  34611. ActionManager._OnPointerOutTrigger = 9;
  34612. ActionManager._OnEveryFrameTrigger = 10;
  34613. ActionManager._OnIntersectionEnterTrigger = 11;
  34614. ActionManager._OnIntersectionExitTrigger = 12;
  34615. ActionManager._OnKeyDownTrigger = 13;
  34616. ActionManager._OnKeyUpTrigger = 14;
  34617. ActionManager._OnPickOutTrigger = 15;
  34618. ActionManager.DragMovementThreshold = 10; // in pixels
  34619. ActionManager.LongPressDelay = 500; // in milliseconds
  34620. return ActionManager;
  34621. }());
  34622. BABYLON.ActionManager = ActionManager;
  34623. })(BABYLON || (BABYLON = {}));
  34624. var BABYLON;
  34625. (function (BABYLON) {
  34626. var InterpolateValueAction = (function (_super) {
  34627. __extends(InterpolateValueAction, _super);
  34628. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  34629. if (duration === void 0) { duration = 1000; }
  34630. _super.call(this, triggerOptions, condition);
  34631. this.propertyPath = propertyPath;
  34632. this.value = value;
  34633. this.duration = duration;
  34634. this.stopOtherAnimations = stopOtherAnimations;
  34635. this.onInterpolationDone = onInterpolationDone;
  34636. this._target = this._effectiveTarget = target;
  34637. }
  34638. InterpolateValueAction.prototype._prepare = function () {
  34639. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34640. this._property = this._getProperty(this.propertyPath);
  34641. };
  34642. InterpolateValueAction.prototype.execute = function () {
  34643. var scene = this._actionManager.getScene();
  34644. var keys = [
  34645. {
  34646. frame: 0,
  34647. value: this._effectiveTarget[this._property]
  34648. }, {
  34649. frame: 100,
  34650. value: this.value
  34651. }
  34652. ];
  34653. var dataType;
  34654. if (typeof this.value === "number") {
  34655. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34656. }
  34657. else if (this.value instanceof BABYLON.Color3) {
  34658. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34659. }
  34660. else if (this.value instanceof BABYLON.Vector3) {
  34661. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34662. }
  34663. else if (this.value instanceof BABYLON.Matrix) {
  34664. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34665. }
  34666. else if (this.value instanceof BABYLON.Quaternion) {
  34667. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34668. }
  34669. else {
  34670. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34671. return;
  34672. }
  34673. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34674. animation.setKeys(keys);
  34675. if (this.stopOtherAnimations) {
  34676. scene.stopAnimation(this._effectiveTarget);
  34677. }
  34678. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34679. };
  34680. InterpolateValueAction.prototype.serialize = function (parent) {
  34681. return _super.prototype._serialize.call(this, {
  34682. name: "InterpolateValueAction",
  34683. properties: [
  34684. BABYLON.Action._GetTargetProperty(this._target),
  34685. { name: "propertyPath", value: this.propertyPath },
  34686. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34687. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34688. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34689. ]
  34690. }, parent);
  34691. };
  34692. return InterpolateValueAction;
  34693. }(BABYLON.Action));
  34694. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34695. })(BABYLON || (BABYLON = {}));
  34696. var BABYLON;
  34697. (function (BABYLON) {
  34698. var SwitchBooleanAction = (function (_super) {
  34699. __extends(SwitchBooleanAction, _super);
  34700. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34701. _super.call(this, triggerOptions, condition);
  34702. this.propertyPath = propertyPath;
  34703. this._target = this._effectiveTarget = target;
  34704. }
  34705. SwitchBooleanAction.prototype._prepare = function () {
  34706. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34707. this._property = this._getProperty(this.propertyPath);
  34708. };
  34709. SwitchBooleanAction.prototype.execute = function () {
  34710. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34711. };
  34712. SwitchBooleanAction.prototype.serialize = function (parent) {
  34713. return _super.prototype._serialize.call(this, {
  34714. name: "SwitchBooleanAction",
  34715. properties: [
  34716. BABYLON.Action._GetTargetProperty(this._target),
  34717. { name: "propertyPath", value: this.propertyPath }
  34718. ]
  34719. }, parent);
  34720. };
  34721. return SwitchBooleanAction;
  34722. }(BABYLON.Action));
  34723. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34724. var SetStateAction = (function (_super) {
  34725. __extends(SetStateAction, _super);
  34726. function SetStateAction(triggerOptions, target, value, condition) {
  34727. _super.call(this, triggerOptions, condition);
  34728. this.value = value;
  34729. this._target = target;
  34730. }
  34731. SetStateAction.prototype.execute = function () {
  34732. this._target.state = this.value;
  34733. };
  34734. SetStateAction.prototype.serialize = function (parent) {
  34735. return _super.prototype._serialize.call(this, {
  34736. name: "SetStateAction",
  34737. properties: [
  34738. BABYLON.Action._GetTargetProperty(this._target),
  34739. { name: "value", value: this.value }
  34740. ]
  34741. }, parent);
  34742. };
  34743. return SetStateAction;
  34744. }(BABYLON.Action));
  34745. BABYLON.SetStateAction = SetStateAction;
  34746. var SetValueAction = (function (_super) {
  34747. __extends(SetValueAction, _super);
  34748. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34749. _super.call(this, triggerOptions, condition);
  34750. this.propertyPath = propertyPath;
  34751. this.value = value;
  34752. this._target = this._effectiveTarget = target;
  34753. }
  34754. SetValueAction.prototype._prepare = function () {
  34755. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34756. this._property = this._getProperty(this.propertyPath);
  34757. };
  34758. SetValueAction.prototype.execute = function () {
  34759. this._effectiveTarget[this._property] = this.value;
  34760. if (this._target.markAsDirty) {
  34761. this._target.markAsDirty(this._property);
  34762. }
  34763. };
  34764. SetValueAction.prototype.serialize = function (parent) {
  34765. return _super.prototype._serialize.call(this, {
  34766. name: "SetValueAction",
  34767. properties: [
  34768. BABYLON.Action._GetTargetProperty(this._target),
  34769. { name: "propertyPath", value: this.propertyPath },
  34770. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34771. ]
  34772. }, parent);
  34773. };
  34774. return SetValueAction;
  34775. }(BABYLON.Action));
  34776. BABYLON.SetValueAction = SetValueAction;
  34777. var IncrementValueAction = (function (_super) {
  34778. __extends(IncrementValueAction, _super);
  34779. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34780. _super.call(this, triggerOptions, condition);
  34781. this.propertyPath = propertyPath;
  34782. this.value = value;
  34783. this._target = this._effectiveTarget = target;
  34784. }
  34785. IncrementValueAction.prototype._prepare = function () {
  34786. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34787. this._property = this._getProperty(this.propertyPath);
  34788. if (typeof this._effectiveTarget[this._property] !== "number") {
  34789. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34790. }
  34791. };
  34792. IncrementValueAction.prototype.execute = function () {
  34793. this._effectiveTarget[this._property] += this.value;
  34794. if (this._target.markAsDirty) {
  34795. this._target.markAsDirty(this._property);
  34796. }
  34797. };
  34798. IncrementValueAction.prototype.serialize = function (parent) {
  34799. return _super.prototype._serialize.call(this, {
  34800. name: "IncrementValueAction",
  34801. properties: [
  34802. BABYLON.Action._GetTargetProperty(this._target),
  34803. { name: "propertyPath", value: this.propertyPath },
  34804. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34805. ]
  34806. }, parent);
  34807. };
  34808. return IncrementValueAction;
  34809. }(BABYLON.Action));
  34810. BABYLON.IncrementValueAction = IncrementValueAction;
  34811. var PlayAnimationAction = (function (_super) {
  34812. __extends(PlayAnimationAction, _super);
  34813. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34814. _super.call(this, triggerOptions, condition);
  34815. this.from = from;
  34816. this.to = to;
  34817. this.loop = loop;
  34818. this._target = target;
  34819. }
  34820. PlayAnimationAction.prototype._prepare = function () {
  34821. };
  34822. PlayAnimationAction.prototype.execute = function () {
  34823. var scene = this._actionManager.getScene();
  34824. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34825. };
  34826. PlayAnimationAction.prototype.serialize = function (parent) {
  34827. return _super.prototype._serialize.call(this, {
  34828. name: "PlayAnimationAction",
  34829. properties: [
  34830. BABYLON.Action._GetTargetProperty(this._target),
  34831. { name: "from", value: String(this.from) },
  34832. { name: "to", value: String(this.to) },
  34833. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34834. ]
  34835. }, parent);
  34836. };
  34837. return PlayAnimationAction;
  34838. }(BABYLON.Action));
  34839. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34840. var StopAnimationAction = (function (_super) {
  34841. __extends(StopAnimationAction, _super);
  34842. function StopAnimationAction(triggerOptions, target, condition) {
  34843. _super.call(this, triggerOptions, condition);
  34844. this._target = target;
  34845. }
  34846. StopAnimationAction.prototype._prepare = function () {
  34847. };
  34848. StopAnimationAction.prototype.execute = function () {
  34849. var scene = this._actionManager.getScene();
  34850. scene.stopAnimation(this._target);
  34851. };
  34852. StopAnimationAction.prototype.serialize = function (parent) {
  34853. return _super.prototype._serialize.call(this, {
  34854. name: "StopAnimationAction",
  34855. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34856. }, parent);
  34857. };
  34858. return StopAnimationAction;
  34859. }(BABYLON.Action));
  34860. BABYLON.StopAnimationAction = StopAnimationAction;
  34861. var DoNothingAction = (function (_super) {
  34862. __extends(DoNothingAction, _super);
  34863. function DoNothingAction(triggerOptions, condition) {
  34864. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34865. _super.call(this, triggerOptions, condition);
  34866. }
  34867. DoNothingAction.prototype.execute = function () {
  34868. };
  34869. DoNothingAction.prototype.serialize = function (parent) {
  34870. return _super.prototype._serialize.call(this, {
  34871. name: "DoNothingAction",
  34872. properties: []
  34873. }, parent);
  34874. };
  34875. return DoNothingAction;
  34876. }(BABYLON.Action));
  34877. BABYLON.DoNothingAction = DoNothingAction;
  34878. var CombineAction = (function (_super) {
  34879. __extends(CombineAction, _super);
  34880. function CombineAction(triggerOptions, children, condition) {
  34881. _super.call(this, triggerOptions, condition);
  34882. this.children = children;
  34883. }
  34884. CombineAction.prototype._prepare = function () {
  34885. for (var index = 0; index < this.children.length; index++) {
  34886. this.children[index]._actionManager = this._actionManager;
  34887. this.children[index]._prepare();
  34888. }
  34889. };
  34890. CombineAction.prototype.execute = function (evt) {
  34891. for (var index = 0; index < this.children.length; index++) {
  34892. this.children[index].execute(evt);
  34893. }
  34894. };
  34895. CombineAction.prototype.serialize = function (parent) {
  34896. var serializationObject = _super.prototype._serialize.call(this, {
  34897. name: "CombineAction",
  34898. properties: [],
  34899. combine: []
  34900. }, parent);
  34901. for (var i = 0; i < this.children.length; i++) {
  34902. serializationObject.combine.push(this.children[i].serialize(null));
  34903. }
  34904. return serializationObject;
  34905. };
  34906. return CombineAction;
  34907. }(BABYLON.Action));
  34908. BABYLON.CombineAction = CombineAction;
  34909. var ExecuteCodeAction = (function (_super) {
  34910. __extends(ExecuteCodeAction, _super);
  34911. function ExecuteCodeAction(triggerOptions, func, condition) {
  34912. _super.call(this, triggerOptions, condition);
  34913. this.func = func;
  34914. }
  34915. ExecuteCodeAction.prototype.execute = function (evt) {
  34916. this.func(evt);
  34917. };
  34918. return ExecuteCodeAction;
  34919. }(BABYLON.Action));
  34920. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34921. var SetParentAction = (function (_super) {
  34922. __extends(SetParentAction, _super);
  34923. function SetParentAction(triggerOptions, target, parent, condition) {
  34924. _super.call(this, triggerOptions, condition);
  34925. this._target = target;
  34926. this._parent = parent;
  34927. }
  34928. SetParentAction.prototype._prepare = function () {
  34929. };
  34930. SetParentAction.prototype.execute = function () {
  34931. if (this._target.parent === this._parent) {
  34932. return;
  34933. }
  34934. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34935. invertParentWorldMatrix.invert();
  34936. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34937. this._target.parent = this._parent;
  34938. };
  34939. SetParentAction.prototype.serialize = function (parent) {
  34940. return _super.prototype._serialize.call(this, {
  34941. name: "SetParentAction",
  34942. properties: [
  34943. BABYLON.Action._GetTargetProperty(this._target),
  34944. BABYLON.Action._GetTargetProperty(this._parent),
  34945. ]
  34946. }, parent);
  34947. };
  34948. return SetParentAction;
  34949. }(BABYLON.Action));
  34950. BABYLON.SetParentAction = SetParentAction;
  34951. var PlaySoundAction = (function (_super) {
  34952. __extends(PlaySoundAction, _super);
  34953. function PlaySoundAction(triggerOptions, sound, condition) {
  34954. _super.call(this, triggerOptions, condition);
  34955. this._sound = sound;
  34956. }
  34957. PlaySoundAction.prototype._prepare = function () {
  34958. };
  34959. PlaySoundAction.prototype.execute = function () {
  34960. if (this._sound !== undefined)
  34961. this._sound.play();
  34962. };
  34963. PlaySoundAction.prototype.serialize = function (parent) {
  34964. return _super.prototype._serialize.call(this, {
  34965. name: "PlaySoundAction",
  34966. properties: [{ name: "sound", value: this._sound.name }]
  34967. }, parent);
  34968. };
  34969. return PlaySoundAction;
  34970. }(BABYLON.Action));
  34971. BABYLON.PlaySoundAction = PlaySoundAction;
  34972. var StopSoundAction = (function (_super) {
  34973. __extends(StopSoundAction, _super);
  34974. function StopSoundAction(triggerOptions, sound, condition) {
  34975. _super.call(this, triggerOptions, condition);
  34976. this._sound = sound;
  34977. }
  34978. StopSoundAction.prototype._prepare = function () {
  34979. };
  34980. StopSoundAction.prototype.execute = function () {
  34981. if (this._sound !== undefined)
  34982. this._sound.stop();
  34983. };
  34984. StopSoundAction.prototype.serialize = function (parent) {
  34985. return _super.prototype._serialize.call(this, {
  34986. name: "StopSoundAction",
  34987. properties: [{ name: "sound", value: this._sound.name }]
  34988. }, parent);
  34989. };
  34990. return StopSoundAction;
  34991. }(BABYLON.Action));
  34992. BABYLON.StopSoundAction = StopSoundAction;
  34993. })(BABYLON || (BABYLON = {}));
  34994. var BABYLON;
  34995. (function (BABYLON) {
  34996. var Geometry = (function () {
  34997. function Geometry(id, scene, vertexData, updatable, mesh) {
  34998. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34999. this._totalVertices = 0;
  35000. this._isDisposed = false;
  35001. this.id = id;
  35002. this._engine = scene.getEngine();
  35003. this._meshes = [];
  35004. this._scene = scene;
  35005. //Init vertex buffer cache
  35006. this._vertexBuffers = {};
  35007. this._indices = [];
  35008. // vertexData
  35009. if (vertexData) {
  35010. this.setAllVerticesData(vertexData, updatable);
  35011. }
  35012. else {
  35013. this._totalVertices = 0;
  35014. this._indices = [];
  35015. }
  35016. // applyToMesh
  35017. if (mesh) {
  35018. if (mesh instanceof BABYLON.LinesMesh) {
  35019. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35020. this.updateExtend();
  35021. }
  35022. this.applyToMesh(mesh);
  35023. mesh.computeWorldMatrix(true);
  35024. }
  35025. }
  35026. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35027. /**
  35028. * 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
  35029. * @returns The Bias Vector
  35030. */
  35031. get: function () {
  35032. return this._boundingBias;
  35033. },
  35034. set: function (value) {
  35035. if (this._boundingBias && this._boundingBias.equals(value)) {
  35036. return;
  35037. }
  35038. this._boundingBias = value.clone();
  35039. this.updateBoundingInfo(true, null);
  35040. },
  35041. enumerable: true,
  35042. configurable: true
  35043. });
  35044. Object.defineProperty(Geometry.prototype, "extend", {
  35045. get: function () {
  35046. return this._extend;
  35047. },
  35048. enumerable: true,
  35049. configurable: true
  35050. });
  35051. Geometry.prototype.getScene = function () {
  35052. return this._scene;
  35053. };
  35054. Geometry.prototype.getEngine = function () {
  35055. return this._engine;
  35056. };
  35057. Geometry.prototype.isReady = function () {
  35058. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35059. };
  35060. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35061. vertexData.applyToGeometry(this, updatable);
  35062. this.notifyUpdate();
  35063. };
  35064. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35065. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35066. this.setVerticesBuffer(buffer);
  35067. };
  35068. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35069. var kind = buffer.getKind();
  35070. if (this._vertexBuffers[kind]) {
  35071. this._vertexBuffers[kind].dispose();
  35072. }
  35073. this._vertexBuffers[kind] = buffer;
  35074. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35075. var data = buffer.getData();
  35076. var stride = buffer.getStrideSize();
  35077. this._totalVertices = data.length / stride;
  35078. this.updateExtend(data, stride);
  35079. var meshes = this._meshes;
  35080. var numOfMeshes = meshes.length;
  35081. for (var index = 0; index < numOfMeshes; index++) {
  35082. var mesh = meshes[index];
  35083. mesh._resetPointsArrayCache();
  35084. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35085. mesh._createGlobalSubMesh();
  35086. mesh.computeWorldMatrix(true);
  35087. }
  35088. }
  35089. this.notifyUpdate(kind);
  35090. };
  35091. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35092. var vertexBuffer = this.getVertexBuffer(kind);
  35093. if (!vertexBuffer) {
  35094. return;
  35095. }
  35096. vertexBuffer.updateDirectly(data, offset);
  35097. this.notifyUpdate(kind);
  35098. };
  35099. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35100. var vertexBuffer = this.getVertexBuffer(kind);
  35101. if (!vertexBuffer) {
  35102. return;
  35103. }
  35104. vertexBuffer.update(data);
  35105. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35106. var stride = vertexBuffer.getStrideSize();
  35107. this._totalVertices = data.length / stride;
  35108. this.updateBoundingInfo(updateExtends, data);
  35109. }
  35110. this.notifyUpdate(kind);
  35111. };
  35112. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35113. if (updateExtends) {
  35114. this.updateExtend(data);
  35115. }
  35116. var meshes = this._meshes;
  35117. var numOfMeshes = meshes.length;
  35118. for (var index = 0; index < numOfMeshes; index++) {
  35119. var mesh = meshes[index];
  35120. mesh._resetPointsArrayCache();
  35121. if (updateExtends) {
  35122. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35123. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35124. var subMesh = mesh.subMeshes[subIndex];
  35125. subMesh.refreshBoundingInfo();
  35126. }
  35127. }
  35128. }
  35129. };
  35130. Geometry.prototype.getTotalVertices = function () {
  35131. if (!this.isReady()) {
  35132. return 0;
  35133. }
  35134. return this._totalVertices;
  35135. };
  35136. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  35137. var vertexBuffer = this.getVertexBuffer(kind);
  35138. if (!vertexBuffer) {
  35139. return null;
  35140. }
  35141. var orig = vertexBuffer.getData();
  35142. if (!copyWhenShared || this._meshes.length === 1) {
  35143. return orig;
  35144. }
  35145. else {
  35146. var len = orig.length;
  35147. var copy = [];
  35148. for (var i = 0; i < len; i++) {
  35149. copy.push(orig[i]);
  35150. }
  35151. return copy;
  35152. }
  35153. };
  35154. Geometry.prototype.getVertexBuffer = function (kind) {
  35155. if (!this.isReady()) {
  35156. return null;
  35157. }
  35158. return this._vertexBuffers[kind];
  35159. };
  35160. Geometry.prototype.getVertexBuffers = function () {
  35161. if (!this.isReady()) {
  35162. return null;
  35163. }
  35164. return this._vertexBuffers;
  35165. };
  35166. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35167. if (!this._vertexBuffers) {
  35168. if (this._delayInfo) {
  35169. return this._delayInfo.indexOf(kind) !== -1;
  35170. }
  35171. return false;
  35172. }
  35173. return this._vertexBuffers[kind] !== undefined;
  35174. };
  35175. Geometry.prototype.getVerticesDataKinds = function () {
  35176. var result = [];
  35177. var kind;
  35178. if (!this._vertexBuffers && this._delayInfo) {
  35179. for (kind in this._delayInfo) {
  35180. result.push(kind);
  35181. }
  35182. }
  35183. else {
  35184. for (kind in this._vertexBuffers) {
  35185. result.push(kind);
  35186. }
  35187. }
  35188. return result;
  35189. };
  35190. Geometry.prototype.setIndices = function (indices, totalVertices) {
  35191. if (this._indexBuffer) {
  35192. this._engine._releaseBuffer(this._indexBuffer);
  35193. }
  35194. this._indices = indices;
  35195. if (this._meshes.length !== 0 && this._indices) {
  35196. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35197. }
  35198. if (totalVertices !== undefined) {
  35199. this._totalVertices = totalVertices;
  35200. }
  35201. var meshes = this._meshes;
  35202. var numOfMeshes = meshes.length;
  35203. for (var index = 0; index < numOfMeshes; index++) {
  35204. meshes[index]._createGlobalSubMesh();
  35205. }
  35206. this.notifyUpdate();
  35207. };
  35208. Geometry.prototype.getTotalIndices = function () {
  35209. if (!this.isReady()) {
  35210. return 0;
  35211. }
  35212. return this._indices.length;
  35213. };
  35214. Geometry.prototype.getIndices = function (copyWhenShared) {
  35215. if (!this.isReady()) {
  35216. return null;
  35217. }
  35218. var orig = this._indices;
  35219. if (!copyWhenShared || this._meshes.length === 1) {
  35220. return orig;
  35221. }
  35222. else {
  35223. var len = orig.length;
  35224. var copy = [];
  35225. for (var i = 0; i < len; i++) {
  35226. copy.push(orig[i]);
  35227. }
  35228. return copy;
  35229. }
  35230. };
  35231. Geometry.prototype.getIndexBuffer = function () {
  35232. if (!this.isReady()) {
  35233. return null;
  35234. }
  35235. return this._indexBuffer;
  35236. };
  35237. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35238. var meshes = this._meshes;
  35239. var index = meshes.indexOf(mesh);
  35240. if (index === -1) {
  35241. return;
  35242. }
  35243. for (var kind in this._vertexBuffers) {
  35244. this._vertexBuffers[kind].dispose();
  35245. }
  35246. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  35247. this._indexBuffer = null;
  35248. }
  35249. meshes.splice(index, 1);
  35250. mesh._geometry = null;
  35251. if (meshes.length === 0 && shouldDispose) {
  35252. this.dispose();
  35253. }
  35254. };
  35255. Geometry.prototype.applyToMesh = function (mesh) {
  35256. if (mesh._geometry === this) {
  35257. return;
  35258. }
  35259. var previousGeometry = mesh._geometry;
  35260. if (previousGeometry) {
  35261. previousGeometry.releaseForMesh(mesh);
  35262. }
  35263. var meshes = this._meshes;
  35264. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35265. mesh._geometry = this;
  35266. this._scene.pushGeometry(this);
  35267. meshes.push(mesh);
  35268. if (this.isReady()) {
  35269. this._applyToMesh(mesh);
  35270. }
  35271. else {
  35272. mesh._boundingInfo = this._boundingInfo;
  35273. }
  35274. };
  35275. Geometry.prototype.updateExtend = function (data, stride) {
  35276. if (data === void 0) { data = null; }
  35277. if (!data) {
  35278. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35279. }
  35280. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35281. };
  35282. Geometry.prototype._applyToMesh = function (mesh) {
  35283. var numOfMeshes = this._meshes.length;
  35284. // vertexBuffers
  35285. for (var kind in this._vertexBuffers) {
  35286. if (numOfMeshes === 1) {
  35287. this._vertexBuffers[kind].create();
  35288. }
  35289. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  35290. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35291. mesh._resetPointsArrayCache();
  35292. if (!this._extend) {
  35293. this.updateExtend(this._vertexBuffers[kind].getData());
  35294. }
  35295. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35296. mesh._createGlobalSubMesh();
  35297. //bounding info was just created again, world matrix should be applied again.
  35298. mesh._updateBoundingInfo();
  35299. }
  35300. }
  35301. // indexBuffer
  35302. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35303. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35304. }
  35305. if (this._indexBuffer) {
  35306. this._indexBuffer.references = numOfMeshes;
  35307. }
  35308. };
  35309. Geometry.prototype.notifyUpdate = function (kind) {
  35310. if (this.onGeometryUpdated) {
  35311. this.onGeometryUpdated(this, kind);
  35312. }
  35313. };
  35314. Geometry.prototype.load = function (scene, onLoaded) {
  35315. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35316. return;
  35317. }
  35318. if (this.isReady()) {
  35319. if (onLoaded) {
  35320. onLoaded();
  35321. }
  35322. return;
  35323. }
  35324. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35325. this._queueLoad(scene, onLoaded);
  35326. };
  35327. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35328. var _this = this;
  35329. scene._addPendingData(this);
  35330. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  35331. _this._delayLoadingFunction(JSON.parse(data), _this);
  35332. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35333. _this._delayInfo = [];
  35334. scene._removePendingData(_this);
  35335. var meshes = _this._meshes;
  35336. var numOfMeshes = meshes.length;
  35337. for (var index = 0; index < numOfMeshes; index++) {
  35338. _this._applyToMesh(meshes[index]);
  35339. }
  35340. if (onLoaded) {
  35341. onLoaded();
  35342. }
  35343. }, function () { }, scene.database);
  35344. };
  35345. /**
  35346. * Invert the geometry to move from a right handed system to a left handed one.
  35347. */
  35348. Geometry.prototype.toLeftHanded = function () {
  35349. // Flip faces
  35350. var tIndices = this.getIndices(false);
  35351. if (tIndices != null && tIndices.length > 0) {
  35352. for (var i = 0; i < tIndices.length; i += 3) {
  35353. var tTemp = tIndices[i + 0];
  35354. tIndices[i + 0] = tIndices[i + 2];
  35355. tIndices[i + 2] = tTemp;
  35356. }
  35357. this.setIndices(tIndices);
  35358. }
  35359. // Negate position.z
  35360. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35361. if (tPositions != null && tPositions.length > 0) {
  35362. for (var i = 0; i < tPositions.length; i += 3) {
  35363. tPositions[i + 2] = -tPositions[i + 2];
  35364. }
  35365. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35366. }
  35367. // Negate normal.z
  35368. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35369. if (tNormals != null && tNormals.length > 0) {
  35370. for (var i = 0; i < tNormals.length; i += 3) {
  35371. tNormals[i + 2] = -tNormals[i + 2];
  35372. }
  35373. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35374. }
  35375. };
  35376. Geometry.prototype.isDisposed = function () {
  35377. return this._isDisposed;
  35378. };
  35379. Geometry.prototype.dispose = function () {
  35380. var meshes = this._meshes;
  35381. var numOfMeshes = meshes.length;
  35382. var index;
  35383. for (index = 0; index < numOfMeshes; index++) {
  35384. this.releaseForMesh(meshes[index]);
  35385. }
  35386. this._meshes = [];
  35387. for (var kind in this._vertexBuffers) {
  35388. this._vertexBuffers[kind].dispose();
  35389. }
  35390. this._vertexBuffers = {};
  35391. this._totalVertices = 0;
  35392. if (this._indexBuffer) {
  35393. this._engine._releaseBuffer(this._indexBuffer);
  35394. }
  35395. this._indexBuffer = null;
  35396. this._indices = [];
  35397. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35398. this.delayLoadingFile = null;
  35399. this._delayLoadingFunction = null;
  35400. this._delayInfo = [];
  35401. this._boundingInfo = null;
  35402. this._scene.removeGeometry(this);
  35403. this._isDisposed = true;
  35404. };
  35405. Geometry.prototype.copy = function (id) {
  35406. var vertexData = new BABYLON.VertexData();
  35407. vertexData.indices = [];
  35408. var indices = this.getIndices();
  35409. for (var index = 0; index < indices.length; index++) {
  35410. vertexData.indices.push(indices[index]);
  35411. }
  35412. var updatable = false;
  35413. var stopChecking = false;
  35414. var kind;
  35415. for (kind in this._vertexBuffers) {
  35416. // using slice() to make a copy of the array and not just reference it
  35417. var data = this.getVerticesData(kind);
  35418. if (data instanceof Float32Array) {
  35419. vertexData.set(new Float32Array(data), kind);
  35420. }
  35421. else {
  35422. vertexData.set(data.slice(0), kind);
  35423. }
  35424. if (!stopChecking) {
  35425. updatable = this.getVertexBuffer(kind).isUpdatable();
  35426. stopChecking = !updatable;
  35427. }
  35428. }
  35429. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  35430. geometry.delayLoadState = this.delayLoadState;
  35431. geometry.delayLoadingFile = this.delayLoadingFile;
  35432. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35433. for (kind in this._delayInfo) {
  35434. geometry._delayInfo = geometry._delayInfo || [];
  35435. geometry._delayInfo.push(kind);
  35436. }
  35437. // Bounding info
  35438. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35439. return geometry;
  35440. };
  35441. Geometry.prototype.serialize = function () {
  35442. var serializationObject = {};
  35443. serializationObject.id = this.id;
  35444. if (BABYLON.Tags.HasTags(this)) {
  35445. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35446. }
  35447. return serializationObject;
  35448. };
  35449. Geometry.prototype.serializeVerticeData = function () {
  35450. var serializationObject = this.serialize();
  35451. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35452. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35453. }
  35454. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35455. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35456. }
  35457. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35458. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35459. }
  35460. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35461. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  35462. }
  35463. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35464. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  35465. }
  35466. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35467. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  35468. }
  35469. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35470. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  35471. }
  35472. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35473. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  35474. }
  35475. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35476. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35477. }
  35478. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35479. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35480. serializationObject.matricesIndices._isExpanded = true;
  35481. }
  35482. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35483. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35484. }
  35485. serializationObject.indices = this.getIndices();
  35486. return serializationObject;
  35487. };
  35488. // Statics
  35489. Geometry.ExtractFromMesh = function (mesh, id) {
  35490. var geometry = mesh._geometry;
  35491. if (!geometry) {
  35492. return null;
  35493. }
  35494. return geometry.copy(id);
  35495. };
  35496. /**
  35497. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35498. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35499. * Be aware Math.random() could cause collisions, but:
  35500. * "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"
  35501. */
  35502. Geometry.RandomId = function () {
  35503. return BABYLON.Tools.RandomId();
  35504. };
  35505. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  35506. var scene = mesh.getScene();
  35507. // Geometry
  35508. var geometryId = parsedGeometry.geometryId;
  35509. if (geometryId) {
  35510. var geometry = scene.getGeometryByID(geometryId);
  35511. if (geometry) {
  35512. geometry.applyToMesh(mesh);
  35513. }
  35514. }
  35515. else if (parsedGeometry instanceof ArrayBuffer) {
  35516. var binaryInfo = mesh._binaryInfo;
  35517. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35518. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35519. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35520. }
  35521. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35522. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35523. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35524. }
  35525. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35526. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35527. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35528. }
  35529. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35530. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35531. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35532. }
  35533. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35534. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35535. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35536. }
  35537. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35538. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35539. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35540. }
  35541. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35542. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35543. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35544. }
  35545. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35546. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35547. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35548. }
  35549. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35550. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35551. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35552. }
  35553. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35554. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35555. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35556. }
  35557. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35558. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35559. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35560. }
  35561. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35562. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35563. mesh.setIndices(indicesData);
  35564. }
  35565. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35566. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35567. mesh.subMeshes = [];
  35568. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35569. var materialIndex = subMeshesData[(i * 5) + 0];
  35570. var verticesStart = subMeshesData[(i * 5) + 1];
  35571. var verticesCount = subMeshesData[(i * 5) + 2];
  35572. var indexStart = subMeshesData[(i * 5) + 3];
  35573. var indexCount = subMeshesData[(i * 5) + 4];
  35574. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35575. }
  35576. }
  35577. }
  35578. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35579. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  35580. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  35581. if (parsedGeometry.uvs) {
  35582. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  35583. }
  35584. if (parsedGeometry.uvs2) {
  35585. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  35586. }
  35587. if (parsedGeometry.uvs3) {
  35588. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  35589. }
  35590. if (parsedGeometry.uvs4) {
  35591. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  35592. }
  35593. if (parsedGeometry.uvs5) {
  35594. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  35595. }
  35596. if (parsedGeometry.uvs6) {
  35597. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  35598. }
  35599. if (parsedGeometry.colors) {
  35600. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  35601. }
  35602. if (parsedGeometry.matricesIndices) {
  35603. if (!parsedGeometry.matricesIndices._isExpanded) {
  35604. var floatIndices = [];
  35605. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35606. var matricesIndex = parsedGeometry.matricesIndices[i];
  35607. floatIndices.push(matricesIndex & 0x000000FF);
  35608. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35609. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35610. floatIndices.push(matricesIndex >> 24);
  35611. }
  35612. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  35613. }
  35614. else {
  35615. delete parsedGeometry.matricesIndices._isExpanded;
  35616. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  35617. }
  35618. }
  35619. if (parsedGeometry.matricesIndicesExtra) {
  35620. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35621. var floatIndices = [];
  35622. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35623. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35624. floatIndices.push(matricesIndex & 0x000000FF);
  35625. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35626. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35627. floatIndices.push(matricesIndex >> 24);
  35628. }
  35629. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  35630. }
  35631. else {
  35632. delete parsedGeometry.matricesIndices._isExpanded;
  35633. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  35634. }
  35635. }
  35636. if (parsedGeometry.matricesWeights) {
  35637. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  35638. }
  35639. if (parsedGeometry.matricesWeightsExtra) {
  35640. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  35641. }
  35642. mesh.setIndices(parsedGeometry.indices);
  35643. }
  35644. // SubMeshes
  35645. if (parsedGeometry.subMeshes) {
  35646. mesh.subMeshes = [];
  35647. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35648. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35649. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35650. }
  35651. }
  35652. // Flat shading
  35653. if (mesh._shouldGenerateFlatShading) {
  35654. mesh.convertToFlatShadedMesh();
  35655. delete mesh._shouldGenerateFlatShading;
  35656. }
  35657. // Update
  35658. mesh.computeWorldMatrix(true);
  35659. // Octree
  35660. if (scene['_selectionOctree']) {
  35661. scene['_selectionOctree'].addMesh(mesh);
  35662. }
  35663. };
  35664. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35665. if (scene.getGeometryByID(parsedVertexData.id)) {
  35666. return null; // null since geometry could be something else than a box...
  35667. }
  35668. var geometry = new Geometry(parsedVertexData.id, scene);
  35669. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35670. if (parsedVertexData.delayLoadingFile) {
  35671. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35672. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35673. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35674. geometry._delayInfo = [];
  35675. if (parsedVertexData.hasUVs) {
  35676. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35677. }
  35678. if (parsedVertexData.hasUVs2) {
  35679. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35680. }
  35681. if (parsedVertexData.hasUVs3) {
  35682. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35683. }
  35684. if (parsedVertexData.hasUVs4) {
  35685. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35686. }
  35687. if (parsedVertexData.hasUVs5) {
  35688. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35689. }
  35690. if (parsedVertexData.hasUVs6) {
  35691. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35692. }
  35693. if (parsedVertexData.hasColors) {
  35694. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35695. }
  35696. if (parsedVertexData.hasMatricesIndices) {
  35697. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35698. }
  35699. if (parsedVertexData.hasMatricesWeights) {
  35700. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35701. }
  35702. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35703. }
  35704. else {
  35705. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35706. }
  35707. scene.pushGeometry(geometry, true);
  35708. return geometry;
  35709. };
  35710. return Geometry;
  35711. }());
  35712. BABYLON.Geometry = Geometry;
  35713. /////// Primitives //////////////////////////////////////////////
  35714. var Geometry;
  35715. (function (Geometry) {
  35716. var Primitives;
  35717. (function (Primitives) {
  35718. /// Abstract class
  35719. var _Primitive = (function (_super) {
  35720. __extends(_Primitive, _super);
  35721. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  35722. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  35723. this._canBeRegenerated = _canBeRegenerated;
  35724. this._beingRegenerated = true;
  35725. this.regenerate();
  35726. this._beingRegenerated = false;
  35727. }
  35728. _Primitive.prototype.canBeRegenerated = function () {
  35729. return this._canBeRegenerated;
  35730. };
  35731. _Primitive.prototype.regenerate = function () {
  35732. if (!this._canBeRegenerated) {
  35733. return;
  35734. }
  35735. this._beingRegenerated = true;
  35736. this.setAllVerticesData(this._regenerateVertexData(), false);
  35737. this._beingRegenerated = false;
  35738. };
  35739. _Primitive.prototype.asNewGeometry = function (id) {
  35740. return _super.prototype.copy.call(this, id);
  35741. };
  35742. // overrides
  35743. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  35744. if (!this._beingRegenerated) {
  35745. return;
  35746. }
  35747. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35748. };
  35749. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  35750. if (!this._beingRegenerated) {
  35751. return;
  35752. }
  35753. _super.prototype.setVerticesData.call(this, kind, data, false);
  35754. };
  35755. // to override
  35756. // protected
  35757. _Primitive.prototype._regenerateVertexData = function () {
  35758. throw new Error("Abstract method");
  35759. };
  35760. _Primitive.prototype.copy = function (id) {
  35761. throw new Error("Must be overriden in sub-classes.");
  35762. };
  35763. _Primitive.prototype.serialize = function () {
  35764. var serializationObject = _super.prototype.serialize.call(this);
  35765. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35766. return serializationObject;
  35767. };
  35768. return _Primitive;
  35769. }(Geometry));
  35770. Primitives._Primitive = _Primitive;
  35771. var Ribbon = (function (_super) {
  35772. __extends(Ribbon, _super);
  35773. // Members
  35774. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  35775. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35776. _super.call(this, id, scene, canBeRegenerated, mesh);
  35777. this.pathArray = pathArray;
  35778. this.closeArray = closeArray;
  35779. this.closePath = closePath;
  35780. this.offset = offset;
  35781. this.side = side;
  35782. }
  35783. Ribbon.prototype._regenerateVertexData = function () {
  35784. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35785. };
  35786. Ribbon.prototype.copy = function (id) {
  35787. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  35788. };
  35789. return Ribbon;
  35790. }(_Primitive));
  35791. Primitives.Ribbon = Ribbon;
  35792. var Box = (function (_super) {
  35793. __extends(Box, _super);
  35794. // Members
  35795. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  35796. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35797. _super.call(this, id, scene, canBeRegenerated, mesh);
  35798. this.size = size;
  35799. this.side = side;
  35800. }
  35801. Box.prototype._regenerateVertexData = function () {
  35802. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35803. };
  35804. Box.prototype.copy = function (id) {
  35805. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35806. };
  35807. Box.prototype.serialize = function () {
  35808. var serializationObject = _super.prototype.serialize.call(this);
  35809. serializationObject.size = this.size;
  35810. return serializationObject;
  35811. };
  35812. Box.Parse = function (parsedBox, scene) {
  35813. if (scene.getGeometryByID(parsedBox.id)) {
  35814. return null; // null since geometry could be something else than a box...
  35815. }
  35816. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35817. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35818. scene.pushGeometry(box, true);
  35819. return box;
  35820. };
  35821. return Box;
  35822. }(_Primitive));
  35823. Primitives.Box = Box;
  35824. var Sphere = (function (_super) {
  35825. __extends(Sphere, _super);
  35826. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  35827. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35828. _super.call(this, id, scene, canBeRegenerated, mesh);
  35829. this.segments = segments;
  35830. this.diameter = diameter;
  35831. this.side = side;
  35832. }
  35833. Sphere.prototype._regenerateVertexData = function () {
  35834. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35835. };
  35836. Sphere.prototype.copy = function (id) {
  35837. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35838. };
  35839. Sphere.prototype.serialize = function () {
  35840. var serializationObject = _super.prototype.serialize.call(this);
  35841. serializationObject.segments = this.segments;
  35842. serializationObject.diameter = this.diameter;
  35843. return serializationObject;
  35844. };
  35845. Sphere.Parse = function (parsedSphere, scene) {
  35846. if (scene.getGeometryByID(parsedSphere.id)) {
  35847. return null; // null since geometry could be something else than a sphere...
  35848. }
  35849. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35850. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35851. scene.pushGeometry(sphere, true);
  35852. return sphere;
  35853. };
  35854. return Sphere;
  35855. }(_Primitive));
  35856. Primitives.Sphere = Sphere;
  35857. var Disc = (function (_super) {
  35858. __extends(Disc, _super);
  35859. // Members
  35860. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  35861. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35862. _super.call(this, id, scene, canBeRegenerated, mesh);
  35863. this.radius = radius;
  35864. this.tessellation = tessellation;
  35865. this.side = side;
  35866. }
  35867. Disc.prototype._regenerateVertexData = function () {
  35868. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35869. };
  35870. Disc.prototype.copy = function (id) {
  35871. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35872. };
  35873. return Disc;
  35874. }(_Primitive));
  35875. Primitives.Disc = Disc;
  35876. var Cylinder = (function (_super) {
  35877. __extends(Cylinder, _super);
  35878. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  35879. if (subdivisions === void 0) { subdivisions = 1; }
  35880. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35881. _super.call(this, id, scene, canBeRegenerated, mesh);
  35882. this.height = height;
  35883. this.diameterTop = diameterTop;
  35884. this.diameterBottom = diameterBottom;
  35885. this.tessellation = tessellation;
  35886. this.subdivisions = subdivisions;
  35887. this.side = side;
  35888. }
  35889. Cylinder.prototype._regenerateVertexData = function () {
  35890. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35891. };
  35892. Cylinder.prototype.copy = function (id) {
  35893. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35894. };
  35895. Cylinder.prototype.serialize = function () {
  35896. var serializationObject = _super.prototype.serialize.call(this);
  35897. serializationObject.height = this.height;
  35898. serializationObject.diameterTop = this.diameterTop;
  35899. serializationObject.diameterBottom = this.diameterBottom;
  35900. serializationObject.tessellation = this.tessellation;
  35901. return serializationObject;
  35902. };
  35903. Cylinder.Parse = function (parsedCylinder, scene) {
  35904. if (scene.getGeometryByID(parsedCylinder.id)) {
  35905. return null; // null since geometry could be something else than a cylinder...
  35906. }
  35907. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35908. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35909. scene.pushGeometry(cylinder, true);
  35910. return cylinder;
  35911. };
  35912. return Cylinder;
  35913. }(_Primitive));
  35914. Primitives.Cylinder = Cylinder;
  35915. var Torus = (function (_super) {
  35916. __extends(Torus, _super);
  35917. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  35918. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35919. _super.call(this, id, scene, canBeRegenerated, mesh);
  35920. this.diameter = diameter;
  35921. this.thickness = thickness;
  35922. this.tessellation = tessellation;
  35923. this.side = side;
  35924. }
  35925. Torus.prototype._regenerateVertexData = function () {
  35926. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35927. };
  35928. Torus.prototype.copy = function (id) {
  35929. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35930. };
  35931. Torus.prototype.serialize = function () {
  35932. var serializationObject = _super.prototype.serialize.call(this);
  35933. serializationObject.diameter = this.diameter;
  35934. serializationObject.thickness = this.thickness;
  35935. serializationObject.tessellation = this.tessellation;
  35936. return serializationObject;
  35937. };
  35938. Torus.Parse = function (parsedTorus, scene) {
  35939. if (scene.getGeometryByID(parsedTorus.id)) {
  35940. return null; // null since geometry could be something else than a torus...
  35941. }
  35942. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35943. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35944. scene.pushGeometry(torus, true);
  35945. return torus;
  35946. };
  35947. return Torus;
  35948. }(_Primitive));
  35949. Primitives.Torus = Torus;
  35950. var Ground = (function (_super) {
  35951. __extends(Ground, _super);
  35952. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  35953. _super.call(this, id, scene, canBeRegenerated, mesh);
  35954. this.width = width;
  35955. this.height = height;
  35956. this.subdivisions = subdivisions;
  35957. }
  35958. Ground.prototype._regenerateVertexData = function () {
  35959. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35960. };
  35961. Ground.prototype.copy = function (id) {
  35962. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35963. };
  35964. Ground.prototype.serialize = function () {
  35965. var serializationObject = _super.prototype.serialize.call(this);
  35966. serializationObject.width = this.width;
  35967. serializationObject.height = this.height;
  35968. serializationObject.subdivisions = this.subdivisions;
  35969. return serializationObject;
  35970. };
  35971. Ground.Parse = function (parsedGround, scene) {
  35972. if (scene.getGeometryByID(parsedGround.id)) {
  35973. return null; // null since geometry could be something else than a ground...
  35974. }
  35975. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35976. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35977. scene.pushGeometry(ground, true);
  35978. return ground;
  35979. };
  35980. return Ground;
  35981. }(_Primitive));
  35982. Primitives.Ground = Ground;
  35983. var TiledGround = (function (_super) {
  35984. __extends(TiledGround, _super);
  35985. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  35986. _super.call(this, id, scene, canBeRegenerated, mesh);
  35987. this.xmin = xmin;
  35988. this.zmin = zmin;
  35989. this.xmax = xmax;
  35990. this.zmax = zmax;
  35991. this.subdivisions = subdivisions;
  35992. this.precision = precision;
  35993. }
  35994. TiledGround.prototype._regenerateVertexData = function () {
  35995. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35996. };
  35997. TiledGround.prototype.copy = function (id) {
  35998. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35999. };
  36000. return TiledGround;
  36001. }(_Primitive));
  36002. Primitives.TiledGround = TiledGround;
  36003. var Plane = (function (_super) {
  36004. __extends(Plane, _super);
  36005. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  36006. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36007. _super.call(this, id, scene, canBeRegenerated, mesh);
  36008. this.size = size;
  36009. this.side = side;
  36010. }
  36011. Plane.prototype._regenerateVertexData = function () {
  36012. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36013. };
  36014. Plane.prototype.copy = function (id) {
  36015. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36016. };
  36017. Plane.prototype.serialize = function () {
  36018. var serializationObject = _super.prototype.serialize.call(this);
  36019. serializationObject.size = this.size;
  36020. return serializationObject;
  36021. };
  36022. Plane.Parse = function (parsedPlane, scene) {
  36023. if (scene.getGeometryByID(parsedPlane.id)) {
  36024. return null; // null since geometry could be something else than a ground...
  36025. }
  36026. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36027. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36028. scene.pushGeometry(plane, true);
  36029. return plane;
  36030. };
  36031. return Plane;
  36032. }(_Primitive));
  36033. Primitives.Plane = Plane;
  36034. var TorusKnot = (function (_super) {
  36035. __extends(TorusKnot, _super);
  36036. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  36037. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36038. _super.call(this, id, scene, canBeRegenerated, mesh);
  36039. this.radius = radius;
  36040. this.tube = tube;
  36041. this.radialSegments = radialSegments;
  36042. this.tubularSegments = tubularSegments;
  36043. this.p = p;
  36044. this.q = q;
  36045. this.side = side;
  36046. }
  36047. TorusKnot.prototype._regenerateVertexData = function () {
  36048. 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 });
  36049. };
  36050. TorusKnot.prototype.copy = function (id) {
  36051. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36052. };
  36053. TorusKnot.prototype.serialize = function () {
  36054. var serializationObject = _super.prototype.serialize.call(this);
  36055. serializationObject.radius = this.radius;
  36056. serializationObject.tube = this.tube;
  36057. serializationObject.radialSegments = this.radialSegments;
  36058. serializationObject.tubularSegments = this.tubularSegments;
  36059. serializationObject.p = this.p;
  36060. serializationObject.q = this.q;
  36061. return serializationObject;
  36062. };
  36063. ;
  36064. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  36065. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36066. return null; // null since geometry could be something else than a ground...
  36067. }
  36068. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36069. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36070. scene.pushGeometry(torusKnot, true);
  36071. return torusKnot;
  36072. };
  36073. return TorusKnot;
  36074. }(_Primitive));
  36075. Primitives.TorusKnot = TorusKnot;
  36076. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  36077. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  36078. })(BABYLON || (BABYLON = {}));
  36079. var BABYLON;
  36080. (function (BABYLON) {
  36081. var GroundMesh = (function (_super) {
  36082. __extends(GroundMesh, _super);
  36083. function GroundMesh(name, scene) {
  36084. _super.call(this, name, scene);
  36085. this.generateOctree = false;
  36086. this._worldInverse = new BABYLON.Matrix();
  36087. }
  36088. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  36089. get: function () {
  36090. return Math.min(this._subdivisionsX, this._subdivisionsY);
  36091. },
  36092. enumerable: true,
  36093. configurable: true
  36094. });
  36095. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  36096. get: function () {
  36097. return this._subdivisionsX;
  36098. },
  36099. enumerable: true,
  36100. configurable: true
  36101. });
  36102. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  36103. get: function () {
  36104. return this._subdivisionsY;
  36105. },
  36106. enumerable: true,
  36107. configurable: true
  36108. });
  36109. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  36110. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  36111. this._subdivisionsX = chunksCount;
  36112. this._subdivisionsY = chunksCount;
  36113. this.subdivide(chunksCount);
  36114. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  36115. };
  36116. /**
  36117. * Returns a height (y) value in the Worl system :
  36118. * the ground altitude at the coordinates (x, z) expressed in the World system.
  36119. * Returns the ground y position if (x, z) are outside the ground surface.
  36120. * Not pertinent if the ground is rotated.
  36121. */
  36122. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  36123. // express x and y in the ground local system
  36124. x -= this.position.x;
  36125. z -= this.position.z;
  36126. x /= this.scaling.x;
  36127. z /= this.scaling.z;
  36128. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36129. return this.position.y;
  36130. }
  36131. if (!this._heightQuads || this._heightQuads.length == 0) {
  36132. this._initHeightQuads();
  36133. this._computeHeightQuads();
  36134. }
  36135. var facet = this._getFacetAt(x, z);
  36136. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  36137. // return y in the World system
  36138. return y * this.scaling.y + this.position.y;
  36139. };
  36140. /**
  36141. * Returns a normalized vector (Vector3) orthogonal to the ground
  36142. * at the ground coordinates (x, z) expressed in the World system.
  36143. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  36144. * Not pertinent if the ground is rotated.
  36145. */
  36146. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  36147. var normal = new BABYLON.Vector3(0, 1, 0);
  36148. this.getNormalAtCoordinatesToRef(x, z, normal);
  36149. return normal;
  36150. };
  36151. /**
  36152. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  36153. * at the ground coordinates (x, z) expressed in the World system.
  36154. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  36155. * Not pertinent if the ground is rotated.
  36156. */
  36157. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  36158. // express x and y in the ground local system
  36159. x -= this.position.x;
  36160. z -= this.position.z;
  36161. x /= this.scaling.x;
  36162. z /= this.scaling.z;
  36163. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36164. return;
  36165. }
  36166. if (!this._heightQuads || this._heightQuads.length == 0) {
  36167. this._initHeightQuads();
  36168. this._computeHeightQuads();
  36169. }
  36170. var facet = this._getFacetAt(x, z);
  36171. ref.x = facet.x;
  36172. ref.y = facet.y;
  36173. ref.z = facet.z;
  36174. };
  36175. /**
  36176. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  36177. * if the ground has been updated.
  36178. * This can be used in the render loop
  36179. */
  36180. GroundMesh.prototype.updateCoordinateHeights = function () {
  36181. if (!this._heightQuads || this._heightQuads.length == 0) {
  36182. this._initHeightQuads();
  36183. }
  36184. this._computeHeightQuads();
  36185. };
  36186. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  36187. GroundMesh.prototype._getFacetAt = function (x, z) {
  36188. // retrieve col and row from x, z coordinates in the ground local system
  36189. var subdivisionsX = this._subdivisionsX;
  36190. var subdivisionsY = this._subdivisionsY;
  36191. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  36192. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  36193. var quad = this._heightQuads[row * this._subdivisionsX + col];
  36194. var facet;
  36195. if (z < quad.slope.x * x + quad.slope.y) {
  36196. facet = quad.facet1;
  36197. }
  36198. else {
  36199. facet = quad.facet2;
  36200. }
  36201. return facet;
  36202. };
  36203. // Creates and populates the heightMap array with "facet" elements :
  36204. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  36205. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36206. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36207. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36208. GroundMesh.prototype._initHeightQuads = function () {
  36209. var subdivisionsX = this._subdivisionsX;
  36210. var subdivisionsY = this._subdivisionsY;
  36211. this._heightQuads = new Array();
  36212. for (var row = 0; row < subdivisionsY; row++) {
  36213. for (var col = 0; col < subdivisionsX; col++) {
  36214. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  36215. this._heightQuads[row * subdivisionsX + col] = quad;
  36216. }
  36217. }
  36218. };
  36219. // Compute each quad element values and update the the heightMap array :
  36220. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36221. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36222. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36223. GroundMesh.prototype._computeHeightQuads = function () {
  36224. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36225. var v1 = BABYLON.Tmp.Vector3[3];
  36226. var v2 = BABYLON.Tmp.Vector3[2];
  36227. var v3 = BABYLON.Tmp.Vector3[1];
  36228. var v4 = BABYLON.Tmp.Vector3[0];
  36229. var v1v2 = BABYLON.Tmp.Vector3[4];
  36230. var v1v3 = BABYLON.Tmp.Vector3[5];
  36231. var v1v4 = BABYLON.Tmp.Vector3[6];
  36232. var norm1 = BABYLON.Tmp.Vector3[7];
  36233. var norm2 = BABYLON.Tmp.Vector3[8];
  36234. var i = 0;
  36235. var j = 0;
  36236. var k = 0;
  36237. var cd = 0; // 2D slope coefficient : z = cd * x + h
  36238. var h = 0;
  36239. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  36240. var d2 = 0;
  36241. var subdivisionsX = this._subdivisionsX;
  36242. var subdivisionsY = this._subdivisionsY;
  36243. for (var row = 0; row < subdivisionsY; row++) {
  36244. for (var col = 0; col < subdivisionsX; col++) {
  36245. i = col * 3;
  36246. j = row * (subdivisionsX + 1) * 3;
  36247. k = (row + 1) * (subdivisionsX + 1) * 3;
  36248. v1.x = positions[j + i];
  36249. v1.y = positions[j + i + 1];
  36250. v1.z = positions[j + i + 2];
  36251. v2.x = positions[j + i + 3];
  36252. v2.y = positions[j + i + 4];
  36253. v2.z = positions[j + i + 5];
  36254. v3.x = positions[k + i];
  36255. v3.y = positions[k + i + 1];
  36256. v3.z = positions[k + i + 2];
  36257. v4.x = positions[k + i + 3];
  36258. v4.y = positions[k + i + 4];
  36259. v4.z = positions[k + i + 5];
  36260. // 2D slope V1V4
  36261. cd = (v4.z - v1.z) / (v4.x - v1.x);
  36262. h = v1.z - cd * v1.x; // v1 belongs to the slope
  36263. // facet equations :
  36264. // we compute each facet normal vector
  36265. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  36266. // we compute the value d by applying the equation to v1 which belongs to the plane
  36267. // then we store the facet equation in a Vector4
  36268. v2.subtractToRef(v1, v1v2);
  36269. v3.subtractToRef(v1, v1v3);
  36270. v4.subtractToRef(v1, v1v4);
  36271. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  36272. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  36273. norm1.normalize();
  36274. norm2.normalize();
  36275. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  36276. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  36277. var quad = this._heightQuads[row * subdivisionsX + col];
  36278. quad.slope.copyFromFloats(cd, h);
  36279. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  36280. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  36281. }
  36282. }
  36283. };
  36284. return GroundMesh;
  36285. }(BABYLON.Mesh));
  36286. BABYLON.GroundMesh = GroundMesh;
  36287. })(BABYLON || (BABYLON = {}));
  36288. var BABYLON;
  36289. (function (BABYLON) {
  36290. var LinesMesh = (function (_super) {
  36291. __extends(LinesMesh, _super);
  36292. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  36293. if (parent === void 0) { parent = null; }
  36294. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  36295. this.color = new BABYLON.Color3(1, 1, 1);
  36296. this.alpha = 1;
  36297. this._positionBuffer = {};
  36298. if (source) {
  36299. this.color = source.color.clone();
  36300. this.alpha = source.alpha;
  36301. }
  36302. this._intersectionThreshold = 0.1;
  36303. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  36304. attributes: [BABYLON.VertexBuffer.PositionKind],
  36305. uniforms: ["worldViewProjection", "color"],
  36306. needAlphaBlending: true
  36307. });
  36308. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  36309. }
  36310. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  36311. /**
  36312. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  36313. * This margin is expressed in world space coordinates, so its value may vary.
  36314. * Default value is 0.1
  36315. * @returns the intersection Threshold value.
  36316. */
  36317. get: function () {
  36318. return this._intersectionThreshold;
  36319. },
  36320. /**
  36321. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  36322. * This margin is expressed in world space coordinates, so its value may vary.
  36323. * @param value the new threshold to apply
  36324. */
  36325. set: function (value) {
  36326. if (this._intersectionThreshold === value) {
  36327. return;
  36328. }
  36329. this._intersectionThreshold = value;
  36330. if (this.geometry) {
  36331. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  36332. }
  36333. },
  36334. enumerable: true,
  36335. configurable: true
  36336. });
  36337. Object.defineProperty(LinesMesh.prototype, "material", {
  36338. get: function () {
  36339. return this._colorShader;
  36340. },
  36341. enumerable: true,
  36342. configurable: true
  36343. });
  36344. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  36345. get: function () {
  36346. return false;
  36347. },
  36348. enumerable: true,
  36349. configurable: true
  36350. });
  36351. LinesMesh.prototype.createInstance = function (name) {
  36352. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  36353. return null;
  36354. };
  36355. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  36356. var engine = this.getScene().getEngine();
  36357. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  36358. // VBOs
  36359. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  36360. // Color
  36361. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  36362. };
  36363. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  36364. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  36365. return;
  36366. }
  36367. var engine = this.getScene().getEngine();
  36368. // Draw order
  36369. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  36370. };
  36371. LinesMesh.prototype.dispose = function (doNotRecurse) {
  36372. this._colorShader.dispose();
  36373. _super.prototype.dispose.call(this, doNotRecurse);
  36374. };
  36375. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  36376. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  36377. };
  36378. return LinesMesh;
  36379. }(BABYLON.Mesh));
  36380. BABYLON.LinesMesh = LinesMesh;
  36381. })(BABYLON || (BABYLON = {}));
  36382. var BABYLON;
  36383. (function (BABYLON) {
  36384. var DefaultLoadingScreen = (function () {
  36385. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  36386. var _this = this;
  36387. if (_loadingText === void 0) { _loadingText = ""; }
  36388. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  36389. this._renderingCanvas = _renderingCanvas;
  36390. this._loadingText = _loadingText;
  36391. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  36392. // Resize
  36393. this._resizeLoadingUI = function () {
  36394. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  36395. _this._loadingDiv.style.position = "absolute";
  36396. _this._loadingDiv.style.left = canvasRect.left + "px";
  36397. _this._loadingDiv.style.top = canvasRect.top + "px";
  36398. _this._loadingDiv.style.width = canvasRect.width + "px";
  36399. _this._loadingDiv.style.height = canvasRect.height + "px";
  36400. };
  36401. }
  36402. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  36403. var _this = this;
  36404. if (this._loadingDiv) {
  36405. // Do not add a loading screen if there is already one
  36406. return;
  36407. }
  36408. this._loadingDiv = document.createElement("div");
  36409. this._loadingDiv.id = "babylonjsLoadingDiv";
  36410. this._loadingDiv.style.opacity = "0";
  36411. this._loadingDiv.style.transition = "opacity 1.5s ease";
  36412. // Loading text
  36413. this._loadingTextDiv = document.createElement("div");
  36414. this._loadingTextDiv.style.position = "absolute";
  36415. this._loadingTextDiv.style.left = "0";
  36416. this._loadingTextDiv.style.top = "50%";
  36417. this._loadingTextDiv.style.marginTop = "80px";
  36418. this._loadingTextDiv.style.width = "100%";
  36419. this._loadingTextDiv.style.height = "20px";
  36420. this._loadingTextDiv.style.fontFamily = "Arial";
  36421. this._loadingTextDiv.style.fontSize = "14px";
  36422. this._loadingTextDiv.style.color = "white";
  36423. this._loadingTextDiv.style.textAlign = "center";
  36424. this._loadingTextDiv.innerHTML = "Loading";
  36425. this._loadingDiv.appendChild(this._loadingTextDiv);
  36426. //set the predefined text
  36427. this._loadingTextDiv.innerHTML = this._loadingText;
  36428. // Loading img
  36429. var imgBack = new Image();
  36430. 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==";
  36431. imgBack.style.position = "absolute";
  36432. imgBack.style.left = "50%";
  36433. imgBack.style.top = "50%";
  36434. imgBack.style.marginLeft = "-50px";
  36435. imgBack.style.marginTop = "-50px";
  36436. imgBack.style.transition = "transform 1.0s ease";
  36437. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  36438. var deg = 360;
  36439. var onTransitionEnd = function () {
  36440. deg += 360;
  36441. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  36442. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  36443. };
  36444. imgBack.addEventListener("transitionend", onTransitionEnd);
  36445. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  36446. this._loadingDiv.appendChild(imgBack);
  36447. // front image
  36448. var imgFront = new Image();
  36449. 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=";
  36450. imgFront.style.position = "absolute";
  36451. imgFront.style.left = "50%";
  36452. imgFront.style.top = "50%";
  36453. imgFront.style.marginLeft = "-50px";
  36454. imgFront.style.marginTop = "-50px";
  36455. this._loadingDiv.appendChild(imgFront);
  36456. this._resizeLoadingUI();
  36457. window.addEventListener("resize", this._resizeLoadingUI);
  36458. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  36459. document.body.appendChild(this._loadingDiv);
  36460. setTimeout(function () {
  36461. _this._loadingDiv.style.opacity = "1";
  36462. imgBack.style.transform = "rotateZ(360deg)";
  36463. imgBack.style.webkitTransform = "rotateZ(360deg)";
  36464. }, 0);
  36465. };
  36466. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  36467. var _this = this;
  36468. if (!this._loadingDiv) {
  36469. return;
  36470. }
  36471. var onTransitionEnd = function () {
  36472. if (!_this._loadingDiv) {
  36473. return;
  36474. }
  36475. document.body.removeChild(_this._loadingDiv);
  36476. window.removeEventListener("resize", _this._resizeLoadingUI);
  36477. _this._loadingDiv = null;
  36478. };
  36479. this._loadingDiv.style.opacity = "0";
  36480. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  36481. };
  36482. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  36483. set: function (text) {
  36484. this._loadingText = text;
  36485. if (this._loadingTextDiv) {
  36486. this._loadingTextDiv.innerHTML = this._loadingText;
  36487. }
  36488. },
  36489. enumerable: true,
  36490. configurable: true
  36491. });
  36492. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  36493. get: function () {
  36494. return this._loadingDivBackgroundColor;
  36495. },
  36496. set: function (color) {
  36497. this._loadingDivBackgroundColor = color;
  36498. if (!this._loadingDiv) {
  36499. return;
  36500. }
  36501. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  36502. },
  36503. enumerable: true,
  36504. configurable: true
  36505. });
  36506. return DefaultLoadingScreen;
  36507. }());
  36508. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  36509. })(BABYLON || (BABYLON = {}));
  36510. var BABYLON;
  36511. (function (BABYLON) {
  36512. var AudioEngine = (function () {
  36513. function AudioEngine() {
  36514. this._audioContext = null;
  36515. this._audioContextInitialized = false;
  36516. this.canUseWebAudio = false;
  36517. this.WarnedWebAudioUnsupported = false;
  36518. this.unlocked = false;
  36519. this.isMP3supported = false;
  36520. this.isOGGsupported = false;
  36521. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  36522. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  36523. this.canUseWebAudio = true;
  36524. }
  36525. var audioElem = document.createElement('audio');
  36526. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  36527. this.isMP3supported = true;
  36528. }
  36529. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  36530. this.isOGGsupported = true;
  36531. }
  36532. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  36533. this._unlockiOSaudio();
  36534. }
  36535. else {
  36536. this.unlocked = true;
  36537. }
  36538. }
  36539. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  36540. get: function () {
  36541. if (!this._audioContextInitialized) {
  36542. this._initializeAudioContext();
  36543. }
  36544. return this._audioContext;
  36545. },
  36546. enumerable: true,
  36547. configurable: true
  36548. });
  36549. AudioEngine.prototype._unlockiOSaudio = function () {
  36550. var _this = this;
  36551. var unlockaudio = function () {
  36552. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  36553. var source = _this.audioContext.createBufferSource();
  36554. source.buffer = buffer;
  36555. source.connect(_this.audioContext.destination);
  36556. source.start(0);
  36557. setTimeout(function () {
  36558. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  36559. _this.unlocked = true;
  36560. window.removeEventListener('touchend', unlockaudio, false);
  36561. if (_this.onAudioUnlocked) {
  36562. _this.onAudioUnlocked();
  36563. }
  36564. }
  36565. }, 0);
  36566. };
  36567. window.addEventListener('touchend', unlockaudio, false);
  36568. };
  36569. AudioEngine.prototype._initializeAudioContext = function () {
  36570. try {
  36571. if (this.canUseWebAudio) {
  36572. this._audioContext = new AudioContext();
  36573. // create a global volume gain node
  36574. this.masterGain = this._audioContext.createGain();
  36575. this.masterGain.gain.value = 1;
  36576. this.masterGain.connect(this._audioContext.destination);
  36577. this._audioContextInitialized = true;
  36578. }
  36579. }
  36580. catch (e) {
  36581. this.canUseWebAudio = false;
  36582. BABYLON.Tools.Error("Web Audio: " + e.message);
  36583. }
  36584. };
  36585. AudioEngine.prototype.dispose = function () {
  36586. if (this.canUseWebAudio && this._audioContextInitialized) {
  36587. if (this._connectedAnalyser) {
  36588. this._connectedAnalyser.stopDebugCanvas();
  36589. this._connectedAnalyser.dispose();
  36590. this.masterGain.disconnect();
  36591. this.masterGain.connect(this._audioContext.destination);
  36592. this._connectedAnalyser = null;
  36593. }
  36594. this.masterGain.gain.value = 1;
  36595. }
  36596. this.WarnedWebAudioUnsupported = false;
  36597. };
  36598. AudioEngine.prototype.getGlobalVolume = function () {
  36599. if (this.canUseWebAudio && this._audioContextInitialized) {
  36600. return this.masterGain.gain.value;
  36601. }
  36602. else {
  36603. return -1;
  36604. }
  36605. };
  36606. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  36607. if (this.canUseWebAudio && this._audioContextInitialized) {
  36608. this.masterGain.gain.value = newVolume;
  36609. }
  36610. };
  36611. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  36612. if (this._connectedAnalyser) {
  36613. this._connectedAnalyser.stopDebugCanvas();
  36614. }
  36615. if (this.canUseWebAudio && this._audioContextInitialized) {
  36616. this._connectedAnalyser = analyser;
  36617. this.masterGain.disconnect();
  36618. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  36619. }
  36620. };
  36621. return AudioEngine;
  36622. }());
  36623. BABYLON.AudioEngine = AudioEngine;
  36624. })(BABYLON || (BABYLON = {}));
  36625. var BABYLON;
  36626. (function (BABYLON) {
  36627. var Sound = (function () {
  36628. /**
  36629. * Create a sound and attach it to a scene
  36630. * @param name Name of your sound
  36631. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  36632. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  36633. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  36634. */
  36635. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  36636. var _this = this;
  36637. this.autoplay = false;
  36638. this.loop = false;
  36639. this.useCustomAttenuation = false;
  36640. this.spatialSound = false;
  36641. this.refDistance = 1;
  36642. this.rolloffFactor = 1;
  36643. this.maxDistance = 100;
  36644. this.distanceModel = "linear";
  36645. this._panningModel = "equalpower";
  36646. this._playbackRate = 1;
  36647. this._streaming = false;
  36648. this._startTime = 0;
  36649. this._startOffset = 0;
  36650. this._position = BABYLON.Vector3.Zero();
  36651. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  36652. this._volume = 1;
  36653. this._isLoaded = false;
  36654. this._isReadyToPlay = false;
  36655. this.isPlaying = false;
  36656. this.isPaused = false;
  36657. this._isDirectional = false;
  36658. // Used if you'd like to create a directional sound.
  36659. // If not set, the sound will be omnidirectional
  36660. this._coneInnerAngle = 360;
  36661. this._coneOuterAngle = 360;
  36662. this._coneOuterGain = 0;
  36663. this._isOutputConnected = false;
  36664. this._urlType = "Unknown";
  36665. this.name = name;
  36666. this._scene = scene;
  36667. this._readyToPlayCallback = readyToPlayCallback;
  36668. // Default custom attenuation function is a linear attenuation
  36669. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  36670. if (currentDistance < maxDistance) {
  36671. return currentVolume * (1 - currentDistance / maxDistance);
  36672. }
  36673. else {
  36674. return 0;
  36675. }
  36676. };
  36677. if (options) {
  36678. this.autoplay = options.autoplay || false;
  36679. this.loop = options.loop || false;
  36680. // if volume === 0, we need another way to check this option
  36681. if (options.volume !== undefined) {
  36682. this._volume = options.volume;
  36683. }
  36684. this.spatialSound = options.spatialSound || false;
  36685. this.maxDistance = options.maxDistance || 100;
  36686. this.useCustomAttenuation = options.useCustomAttenuation || false;
  36687. this.rolloffFactor = options.rolloffFactor || 1;
  36688. this.refDistance = options.refDistance || 1;
  36689. this.distanceModel = options.distanceModel || "linear";
  36690. this._playbackRate = options.playbackRate || 1;
  36691. this._streaming = options.streaming || false;
  36692. }
  36693. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36694. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  36695. this._soundGain.gain.value = this._volume;
  36696. this._inputAudioNode = this._soundGain;
  36697. this._ouputAudioNode = this._soundGain;
  36698. if (this.spatialSound) {
  36699. this._createSpatialParameters();
  36700. }
  36701. this._scene.mainSoundTrack.AddSound(this);
  36702. var validParameter = true;
  36703. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  36704. if (urlOrArrayBuffer) {
  36705. if (typeof (urlOrArrayBuffer) === "string")
  36706. this._urlType = "String";
  36707. if (Array.isArray(urlOrArrayBuffer))
  36708. this._urlType = "Array";
  36709. if (urlOrArrayBuffer instanceof ArrayBuffer)
  36710. this._urlType = "ArrayBuffer";
  36711. var urls = [];
  36712. var codecSupportedFound = false;
  36713. switch (this._urlType) {
  36714. case "ArrayBuffer":
  36715. if (urlOrArrayBuffer.byteLength > 0) {
  36716. codecSupportedFound = true;
  36717. this._soundLoaded(urlOrArrayBuffer);
  36718. }
  36719. break;
  36720. case "String":
  36721. urls.push(urlOrArrayBuffer);
  36722. case "Array":
  36723. if (urls.length === 0)
  36724. urls = urlOrArrayBuffer;
  36725. // If we found a supported format, we load it immediately and stop the loop
  36726. for (var i = 0; i < urls.length; i++) {
  36727. var url = urls[i];
  36728. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  36729. codecSupportedFound = true;
  36730. }
  36731. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  36732. codecSupportedFound = true;
  36733. }
  36734. if (url.indexOf(".wav", url.length - 4) !== -1) {
  36735. codecSupportedFound = true;
  36736. }
  36737. if (codecSupportedFound) {
  36738. // Loading sound using XHR2
  36739. if (!this._streaming) {
  36740. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  36741. }
  36742. else {
  36743. this._htmlAudioElement = new Audio(url);
  36744. this._htmlAudioElement.controls = false;
  36745. this._htmlAudioElement.loop = this.loop;
  36746. this._htmlAudioElement.crossOrigin = "anonymous";
  36747. this._htmlAudioElement.preload = "auto";
  36748. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  36749. _this._isReadyToPlay = true;
  36750. if (_this.autoplay) {
  36751. _this.play();
  36752. }
  36753. if (_this._readyToPlayCallback) {
  36754. _this._readyToPlayCallback();
  36755. }
  36756. });
  36757. document.body.appendChild(this._htmlAudioElement);
  36758. }
  36759. break;
  36760. }
  36761. }
  36762. break;
  36763. default:
  36764. validParameter = false;
  36765. break;
  36766. }
  36767. if (!validParameter) {
  36768. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  36769. }
  36770. else {
  36771. if (!codecSupportedFound) {
  36772. this._isReadyToPlay = true;
  36773. // Simulating a ready to play event to avoid breaking code path
  36774. if (this._readyToPlayCallback) {
  36775. window.setTimeout(function () {
  36776. _this._readyToPlayCallback();
  36777. }, 1000);
  36778. }
  36779. }
  36780. }
  36781. }
  36782. }
  36783. else {
  36784. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  36785. this._scene.mainSoundTrack.AddSound(this);
  36786. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  36787. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  36788. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  36789. }
  36790. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  36791. if (this._readyToPlayCallback) {
  36792. window.setTimeout(function () {
  36793. _this._readyToPlayCallback();
  36794. }, 1000);
  36795. }
  36796. }
  36797. }
  36798. Sound.prototype.dispose = function () {
  36799. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  36800. if (this.isPlaying) {
  36801. this.stop();
  36802. }
  36803. this._isReadyToPlay = false;
  36804. if (this.soundTrackId === -1) {
  36805. this._scene.mainSoundTrack.RemoveSound(this);
  36806. }
  36807. else {
  36808. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  36809. }
  36810. if (this._soundGain) {
  36811. this._soundGain.disconnect();
  36812. this._soundGain = null;
  36813. }
  36814. if (this._soundPanner) {
  36815. this._soundPanner.disconnect();
  36816. this._soundPanner = null;
  36817. }
  36818. if (this._soundSource) {
  36819. this._soundSource.disconnect();
  36820. this._soundSource = null;
  36821. }
  36822. this._audioBuffer = null;
  36823. if (this._htmlAudioElement) {
  36824. this._htmlAudioElement.pause();
  36825. this._htmlAudioElement.src = "";
  36826. document.body.removeChild(this._htmlAudioElement);
  36827. }
  36828. if (this._connectedMesh) {
  36829. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36830. this._connectedMesh = null;
  36831. }
  36832. }
  36833. };
  36834. Sound.prototype._soundLoaded = function (audioData) {
  36835. var _this = this;
  36836. this._isLoaded = true;
  36837. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  36838. _this._audioBuffer = buffer;
  36839. _this._isReadyToPlay = true;
  36840. if (_this.autoplay) {
  36841. _this.play();
  36842. }
  36843. if (_this._readyToPlayCallback) {
  36844. _this._readyToPlayCallback();
  36845. }
  36846. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  36847. };
  36848. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  36849. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36850. this._audioBuffer = audioBuffer;
  36851. this._isReadyToPlay = true;
  36852. }
  36853. };
  36854. Sound.prototype.updateOptions = function (options) {
  36855. if (options) {
  36856. this.loop = options.loop || this.loop;
  36857. this.maxDistance = options.maxDistance || this.maxDistance;
  36858. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  36859. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  36860. this.refDistance = options.refDistance || this.refDistance;
  36861. this.distanceModel = options.distanceModel || this.distanceModel;
  36862. this._playbackRate = options.playbackRate || this._playbackRate;
  36863. this._updateSpatialParameters();
  36864. if (this.isPlaying) {
  36865. if (this._streaming) {
  36866. this._htmlAudioElement.playbackRate = this._playbackRate;
  36867. }
  36868. else {
  36869. this._soundSource.playbackRate.value = this._playbackRate;
  36870. }
  36871. }
  36872. }
  36873. };
  36874. Sound.prototype._createSpatialParameters = function () {
  36875. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36876. if (this._scene.headphone) {
  36877. this._panningModel = "HRTF";
  36878. }
  36879. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  36880. this._updateSpatialParameters();
  36881. this._soundPanner.connect(this._ouputAudioNode);
  36882. this._inputAudioNode = this._soundPanner;
  36883. }
  36884. };
  36885. Sound.prototype._updateSpatialParameters = function () {
  36886. if (this.spatialSound) {
  36887. if (this.useCustomAttenuation) {
  36888. // Tricks to disable in a way embedded Web Audio attenuation
  36889. this._soundPanner.distanceModel = "linear";
  36890. this._soundPanner.maxDistance = Number.MAX_VALUE;
  36891. this._soundPanner.refDistance = 1;
  36892. this._soundPanner.rolloffFactor = 1;
  36893. this._soundPanner.panningModel = this._panningModel;
  36894. }
  36895. else {
  36896. this._soundPanner.distanceModel = this.distanceModel;
  36897. this._soundPanner.maxDistance = this.maxDistance;
  36898. this._soundPanner.refDistance = this.refDistance;
  36899. this._soundPanner.rolloffFactor = this.rolloffFactor;
  36900. this._soundPanner.panningModel = this._panningModel;
  36901. }
  36902. }
  36903. };
  36904. Sound.prototype.switchPanningModelToHRTF = function () {
  36905. this._panningModel = "HRTF";
  36906. this._switchPanningModel();
  36907. };
  36908. Sound.prototype.switchPanningModelToEqualPower = function () {
  36909. this._panningModel = "equalpower";
  36910. this._switchPanningModel();
  36911. };
  36912. Sound.prototype._switchPanningModel = function () {
  36913. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36914. this._soundPanner.panningModel = this._panningModel;
  36915. }
  36916. };
  36917. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  36918. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36919. if (this._isOutputConnected) {
  36920. this._ouputAudioNode.disconnect();
  36921. }
  36922. this._ouputAudioNode.connect(soundTrackAudioNode);
  36923. this._isOutputConnected = true;
  36924. }
  36925. };
  36926. /**
  36927. * Transform this sound into a directional source
  36928. * @param coneInnerAngle Size of the inner cone in degree
  36929. * @param coneOuterAngle Size of the outer cone in degree
  36930. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  36931. */
  36932. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  36933. if (coneOuterAngle < coneInnerAngle) {
  36934. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  36935. return;
  36936. }
  36937. this._coneInnerAngle = coneInnerAngle;
  36938. this._coneOuterAngle = coneOuterAngle;
  36939. this._coneOuterGain = coneOuterGain;
  36940. this._isDirectional = true;
  36941. if (this.isPlaying && this.loop) {
  36942. this.stop();
  36943. this.play();
  36944. }
  36945. };
  36946. Sound.prototype.setPosition = function (newPosition) {
  36947. this._position = newPosition;
  36948. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36949. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36950. }
  36951. };
  36952. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  36953. this._localDirection = newLocalDirection;
  36954. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  36955. this._updateDirection();
  36956. }
  36957. };
  36958. Sound.prototype._updateDirection = function () {
  36959. var mat = this._connectedMesh.getWorldMatrix();
  36960. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  36961. direction.normalize();
  36962. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  36963. };
  36964. Sound.prototype.updateDistanceFromListener = function () {
  36965. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  36966. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  36967. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  36968. }
  36969. };
  36970. Sound.prototype.setAttenuationFunction = function (callback) {
  36971. this._customAttenuationFunction = callback;
  36972. };
  36973. /**
  36974. * Play the sound
  36975. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  36976. * @param offset (optional) Start the sound setting it at a specific time
  36977. */
  36978. Sound.prototype.play = function (time, offset) {
  36979. var _this = this;
  36980. if (this._isReadyToPlay && this._scene.audioEnabled) {
  36981. try {
  36982. if (this._startOffset < 0) {
  36983. time = -this._startOffset;
  36984. this._startOffset = 0;
  36985. }
  36986. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36987. if (!this._soundSource || !this._streamingSource) {
  36988. if (this.spatialSound) {
  36989. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36990. if (this._isDirectional) {
  36991. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  36992. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  36993. this._soundPanner.coneOuterGain = this._coneOuterGain;
  36994. if (this._connectedMesh) {
  36995. this._updateDirection();
  36996. }
  36997. else {
  36998. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  36999. }
  37000. }
  37001. }
  37002. }
  37003. if (this._streaming) {
  37004. if (!this._streamingSource) {
  37005. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  37006. this._htmlAudioElement.onended = function () { _this._onended(); };
  37007. this._htmlAudioElement.playbackRate = this._playbackRate;
  37008. }
  37009. this._streamingSource.disconnect();
  37010. this._streamingSource.connect(this._inputAudioNode);
  37011. this._htmlAudioElement.play();
  37012. }
  37013. else {
  37014. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  37015. this._soundSource.buffer = this._audioBuffer;
  37016. this._soundSource.connect(this._inputAudioNode);
  37017. this._soundSource.loop = this.loop;
  37018. this._soundSource.playbackRate.value = this._playbackRate;
  37019. this._soundSource.onended = function () { _this._onended(); };
  37020. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  37021. }
  37022. this._startTime = startTime;
  37023. this.isPlaying = true;
  37024. this.isPaused = false;
  37025. }
  37026. catch (ex) {
  37027. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  37028. }
  37029. }
  37030. };
  37031. Sound.prototype._onended = function () {
  37032. this.isPlaying = false;
  37033. if (this.onended) {
  37034. this.onended();
  37035. }
  37036. };
  37037. /**
  37038. * Stop the sound
  37039. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  37040. */
  37041. Sound.prototype.stop = function (time) {
  37042. if (this.isPlaying) {
  37043. if (this._streaming) {
  37044. this._htmlAudioElement.pause();
  37045. // Test needed for Firefox or it will generate an Invalid State Error
  37046. if (this._htmlAudioElement.currentTime > 0) {
  37047. this._htmlAudioElement.currentTime = 0;
  37048. }
  37049. }
  37050. else {
  37051. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  37052. this._soundSource.stop(stopTime);
  37053. this._soundSource.onended = null;
  37054. if (!this.isPaused) {
  37055. this._startOffset = 0;
  37056. }
  37057. }
  37058. this.isPlaying = false;
  37059. }
  37060. };
  37061. Sound.prototype.pause = function () {
  37062. if (this.isPlaying) {
  37063. this.isPaused = true;
  37064. if (this._streaming) {
  37065. this._htmlAudioElement.pause();
  37066. }
  37067. else {
  37068. this.stop(0);
  37069. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  37070. }
  37071. }
  37072. };
  37073. Sound.prototype.setVolume = function (newVolume, time) {
  37074. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37075. if (time) {
  37076. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  37077. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  37078. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  37079. }
  37080. else {
  37081. this._soundGain.gain.value = newVolume;
  37082. }
  37083. }
  37084. this._volume = newVolume;
  37085. };
  37086. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  37087. this._playbackRate = newPlaybackRate;
  37088. if (this.isPlaying) {
  37089. if (this._streaming) {
  37090. this._htmlAudioElement.playbackRate = this._playbackRate;
  37091. }
  37092. else {
  37093. this._soundSource.playbackRate.value = this._playbackRate;
  37094. }
  37095. }
  37096. };
  37097. Sound.prototype.getVolume = function () {
  37098. return this._volume;
  37099. };
  37100. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  37101. var _this = this;
  37102. if (this._connectedMesh) {
  37103. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37104. this._registerFunc = null;
  37105. }
  37106. this._connectedMesh = meshToConnectTo;
  37107. if (!this.spatialSound) {
  37108. this.spatialSound = true;
  37109. this._createSpatialParameters();
  37110. if (this.isPlaying && this.loop) {
  37111. this.stop();
  37112. this.play();
  37113. }
  37114. }
  37115. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  37116. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  37117. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  37118. };
  37119. Sound.prototype.detachFromMesh = function () {
  37120. if (this._connectedMesh) {
  37121. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37122. this._registerFunc = null;
  37123. this._connectedMesh = null;
  37124. }
  37125. };
  37126. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  37127. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  37128. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  37129. this._updateDirection();
  37130. }
  37131. };
  37132. Sound.prototype.clone = function () {
  37133. var _this = this;
  37134. if (!this._streaming) {
  37135. var setBufferAndRun = function () {
  37136. if (_this._isReadyToPlay) {
  37137. clonedSound._audioBuffer = _this.getAudioBuffer();
  37138. clonedSound._isReadyToPlay = true;
  37139. if (clonedSound.autoplay) {
  37140. clonedSound.play();
  37141. }
  37142. }
  37143. else {
  37144. window.setTimeout(setBufferAndRun, 300);
  37145. }
  37146. };
  37147. var currentOptions = {
  37148. autoplay: this.autoplay, loop: this.loop,
  37149. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  37150. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  37151. refDistance: this.refDistance, distanceModel: this.distanceModel
  37152. };
  37153. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  37154. if (this.useCustomAttenuation) {
  37155. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  37156. }
  37157. clonedSound.setPosition(this._position);
  37158. clonedSound.setPlaybackRate(this._playbackRate);
  37159. setBufferAndRun();
  37160. return clonedSound;
  37161. }
  37162. else {
  37163. return null;
  37164. }
  37165. };
  37166. Sound.prototype.getAudioBuffer = function () {
  37167. return this._audioBuffer;
  37168. };
  37169. Sound.prototype.serialize = function () {
  37170. var serializationObject = {
  37171. name: this.name,
  37172. url: this.name,
  37173. autoplay: this.autoplay,
  37174. loop: this.loop,
  37175. volume: this._volume,
  37176. spatialSound: this.spatialSound,
  37177. maxDistance: this.maxDistance,
  37178. rolloffFactor: this.rolloffFactor,
  37179. refDistance: this.refDistance,
  37180. distanceModel: this.distanceModel,
  37181. playbackRate: this._playbackRate,
  37182. panningModel: this._panningModel,
  37183. soundTrackId: this.soundTrackId
  37184. };
  37185. if (this.spatialSound) {
  37186. if (this._connectedMesh)
  37187. serializationObject.connectedMeshId = this._connectedMesh.id;
  37188. serializationObject.position = this._position.asArray();
  37189. serializationObject.refDistance = this.refDistance;
  37190. serializationObject.distanceModel = this.distanceModel;
  37191. serializationObject.isDirectional = this._isDirectional;
  37192. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  37193. serializationObject.coneInnerAngle = this._coneInnerAngle;
  37194. serializationObject.coneOuterAngle = this._coneOuterAngle;
  37195. serializationObject.coneOuterGain = this._coneOuterGain;
  37196. }
  37197. return serializationObject;
  37198. };
  37199. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  37200. var soundName = parsedSound.name;
  37201. var soundUrl;
  37202. if (parsedSound.url) {
  37203. soundUrl = rootUrl + parsedSound.url;
  37204. }
  37205. else {
  37206. soundUrl = rootUrl + soundName;
  37207. }
  37208. var options = {
  37209. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  37210. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  37211. rolloffFactor: parsedSound.rolloffFactor,
  37212. refDistance: parsedSound.refDistance,
  37213. distanceModel: parsedSound.distanceModel,
  37214. playbackRate: parsedSound.playbackRate
  37215. };
  37216. var newSound;
  37217. if (!sourceSound) {
  37218. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  37219. scene._addPendingData(newSound);
  37220. }
  37221. else {
  37222. var setBufferAndRun = function () {
  37223. if (sourceSound._isReadyToPlay) {
  37224. newSound._audioBuffer = sourceSound.getAudioBuffer();
  37225. newSound._isReadyToPlay = true;
  37226. if (newSound.autoplay) {
  37227. newSound.play();
  37228. }
  37229. }
  37230. else {
  37231. window.setTimeout(setBufferAndRun, 300);
  37232. }
  37233. };
  37234. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  37235. setBufferAndRun();
  37236. }
  37237. if (parsedSound.position) {
  37238. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  37239. newSound.setPosition(soundPosition);
  37240. }
  37241. if (parsedSound.isDirectional) {
  37242. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  37243. if (parsedSound.localDirectionToMesh) {
  37244. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  37245. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  37246. }
  37247. }
  37248. if (parsedSound.connectedMeshId) {
  37249. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  37250. if (connectedMesh) {
  37251. newSound.attachToMesh(connectedMesh);
  37252. }
  37253. }
  37254. return newSound;
  37255. };
  37256. return Sound;
  37257. }());
  37258. BABYLON.Sound = Sound;
  37259. })(BABYLON || (BABYLON = {}));
  37260. var BABYLON;
  37261. (function (BABYLON) {
  37262. var SoundTrack = (function () {
  37263. function SoundTrack(scene, options) {
  37264. this.id = -1;
  37265. this._isMainTrack = false;
  37266. this._isInitialized = false;
  37267. this._scene = scene;
  37268. this.soundCollection = new Array();
  37269. this._options = options;
  37270. if (!this._isMainTrack) {
  37271. this._scene.soundTracks.push(this);
  37272. this.id = this._scene.soundTracks.length - 1;
  37273. }
  37274. }
  37275. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  37276. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37277. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  37278. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  37279. if (this._options) {
  37280. if (this._options.volume) {
  37281. this._outputAudioNode.gain.value = this._options.volume;
  37282. }
  37283. if (this._options.mainTrack) {
  37284. this._isMainTrack = this._options.mainTrack;
  37285. }
  37286. }
  37287. this._isInitialized = true;
  37288. }
  37289. };
  37290. SoundTrack.prototype.dispose = function () {
  37291. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37292. if (this._connectedAnalyser) {
  37293. this._connectedAnalyser.stopDebugCanvas();
  37294. }
  37295. while (this.soundCollection.length) {
  37296. this.soundCollection[0].dispose();
  37297. }
  37298. if (this._outputAudioNode) {
  37299. this._outputAudioNode.disconnect();
  37300. }
  37301. this._outputAudioNode = null;
  37302. }
  37303. };
  37304. SoundTrack.prototype.AddSound = function (sound) {
  37305. if (!this._isInitialized) {
  37306. this._initializeSoundTrackAudioGraph();
  37307. }
  37308. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37309. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  37310. }
  37311. if (sound.soundTrackId) {
  37312. if (sound.soundTrackId === -1) {
  37313. this._scene.mainSoundTrack.RemoveSound(sound);
  37314. }
  37315. else {
  37316. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  37317. }
  37318. }
  37319. this.soundCollection.push(sound);
  37320. sound.soundTrackId = this.id;
  37321. };
  37322. SoundTrack.prototype.RemoveSound = function (sound) {
  37323. var index = this.soundCollection.indexOf(sound);
  37324. if (index !== -1) {
  37325. this.soundCollection.splice(index, 1);
  37326. }
  37327. };
  37328. SoundTrack.prototype.setVolume = function (newVolume) {
  37329. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37330. this._outputAudioNode.gain.value = newVolume;
  37331. }
  37332. };
  37333. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  37334. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37335. for (var i = 0; i < this.soundCollection.length; i++) {
  37336. this.soundCollection[i].switchPanningModelToHRTF();
  37337. }
  37338. }
  37339. };
  37340. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  37341. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37342. for (var i = 0; i < this.soundCollection.length; i++) {
  37343. this.soundCollection[i].switchPanningModelToEqualPower();
  37344. }
  37345. }
  37346. };
  37347. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  37348. if (this._connectedAnalyser) {
  37349. this._connectedAnalyser.stopDebugCanvas();
  37350. }
  37351. this._connectedAnalyser = analyser;
  37352. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37353. this._outputAudioNode.disconnect();
  37354. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  37355. }
  37356. };
  37357. return SoundTrack;
  37358. }());
  37359. BABYLON.SoundTrack = SoundTrack;
  37360. })(BABYLON || (BABYLON = {}));
  37361. var BABYLON;
  37362. (function (BABYLON) {
  37363. /**
  37364. * Special Glow Blur post process only blurring the alpha channel
  37365. * It enforces keeping the most luminous color in the color channel.
  37366. */
  37367. var GlowBlurPostProcess = (function (_super) {
  37368. __extends(GlowBlurPostProcess, _super);
  37369. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  37370. var _this = this;
  37371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37372. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  37373. this.direction = direction;
  37374. this.blurWidth = blurWidth;
  37375. this.onApplyObservable.add(function (effect) {
  37376. effect.setFloat2("screenSize", _this.width, _this.height);
  37377. effect.setVector2("direction", _this.direction);
  37378. effect.setFloat("blurWidth", _this.blurWidth);
  37379. });
  37380. }
  37381. return GlowBlurPostProcess;
  37382. }(BABYLON.PostProcess));
  37383. /**
  37384. * The highlight layer Helps adding a glow effect around a mesh.
  37385. *
  37386. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  37387. * glowy meshes to your scene.
  37388. *
  37389. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  37390. */
  37391. var HighlightLayer = (function () {
  37392. /**
  37393. * Instantiates a new highlight Layer and references it to the scene..
  37394. * @param name The name of the layer
  37395. * @param scene The scene to use the layer in
  37396. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  37397. */
  37398. function HighlightLayer(name, scene, options) {
  37399. this._vertexBuffers = {};
  37400. this._mainTextureDesiredSize = { width: 0, height: 0 };
  37401. this._meshes = {};
  37402. this._maxSize = 0;
  37403. this._shouldRender = false;
  37404. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  37405. this._excludedMeshes = {};
  37406. /**
  37407. * Specifies whether or not the inner glow is ACTIVE in the layer.
  37408. */
  37409. this.innerGlow = true;
  37410. /**
  37411. * Specifies whether or not the outer glow is ACTIVE in the layer.
  37412. */
  37413. this.outerGlow = true;
  37414. /**
  37415. * An event triggered when the highlight layer has been disposed.
  37416. * @type {BABYLON.Observable}
  37417. */
  37418. this.onDisposeObservable = new BABYLON.Observable();
  37419. /**
  37420. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  37421. * @type {BABYLON.Observable}
  37422. */
  37423. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  37424. /**
  37425. * An event triggered when the highlight layer is being blurred.
  37426. * @type {BABYLON.Observable}
  37427. */
  37428. this.onBeforeBlurObservable = new BABYLON.Observable();
  37429. /**
  37430. * An event triggered when the highlight layer has been blurred.
  37431. * @type {BABYLON.Observable}
  37432. */
  37433. this.onAfterBlurObservable = new BABYLON.Observable();
  37434. /**
  37435. * An event triggered when the glowing blurred texture is being merged in the scene.
  37436. * @type {BABYLON.Observable}
  37437. */
  37438. this.onBeforeComposeObservable = new BABYLON.Observable();
  37439. /**
  37440. * An event triggered when the glowing blurred texture has been merged in the scene.
  37441. * @type {BABYLON.Observable}
  37442. */
  37443. this.onAfterComposeObservable = new BABYLON.Observable();
  37444. /**
  37445. * An event triggered when the highlight layer changes its size.
  37446. * @type {BABYLON.Observable}
  37447. */
  37448. this.onSizeChangedObservable = new BABYLON.Observable();
  37449. this._scene = scene;
  37450. var engine = scene.getEngine();
  37451. this._engine = engine;
  37452. this._maxSize = this._engine.getCaps().maxTextureSize;
  37453. this._scene.highlightLayers.push(this);
  37454. // Warn on stencil.
  37455. if (!this._engine.isStencilEnable) {
  37456. 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 }");
  37457. }
  37458. // Adapt options
  37459. this._options = options || {
  37460. mainTextureRatio: 0.25,
  37461. blurTextureSizeRatio: 0.5,
  37462. blurHorizontalSize: 1,
  37463. blurVerticalSize: 1,
  37464. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  37465. };
  37466. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  37467. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  37468. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  37469. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  37470. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  37471. // VBO
  37472. var vertices = [];
  37473. vertices.push(1, 1);
  37474. vertices.push(-1, 1);
  37475. vertices.push(-1, -1);
  37476. vertices.push(1, -1);
  37477. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37478. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  37479. // Indices
  37480. var indices = [];
  37481. indices.push(0);
  37482. indices.push(1);
  37483. indices.push(2);
  37484. indices.push(0);
  37485. indices.push(2);
  37486. indices.push(3);
  37487. this._indexBuffer = engine.createIndexBuffer(indices);
  37488. // Effect
  37489. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  37490. // Render target
  37491. this.setMainTextureSize();
  37492. // Create Textures and post processes
  37493. this.createTextureAndPostProcesses();
  37494. }
  37495. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  37496. /**
  37497. * Gets the horizontal size of the blur.
  37498. */
  37499. get: function () {
  37500. return this._horizontalBlurPostprocess.blurWidth;
  37501. },
  37502. /**
  37503. * Specifies the horizontal size of the blur.
  37504. */
  37505. set: function (value) {
  37506. this._horizontalBlurPostprocess.blurWidth = value;
  37507. },
  37508. enumerable: true,
  37509. configurable: true
  37510. });
  37511. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  37512. /**
  37513. * Gets the vertical size of the blur.
  37514. */
  37515. get: function () {
  37516. return this._verticalBlurPostprocess.blurWidth;
  37517. },
  37518. /**
  37519. * Specifies the vertical size of the blur.
  37520. */
  37521. set: function (value) {
  37522. this._verticalBlurPostprocess.blurWidth = value;
  37523. },
  37524. enumerable: true,
  37525. configurable: true
  37526. });
  37527. Object.defineProperty(HighlightLayer.prototype, "camera", {
  37528. /**
  37529. * Gets the camera attached to the layer.
  37530. */
  37531. get: function () {
  37532. return this._options.camera;
  37533. },
  37534. enumerable: true,
  37535. configurable: true
  37536. });
  37537. /**
  37538. * Creates the render target textures and post processes used in the highlight layer.
  37539. */
  37540. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  37541. var _this = this;
  37542. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  37543. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  37544. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  37545. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  37546. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  37547. width: this._mainTextureDesiredSize.width,
  37548. height: this._mainTextureDesiredSize.height
  37549. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  37550. this._mainTexture.activeCamera = this._options.camera;
  37551. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37552. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37553. this._mainTexture.anisotropicFilteringLevel = 1;
  37554. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37555. this._mainTexture.renderParticles = false;
  37556. this._mainTexture.renderList = null;
  37557. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  37558. width: blurTextureWidth,
  37559. height: blurTextureHeight
  37560. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  37561. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37562. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37563. this._blurTexture.anisotropicFilteringLevel = 16;
  37564. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  37565. this._blurTexture.renderParticles = false;
  37566. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37567. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  37568. effect.setTexture("textureSampler", _this._mainTexture);
  37569. });
  37570. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37571. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  37572. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  37573. });
  37574. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37575. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  37576. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  37577. });
  37578. this._mainTexture.onAfterUnbindObservable.add(function () {
  37579. _this.onBeforeBlurObservable.notifyObservers(_this);
  37580. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  37581. _this.onAfterBlurObservable.notifyObservers(_this);
  37582. });
  37583. // Custom render function
  37584. var renderSubMesh = function (subMesh) {
  37585. var mesh = subMesh.getRenderingMesh();
  37586. var scene = _this._scene;
  37587. var engine = scene.getEngine();
  37588. // Culling
  37589. engine.setState(subMesh.getMaterial().backFaceCulling);
  37590. // Managing instances
  37591. var batch = mesh._getInstancesRenderList(subMesh._id);
  37592. if (batch.mustReturn) {
  37593. return;
  37594. }
  37595. // Excluded Mesh
  37596. if (_this._excludedMeshes[mesh.id]) {
  37597. return;
  37598. }
  37599. ;
  37600. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37601. var highlightLayerMesh = _this._meshes[mesh.id];
  37602. var material = subMesh.getMaterial();
  37603. var emissiveTexture = null;
  37604. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  37605. emissiveTexture = material.emissiveTexture;
  37606. }
  37607. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  37608. engine.enableEffect(_this._glowMapGenerationEffect);
  37609. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  37610. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  37611. if (highlightLayerMesh) {
  37612. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  37613. }
  37614. else {
  37615. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  37616. }
  37617. // Alpha test
  37618. if (material && material.needAlphaTesting()) {
  37619. var alphaTexture = material.getAlphaTestTexture();
  37620. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  37621. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37622. }
  37623. // Glow emissive only
  37624. if (emissiveTexture) {
  37625. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  37626. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  37627. }
  37628. // Bones
  37629. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37630. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37631. }
  37632. // Draw
  37633. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  37634. }
  37635. else {
  37636. // Need to reset refresh rate of the shadowMap
  37637. _this._mainTexture.resetRefreshCounter();
  37638. }
  37639. };
  37640. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  37641. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  37642. var index;
  37643. for (index = 0; index < opaqueSubMeshes.length; index++) {
  37644. renderSubMesh(opaqueSubMeshes.data[index]);
  37645. }
  37646. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  37647. renderSubMesh(alphaTestSubMeshes.data[index]);
  37648. }
  37649. for (index = 0; index < transparentSubMeshes.length; index++) {
  37650. renderSubMesh(transparentSubMeshes.data[index]);
  37651. }
  37652. };
  37653. this._mainTexture.onClearObservable.add(function (engine) {
  37654. engine.clear(HighlightLayer.neutralColor, true, true, true);
  37655. });
  37656. };
  37657. /**
  37658. * Checks for the readiness of the element composing the layer.
  37659. * @param subMesh the mesh to check for
  37660. * @param useInstances specify wether or not to use instances to render the mesh
  37661. * @param emissiveTexture the associated emissive texture used to generate the glow
  37662. * @return true if ready otherwise, false
  37663. */
  37664. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  37665. if (!subMesh.getMaterial().isReady()) {
  37666. return false;
  37667. }
  37668. var defines = [];
  37669. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37670. var mesh = subMesh.getMesh();
  37671. var material = subMesh.getMaterial();
  37672. var uv1 = false;
  37673. var uv2 = false;
  37674. // Alpha test
  37675. if (material && material.needAlphaTesting()) {
  37676. var alphaTexture = material.getAlphaTestTexture();
  37677. if (alphaTexture) {
  37678. defines.push("#define ALPHATEST");
  37679. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37680. alphaTexture.coordinatesIndex === 1) {
  37681. defines.push("#define DIFFUSEUV2");
  37682. uv2 = true;
  37683. }
  37684. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37685. defines.push("#define DIFFUSEUV1");
  37686. uv1 = true;
  37687. }
  37688. }
  37689. }
  37690. // Emissive
  37691. if (emissiveTexture) {
  37692. defines.push("#define EMISSIVE");
  37693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37694. emissiveTexture.coordinatesIndex === 1) {
  37695. defines.push("#define EMISSIVEUV2");
  37696. uv2 = true;
  37697. }
  37698. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37699. defines.push("#define EMISSIVEUV1");
  37700. uv1 = true;
  37701. }
  37702. }
  37703. if (uv1) {
  37704. attribs.push(BABYLON.VertexBuffer.UVKind);
  37705. defines.push("#define UV1");
  37706. }
  37707. if (uv2) {
  37708. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37709. defines.push("#define UV2");
  37710. }
  37711. // Bones
  37712. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37713. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37714. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37715. if (mesh.numBoneInfluencers > 4) {
  37716. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37717. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37718. }
  37719. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37720. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37721. }
  37722. else {
  37723. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37724. }
  37725. // Instances
  37726. if (useInstances) {
  37727. defines.push("#define INSTANCES");
  37728. attribs.push("world0");
  37729. attribs.push("world1");
  37730. attribs.push("world2");
  37731. attribs.push("world3");
  37732. }
  37733. // Get correct effect
  37734. var join = defines.join("\n");
  37735. if (this._cachedDefines !== join) {
  37736. this._cachedDefines = join;
  37737. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  37738. }
  37739. return this._glowMapGenerationEffect.isReady();
  37740. };
  37741. /**
  37742. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  37743. */
  37744. HighlightLayer.prototype.render = function () {
  37745. var currentEffect = this._glowMapMergeEffect;
  37746. // Check
  37747. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  37748. return;
  37749. var engine = this._scene.getEngine();
  37750. this.onBeforeComposeObservable.notifyObservers(this);
  37751. // Render
  37752. engine.enableEffect(currentEffect);
  37753. engine.setState(false);
  37754. // Cache
  37755. var previousStencilBuffer = engine.getStencilBuffer();
  37756. var previousStencilFunction = engine.getStencilFunction();
  37757. var previousStencilMask = engine.getStencilMask();
  37758. var previousAlphaMode = engine.getAlphaMode();
  37759. // Texture
  37760. currentEffect.setTexture("textureSampler", this._blurTexture);
  37761. // VBOs
  37762. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  37763. // Draw order
  37764. engine.setAlphaMode(this._options.alphaBlendingMode);
  37765. engine.setStencilMask(0x00);
  37766. engine.setStencilBuffer(true);
  37767. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  37768. if (this.outerGlow) {
  37769. currentEffect.setFloat("offset", 0);
  37770. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  37771. engine.draw(true, 0, 6);
  37772. }
  37773. if (this.innerGlow) {
  37774. currentEffect.setFloat("offset", 1);
  37775. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  37776. engine.draw(true, 0, 6);
  37777. }
  37778. // Restore Cache
  37779. engine.setStencilFunction(previousStencilFunction);
  37780. engine.setStencilMask(previousStencilMask);
  37781. engine.setAlphaMode(previousAlphaMode);
  37782. engine.setStencilBuffer(previousStencilBuffer);
  37783. this.onAfterComposeObservable.notifyObservers(this);
  37784. // Handle size changes.
  37785. var size = this._mainTexture.getSize();
  37786. this.setMainTextureSize();
  37787. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  37788. // Recreate RTT and post processes on size change.
  37789. this.onSizeChangedObservable.notifyObservers(this);
  37790. this.disposeTextureAndPostProcesses();
  37791. this.createTextureAndPostProcesses();
  37792. }
  37793. };
  37794. /**
  37795. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  37796. * @param mesh The mesh to exclude from the highlight layer
  37797. */
  37798. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  37799. var meshExcluded = this._excludedMeshes[mesh.id];
  37800. if (!meshExcluded) {
  37801. this._excludedMeshes[mesh.id] = {
  37802. mesh: mesh,
  37803. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  37804. mesh.getEngine().setStencilBuffer(false);
  37805. }),
  37806. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  37807. mesh.getEngine().setStencilBuffer(true);
  37808. }),
  37809. };
  37810. }
  37811. };
  37812. /**
  37813. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  37814. * @param mesh The mesh to highlight
  37815. */
  37816. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  37817. var meshExcluded = this._excludedMeshes[mesh.id];
  37818. if (meshExcluded) {
  37819. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  37820. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  37821. }
  37822. this._excludedMeshes[mesh.id] = undefined;
  37823. };
  37824. /**
  37825. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  37826. * @param mesh The mesh to highlight
  37827. * @param color The color of the highlight
  37828. * @param glowEmissiveOnly Extract the glow from the emissive texture
  37829. */
  37830. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  37831. var _this = this;
  37832. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  37833. var meshHighlight = this._meshes[mesh.id];
  37834. if (meshHighlight) {
  37835. meshHighlight.color = color;
  37836. }
  37837. else {
  37838. this._meshes[mesh.id] = {
  37839. mesh: mesh,
  37840. color: color,
  37841. // Lambda required for capture due to Observable this context
  37842. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  37843. if (_this._excludedMeshes[mesh.id]) {
  37844. _this.defaultStencilReference(mesh);
  37845. }
  37846. else {
  37847. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  37848. }
  37849. }),
  37850. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  37851. glowEmissiveOnly: glowEmissiveOnly
  37852. };
  37853. }
  37854. this._shouldRender = true;
  37855. };
  37856. /**
  37857. * Remove a mesh from the highlight layer in order to make it stop glowing.
  37858. * @param mesh The mesh to highlight
  37859. */
  37860. HighlightLayer.prototype.removeMesh = function (mesh) {
  37861. var meshHighlight = this._meshes[mesh.id];
  37862. if (meshHighlight) {
  37863. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37864. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37865. }
  37866. this._meshes[mesh.id] = undefined;
  37867. this._shouldRender = false;
  37868. for (var meshHighlightToCheck in this._meshes) {
  37869. if (meshHighlightToCheck) {
  37870. this._shouldRender = true;
  37871. break;
  37872. }
  37873. }
  37874. };
  37875. /**
  37876. * Returns true if the layer contains information to display, otherwise false.
  37877. */
  37878. HighlightLayer.prototype.shouldRender = function () {
  37879. return this._shouldRender;
  37880. };
  37881. /**
  37882. * Sets the main texture desired size which is the closest power of two
  37883. * of the engine canvas size.
  37884. */
  37885. HighlightLayer.prototype.setMainTextureSize = function () {
  37886. if (this._options.mainTextureFixedSize) {
  37887. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  37888. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  37889. }
  37890. else {
  37891. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  37892. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  37893. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  37894. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  37895. }
  37896. };
  37897. /**
  37898. * Force the stencil to the normal expected value for none glowing parts
  37899. */
  37900. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  37901. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  37902. };
  37903. /**
  37904. * Dispose only the render target textures and post process.
  37905. */
  37906. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  37907. this._blurTexture.dispose();
  37908. this._mainTexture.dispose();
  37909. this._downSamplePostprocess.dispose();
  37910. this._horizontalBlurPostprocess.dispose();
  37911. this._verticalBlurPostprocess.dispose();
  37912. };
  37913. /**
  37914. * Dispose the highlight layer and free resources.
  37915. */
  37916. HighlightLayer.prototype.dispose = function () {
  37917. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37918. if (vertexBuffer) {
  37919. vertexBuffer.dispose();
  37920. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37921. }
  37922. if (this._indexBuffer) {
  37923. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37924. this._indexBuffer = null;
  37925. }
  37926. // Clean textures and post processes
  37927. this.disposeTextureAndPostProcesses();
  37928. // Clean mesh references
  37929. for (var id in this._meshes) {
  37930. var meshHighlight = this._meshes[id];
  37931. if (meshHighlight && meshHighlight.mesh) {
  37932. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37933. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37934. }
  37935. }
  37936. this._meshes = null;
  37937. for (var id in this._excludedMeshes) {
  37938. var meshHighlight = this._excludedMeshes[id];
  37939. if (meshHighlight) {
  37940. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  37941. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  37942. }
  37943. }
  37944. this._excludedMeshes = null;
  37945. // Remove from scene
  37946. var index = this._scene.highlightLayers.indexOf(this, 0);
  37947. if (index > -1) {
  37948. this._scene.highlightLayers.splice(index, 1);
  37949. }
  37950. // Callback
  37951. this.onDisposeObservable.notifyObservers(this);
  37952. this.onDisposeObservable.clear();
  37953. this.onBeforeRenderMainTextureObservable.clear();
  37954. this.onBeforeBlurObservable.clear();
  37955. this.onBeforeComposeObservable.clear();
  37956. this.onAfterComposeObservable.clear();
  37957. this.onSizeChangedObservable.clear();
  37958. };
  37959. /**
  37960. * The neutral color used during the preparation of the glow effect.
  37961. * This is black by default as the blend operation is a blend operation.
  37962. */
  37963. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  37964. /**
  37965. * Stencil value used for glowing meshes.
  37966. */
  37967. HighlightLayer.glowingMeshStencilReference = 0x02;
  37968. /**
  37969. * Stencil value used for the other meshes in the scene.
  37970. */
  37971. HighlightLayer.normalMeshStencilReference = 0x01;
  37972. return HighlightLayer;
  37973. }());
  37974. BABYLON.HighlightLayer = HighlightLayer;
  37975. })(BABYLON || (BABYLON = {}));
  37976. var BABYLON;
  37977. (function (BABYLON) {
  37978. var SIMDVector3 = (function () {
  37979. function SIMDVector3() {
  37980. }
  37981. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  37982. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  37983. };
  37984. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  37985. var m = transformation.m;
  37986. var m0 = SIMD.Float32x4.load(m, 0);
  37987. var m1 = SIMD.Float32x4.load(m, 4);
  37988. var m2 = SIMD.Float32x4.load(m, 8);
  37989. var m3 = SIMD.Float32x4.load(m, 12);
  37990. 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));
  37991. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  37992. result.x = SIMD.Float32x4.extractLane(r, 0);
  37993. result.y = SIMD.Float32x4.extractLane(r, 1);
  37994. result.z = SIMD.Float32x4.extractLane(r, 2);
  37995. };
  37996. return SIMDVector3;
  37997. }());
  37998. var SIMDMatrix = (function () {
  37999. function SIMDMatrix() {
  38000. }
  38001. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  38002. var tm = this.m;
  38003. var om = other.m;
  38004. var m0 = SIMD.Float32x4.load(om, 0);
  38005. var m1 = SIMD.Float32x4.load(om, 4);
  38006. var m2 = SIMD.Float32x4.load(om, 8);
  38007. var m3 = SIMD.Float32x4.load(om, 12);
  38008. for (var i = 0; i < 16; i += 4) {
  38009. 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)))));
  38010. }
  38011. return this;
  38012. };
  38013. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  38014. var src = this.m;
  38015. var dest = other.m;
  38016. // Load the 4 rows
  38017. var src0 = SIMD.Float32x4.load(src, 0);
  38018. var src1 = SIMD.Float32x4.load(src, 4);
  38019. var src2 = SIMD.Float32x4.load(src, 8);
  38020. var src3 = SIMD.Float32x4.load(src, 12);
  38021. // Transpose the source matrix. Sort of. Not a true transpose operation
  38022. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  38023. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  38024. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  38025. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  38026. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  38027. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  38028. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  38029. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  38030. // This is a true transposition, but it will lead to an incorrect result
  38031. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  38032. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  38033. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  38034. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  38035. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  38036. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  38037. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  38038. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  38039. // ----
  38040. tmp1 = SIMD.Float32x4.mul(row2, row3);
  38041. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38042. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  38043. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  38044. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38045. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  38046. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  38047. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  38048. // ----
  38049. tmp1 = SIMD.Float32x4.mul(row1, row2);
  38050. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38051. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  38052. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  38053. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38054. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  38055. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  38056. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  38057. // ----
  38058. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  38059. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38060. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  38061. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  38062. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  38063. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38064. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  38065. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  38066. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  38067. // ----
  38068. tmp1 = SIMD.Float32x4.mul(row0, row1);
  38069. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38070. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  38071. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  38072. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38073. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  38074. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  38075. // ----
  38076. tmp1 = SIMD.Float32x4.mul(row0, row3);
  38077. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38078. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  38079. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  38080. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38081. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  38082. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  38083. // ----
  38084. tmp1 = SIMD.Float32x4.mul(row0, row2);
  38085. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38086. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  38087. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  38088. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38089. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  38090. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  38091. // Compute determinant
  38092. var det = SIMD.Float32x4.mul(row0, minor0);
  38093. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  38094. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  38095. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  38096. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  38097. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  38098. // These shuffles aren't necessary if the faulty transposition is done
  38099. // up at the top of this function.
  38100. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  38101. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  38102. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  38103. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  38104. // Compute final values by multiplying with 1/det
  38105. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  38106. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  38107. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  38108. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  38109. return this;
  38110. };
  38111. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  38112. var out = result.m;
  38113. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  38114. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  38115. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  38116. // cc.kmVec3Subtract(f, pCenter, pEye);
  38117. var f = SIMD.Float32x4.sub(center, eye);
  38118. // cc.kmVec3Normalize(f, f);
  38119. var tmp = SIMD.Float32x4.mul(f, f);
  38120. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38121. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38122. // cc.kmVec3Assign(up, pUp);
  38123. // cc.kmVec3Normalize(up, up);
  38124. tmp = SIMD.Float32x4.mul(up, up);
  38125. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38126. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38127. // cc.kmVec3Cross(s, f, up);
  38128. 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)));
  38129. // cc.kmVec3Normalize(s, s);
  38130. tmp = SIMD.Float32x4.mul(s, s);
  38131. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38132. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38133. // cc.kmVec3Cross(u, s, f);
  38134. 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)));
  38135. // cc.kmVec3Normalize(s, s);
  38136. tmp = SIMD.Float32x4.mul(s, s);
  38137. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38138. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38139. var zero = SIMD.Float32x4.splat(0.0);
  38140. s = SIMD.Float32x4.neg(s);
  38141. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  38142. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  38143. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  38144. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  38145. 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);
  38146. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  38147. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  38148. 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)))));
  38149. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  38150. 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)))));
  38151. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  38152. 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)))));
  38153. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  38154. 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)))));
  38155. };
  38156. return SIMDMatrix;
  38157. }());
  38158. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  38159. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  38160. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  38161. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  38162. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  38163. var SIMDHelper = (function () {
  38164. function SIMDHelper() {
  38165. }
  38166. Object.defineProperty(SIMDHelper, "IsEnabled", {
  38167. get: function () {
  38168. return SIMDHelper._isEnabled;
  38169. },
  38170. enumerable: true,
  38171. configurable: true
  38172. });
  38173. SIMDHelper.DisableSIMD = function () {
  38174. // Replace functions
  38175. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  38176. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  38177. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  38178. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  38179. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  38180. SIMDHelper._isEnabled = false;
  38181. };
  38182. SIMDHelper.EnableSIMD = function () {
  38183. if (self.SIMD === undefined) {
  38184. return;
  38185. }
  38186. // check if polyfills needed
  38187. if (!self.Math.fround) {
  38188. self.Math.fround = (function (array) { return function (x) {
  38189. return array[0] = x, array[0];
  38190. }; })(new Float32Array(1));
  38191. }
  38192. if (!self.Math.imul) {
  38193. self.Math.imul = function (a, b) {
  38194. var ah = (a >>> 16) & 0xffff;
  38195. var al = a & 0xffff;
  38196. var bh = (b >>> 16) & 0xffff;
  38197. var bl = b & 0xffff;
  38198. // the shift by 0 fixes the sign on the high part
  38199. // the final |0 converts the unsigned value into a signed value
  38200. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  38201. };
  38202. }
  38203. // Replace functions
  38204. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  38205. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  38206. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  38207. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  38208. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  38209. SIMDHelper._isEnabled = true;
  38210. };
  38211. SIMDHelper._isEnabled = false;
  38212. return SIMDHelper;
  38213. }());
  38214. BABYLON.SIMDHelper = SIMDHelper;
  38215. })(BABYLON || (BABYLON = {}));
  38216. var BABYLON;
  38217. (function (BABYLON) {
  38218. /**
  38219. * This class describe a rectangle that were added to the map.
  38220. * You have access to its coordinates either in pixel or normalized (UV)
  38221. */
  38222. var PackedRect = (function () {
  38223. function PackedRect(root, parent, pos, size) {
  38224. this._pos = pos;
  38225. this._size = size;
  38226. this._root = root;
  38227. this._parent = parent;
  38228. this._contentSize = null;
  38229. this._bottomNode = null;
  38230. this._leftNode = null;
  38231. this._initialSize = null;
  38232. this._rightNode = null;
  38233. }
  38234. Object.defineProperty(PackedRect.prototype, "pos", {
  38235. /**
  38236. * @returns the position of this node into the map
  38237. */
  38238. get: function () {
  38239. return this._pos;
  38240. },
  38241. enumerable: true,
  38242. configurable: true
  38243. });
  38244. Object.defineProperty(PackedRect.prototype, "contentSize", {
  38245. /**
  38246. * @returns the size of the rectangle this node handles
  38247. */
  38248. get: function () {
  38249. return this._contentSize;
  38250. },
  38251. enumerable: true,
  38252. configurable: true
  38253. });
  38254. Object.defineProperty(PackedRect.prototype, "UVs", {
  38255. /**
  38256. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  38257. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  38258. */
  38259. get: function () {
  38260. return this.getUVsForCustomSize(this._root._size);
  38261. },
  38262. enumerable: true,
  38263. configurable: true
  38264. });
  38265. /**
  38266. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations) and then using only a part of the PackRect.
  38267. * This method will return the UVs for this part by given the custom size of what you really use
  38268. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  38269. */
  38270. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  38271. var mainWidth = this._root._size.width;
  38272. var mainHeight = this._root._size.height;
  38273. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  38274. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  38275. var uvs = new Array();
  38276. uvs.push(topLeft);
  38277. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  38278. uvs.push(rightBottom);
  38279. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  38280. return uvs;
  38281. };
  38282. /**
  38283. * Free this rectangle from the map.
  38284. * Call this method when you no longer need the rectangle to be in the map.
  38285. */
  38286. PackedRect.prototype.freeContent = function () {
  38287. if (!this.contentSize) {
  38288. return;
  38289. }
  38290. this._contentSize = null;
  38291. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  38292. this.attemptDefrag();
  38293. };
  38294. Object.defineProperty(PackedRect.prototype, "isUsed", {
  38295. get: function () {
  38296. return this._contentSize != null || this._leftNode != null;
  38297. },
  38298. enumerable: true,
  38299. configurable: true
  38300. });
  38301. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  38302. var node = this.findNode(contentSize);
  38303. // Not enough space...
  38304. if (!node) {
  38305. return null;
  38306. }
  38307. node.splitNode(contentSize);
  38308. return node;
  38309. };
  38310. PackedRect.prototype.findNode = function (size) {
  38311. var resNode = null;
  38312. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  38313. if (this.isUsed) {
  38314. if (this._leftNode) {
  38315. resNode = this._leftNode.findNode(size);
  38316. }
  38317. if (!resNode && this._rightNode) {
  38318. resNode = this._rightNode.findNode(size);
  38319. }
  38320. if (!resNode && this._bottomNode) {
  38321. resNode = this._bottomNode.findNode(size);
  38322. }
  38323. }
  38324. else if (this._initialSize) {
  38325. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  38326. resNode = this;
  38327. }
  38328. else {
  38329. return null;
  38330. }
  38331. }
  38332. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  38333. resNode = this;
  38334. }
  38335. return resNode;
  38336. };
  38337. PackedRect.prototype.splitNode = function (contentSize) {
  38338. // 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)
  38339. if (!this._contentSize && this._initialSize) {
  38340. this._contentSize = contentSize.clone();
  38341. 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));
  38342. return this._leftNode.splitNode(contentSize);
  38343. }
  38344. else {
  38345. this._contentSize = contentSize.clone();
  38346. this._initialSize = contentSize.clone();
  38347. if (contentSize.width !== this._size.width) {
  38348. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
  38349. }
  38350. if (contentSize.height !== this._size.height) {
  38351. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
  38352. }
  38353. return this;
  38354. }
  38355. };
  38356. PackedRect.prototype.attemptDefrag = function () {
  38357. if (!this.isUsed && this.isRecursiveFree) {
  38358. this.clearNode();
  38359. if (this._parent) {
  38360. this._parent.attemptDefrag();
  38361. }
  38362. }
  38363. };
  38364. PackedRect.prototype.clearNode = function () {
  38365. this._initialSize = null;
  38366. this._rightNode = null;
  38367. this._bottomNode = null;
  38368. };
  38369. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  38370. get: function () {
  38371. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  38372. },
  38373. enumerable: true,
  38374. configurable: true
  38375. });
  38376. PackedRect.prototype.evalFreeSize = function (size) {
  38377. var levelSize = 0;
  38378. if (!this.isUsed) {
  38379. if (this._initialSize) {
  38380. levelSize = this._initialSize.surface;
  38381. }
  38382. else {
  38383. levelSize = this._size.surface;
  38384. }
  38385. }
  38386. if (this._rightNode) {
  38387. levelSize += this._rightNode.evalFreeSize(0);
  38388. }
  38389. if (this._bottomNode) {
  38390. levelSize += this._bottomNode.evalFreeSize(0);
  38391. }
  38392. return levelSize + size;
  38393. };
  38394. return PackedRect;
  38395. }());
  38396. BABYLON.PackedRect = PackedRect;
  38397. /**
  38398. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  38399. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  38400. * 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.
  38401. */
  38402. var RectPackingMap = (function (_super) {
  38403. __extends(RectPackingMap, _super);
  38404. /**
  38405. * Create an instance of the object with a dimension using the given size
  38406. * @param size The dimension of the rectangle that will contain all the sub ones.
  38407. */
  38408. function RectPackingMap(size) {
  38409. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  38410. this._root = this;
  38411. }
  38412. /**
  38413. * Add a rectangle, finding the best location to store it into the map
  38414. * @param size the dimension of the rectangle to store
  38415. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  38416. */
  38417. RectPackingMap.prototype.addRect = function (size) {
  38418. var node = this.findAndSplitNode(size);
  38419. return node;
  38420. };
  38421. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  38422. /**
  38423. * Return the current space free normalized between [0;1]
  38424. * @returns {}
  38425. */
  38426. get: function () {
  38427. var freeSize = 0;
  38428. freeSize = this.evalFreeSize(freeSize);
  38429. return freeSize / (this._size.width * this._size.height);
  38430. },
  38431. enumerable: true,
  38432. configurable: true
  38433. });
  38434. return RectPackingMap;
  38435. }(PackedRect));
  38436. BABYLON.RectPackingMap = RectPackingMap;
  38437. })(BABYLON || (BABYLON = {}));
  38438. var BABYLON;
  38439. (function (BABYLON) {
  38440. var DynamicFloatArrayElementInfo = (function () {
  38441. function DynamicFloatArrayElementInfo() {
  38442. }
  38443. return DynamicFloatArrayElementInfo;
  38444. }());
  38445. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  38446. /**
  38447. * 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.
  38448. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  38449. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  38450. * 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.
  38451. * 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.
  38452. * 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".
  38453. */
  38454. var DynamicFloatArray = (function () {
  38455. /**
  38456. * Construct an instance of the dynamic float array
  38457. * @param stride size of one element in float (i.e. not bytes!)
  38458. * @param initialElementCount the number of available entries at construction
  38459. */
  38460. function DynamicFloatArray(stride, initialElementCount) {
  38461. this.compareValueOffset = null;
  38462. this.sortingAscending = true;
  38463. this._stride = stride;
  38464. this.buffer = new Float32Array(stride * initialElementCount);
  38465. this._lastUsed = 0;
  38466. this._firstFree = 0;
  38467. this._allEntries = new Array(initialElementCount);
  38468. this._freeEntries = new Array(initialElementCount);
  38469. for (var i = 0; i < initialElementCount; i++) {
  38470. var element = new DynamicFloatArrayElementInfo();
  38471. element.offset = i * stride;
  38472. this._allEntries[i] = element;
  38473. this._freeEntries[initialElementCount - i - 1] = element;
  38474. }
  38475. }
  38476. /**
  38477. * Allocate an element in the array.
  38478. * @return the element info instance that contains the offset into the main buffer of the element's location.
  38479. * Beware, this offset may change when you call pack()
  38480. */
  38481. DynamicFloatArray.prototype.allocElement = function () {
  38482. if (this._freeEntries.length === 0) {
  38483. this._growBuffer();
  38484. }
  38485. var el = this._freeEntries.pop();
  38486. this._lastUsed = Math.max(el.offset, this._lastUsed);
  38487. if (el.offset === this._firstFree) {
  38488. if (this._freeEntries.length > 0) {
  38489. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  38490. }
  38491. else {
  38492. this._firstFree += this._stride;
  38493. }
  38494. }
  38495. return el;
  38496. };
  38497. /**
  38498. * Free the element corresponding to the given element info
  38499. * @param elInfo the element that describe the allocated element
  38500. */
  38501. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  38502. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  38503. this._freeEntries.push(elInfo);
  38504. };
  38505. /**
  38506. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  38507. * 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().
  38508. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  38509. */
  38510. DynamicFloatArray.prototype.pack = function () {
  38511. // no free slot? no need to pack
  38512. if (this._freeEntries.length === 0) {
  38513. return this.buffer;
  38514. }
  38515. // If the buffer is already packed the last used will always be lower than the first free
  38516. // 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.
  38517. if (this._lastUsed < this._firstFree) {
  38518. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  38519. return elementsBuffer_1;
  38520. }
  38521. var s = this._stride;
  38522. // 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
  38523. var lastFree = new DynamicFloatArrayElementInfo();
  38524. lastFree.offset = this.totalElementCount * s;
  38525. this._freeEntries.push(lastFree);
  38526. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  38527. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  38528. var firstFreeSlotOffset = sortedFree[0].offset;
  38529. var freeZoneSize = 1;
  38530. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  38531. var prevOffset = sortedFree[0].offset;
  38532. for (var i = 1; i < sortedFree.length; i++) {
  38533. // 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
  38534. if (firstFreeSlotOffset >= occupiedZoneSize) {
  38535. break;
  38536. }
  38537. var curFree = sortedFree[i];
  38538. var curOffset = curFree.offset;
  38539. // Compute the distance between this offset and the previous
  38540. var distance = curOffset - prevOffset;
  38541. // If the distance is the stride size, they are adjacent, it good, move to the next
  38542. if (distance === s) {
  38543. // Free zone is one element bigger
  38544. ++freeZoneSize;
  38545. // as we're about to iterate to the next, the cur becomes the previous...
  38546. prevOffset = curOffset;
  38547. continue;
  38548. }
  38549. // Distance is bigger, which means there's x element between the previous free and this one
  38550. var usedRange = (distance / s) - 1;
  38551. // Two cases the free zone is smaller than the data to move or bigger
  38552. // Copy what can fit in the free zone
  38553. var curMoveOffset = curOffset - s;
  38554. var copyCount = Math.min(freeZoneSize, usedRange);
  38555. for (var j = 0; j < copyCount; j++) {
  38556. var freeI = firstFreeSlotOffset / s;
  38557. var curI = curMoveOffset / s;
  38558. var moveEl = sortedAll[curI];
  38559. this._moveElement(moveEl, firstFreeSlotOffset);
  38560. var replacedEl = sortedAll[freeI];
  38561. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  38562. replacedEl.offset = curMoveOffset;
  38563. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  38564. sortedAll[freeI] = moveEl;
  38565. sortedAll[curI] = replacedEl;
  38566. curMoveOffset -= s;
  38567. firstFreeSlotOffset += s;
  38568. }
  38569. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  38570. if (freeZoneSize <= usedRange) {
  38571. firstFreeSlotOffset = curMoveOffset + s;
  38572. freeZoneSize = 1 + copyCount;
  38573. }
  38574. else {
  38575. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  38576. }
  38577. // as we're about to iterate to the next, the cur becomes the previous...
  38578. prevOffset = curOffset;
  38579. }
  38580. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  38581. this._lastUsed = firstFreeSlotOffset - s;
  38582. this._firstFree = firstFreeSlotOffset;
  38583. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  38584. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  38585. this._allEntries = sortedAll;
  38586. return elementsBuffer;
  38587. };
  38588. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  38589. for (var i = 0; i < this._stride; i++) {
  38590. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  38591. }
  38592. element.offset = destOffset;
  38593. };
  38594. DynamicFloatArray.prototype._growBuffer = function () {
  38595. // Allocate the new buffer with 50% more entries, copy the content of the current one
  38596. var newElCount = Math.floor(this.totalElementCount * 1.5);
  38597. var newBuffer = new Float32Array(newElCount * this._stride);
  38598. newBuffer.set(this.buffer);
  38599. var curCount = this.totalElementCount;
  38600. var addedCount = newElCount - this.totalElementCount;
  38601. for (var i = 0; i < addedCount; i++) {
  38602. var element = new DynamicFloatArrayElementInfo();
  38603. element.offset = (curCount + i) * this.stride;
  38604. this._allEntries.push(element);
  38605. this._freeEntries[addedCount - i - 1] = element;
  38606. }
  38607. this._firstFree = curCount * this.stride;
  38608. this.buffer = newBuffer;
  38609. };
  38610. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  38611. /**
  38612. * Get the total count of entries that can fit in the current buffer
  38613. * @returns the elements count
  38614. */
  38615. get: function () {
  38616. return this._allEntries.length;
  38617. },
  38618. enumerable: true,
  38619. configurable: true
  38620. });
  38621. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  38622. /**
  38623. * Get the count of free entries that can still be allocated without resizing the buffer
  38624. * @returns the free elements count
  38625. */
  38626. get: function () {
  38627. return this._freeEntries.length;
  38628. },
  38629. enumerable: true,
  38630. configurable: true
  38631. });
  38632. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  38633. /**
  38634. * Get the count of allocated elements
  38635. * @returns the allocated elements count
  38636. */
  38637. get: function () {
  38638. return this._allEntries.length - this._freeEntries.length;
  38639. },
  38640. enumerable: true,
  38641. configurable: true
  38642. });
  38643. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  38644. /**
  38645. * Return the size of one element in float
  38646. * @returns the size in float
  38647. */
  38648. get: function () {
  38649. return this._stride;
  38650. },
  38651. enumerable: true,
  38652. configurable: true
  38653. });
  38654. DynamicFloatArray.prototype.sort = function () {
  38655. var _this = this;
  38656. if (!this.compareValueOffset) {
  38657. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  38658. }
  38659. var count = this.usedElementCount;
  38660. // Do we have to (re)create the sort table?
  38661. if (!this._sortTable || this._sortTable.length < count) {
  38662. // 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...
  38663. var newCount = Math.min(this.totalElementCount, count * 2);
  38664. this._sortTable = new Array(newCount);
  38665. }
  38666. if (!this._sortedTable || this._sortedTable.length !== count) {
  38667. this._sortedTable = new Array(count);
  38668. }
  38669. // Because, you know...
  38670. this.pack();
  38671. //let stride = this.stride;
  38672. //for (let i = 0; i < count; i++) {
  38673. // let si = this._sortTable[i];
  38674. // if (!si) {
  38675. // si = new SortInfo();
  38676. // this._sortTable[i] = si;
  38677. // }
  38678. // si.entry = this._allEntries[i];
  38679. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  38680. // si.swapedOffset = null;
  38681. // this._sortedTable[i] = si;
  38682. //}
  38683. var curOffset = 0;
  38684. var stride = this.stride;
  38685. for (var i = 0; i < count; i++, curOffset += stride) {
  38686. var si = this._sortTable[i];
  38687. if (!si) {
  38688. si = new SortInfo();
  38689. this._sortTable[i] = si;
  38690. }
  38691. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  38692. si.offset = curOffset;
  38693. si.swapedOffset = null;
  38694. this._sortedTable[i] = si;
  38695. }
  38696. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  38697. if (this.sortingAscending) {
  38698. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  38699. }
  38700. else {
  38701. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  38702. }
  38703. var swapElements = function (src, dst) {
  38704. for (var i = 0; i < stride; i++) {
  38705. var tps = _this.buffer[dst + i];
  38706. _this.buffer[dst + i] = _this.buffer[src + i];
  38707. _this.buffer[src + i] = tps;
  38708. }
  38709. };
  38710. // 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:
  38711. // 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),
  38712. // and I still want something with a good algorithm complexity.
  38713. // 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,
  38714. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  38715. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  38716. // 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
  38717. // until we find a SortInfo object without a swapedOffset which means we got the right location
  38718. // 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
  38719. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  38720. for (var i = 0; i < count; i++) {
  38721. // Get the element to move
  38722. var sourceSI = this._sortedTable[i];
  38723. var destSI = this._sortTable[i];
  38724. var sourceOff = sourceSI.offset;
  38725. // If the source changed location, find the new one
  38726. if (sourceSI.swapedOffset) {
  38727. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  38728. var curSI = sourceSI;
  38729. while (curSI.swapedOffset) {
  38730. curSI = this._sortTable[curSI.swapedOffset / stride];
  38731. }
  38732. // Finally get the right location
  38733. sourceOff = curSI.offset;
  38734. }
  38735. // Tag the element being replaced with its new location
  38736. destSI.swapedOffset = sourceOff;
  38737. // Swap elements (only if needed)
  38738. if (sourceOff !== destSI.offset) {
  38739. swapElements(sourceOff, destSI.offset);
  38740. }
  38741. // Update the offset in the corresponding DFAE
  38742. //sourceSI.entry.offset = destSI.entry.offset;
  38743. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  38744. }
  38745. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  38746. return true;
  38747. };
  38748. return DynamicFloatArray;
  38749. }());
  38750. BABYLON.DynamicFloatArray = DynamicFloatArray;
  38751. var SortInfo = (function () {
  38752. function SortInfo() {
  38753. this.compareData = this.offset = this.swapedOffset = null;
  38754. }
  38755. return SortInfo;
  38756. }());
  38757. })(BABYLON || (BABYLON = {}));
  38758. var BABYLON;
  38759. (function (BABYLON) {
  38760. /**
  38761. * This class given information about a given character.
  38762. */
  38763. var CharInfo = (function () {
  38764. function CharInfo() {
  38765. }
  38766. return CharInfo;
  38767. }());
  38768. BABYLON.CharInfo = CharInfo;
  38769. var FontTexture = (function (_super) {
  38770. __extends(FontTexture, _super);
  38771. /**
  38772. * Create a new instance of the FontTexture class
  38773. * @param name the name of the texture
  38774. * @param font the font to use, use the W3C CSS notation
  38775. * @param scene the scene that owns the texture
  38776. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  38777. * @param samplingMode the texture sampling mode
  38778. * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
  38779. */
  38780. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  38781. if (maxCharCount === void 0) { maxCharCount = 200; }
  38782. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38783. if (superSample === void 0) { superSample = false; }
  38784. if (signedDistanceField === void 0) { signedDistanceField = false; }
  38785. _super.call(this, null, scene, true, false, samplingMode);
  38786. this._charInfos = {};
  38787. this._curCharCount = 0;
  38788. this._lastUpdateCharCount = -1;
  38789. this._usedCounter = 1;
  38790. this.name = name;
  38791. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38792. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38793. this._sdfScale = 8;
  38794. this._signedDistanceField = signedDistanceField;
  38795. this._superSample = false;
  38796. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  38797. if (superSample || signedDistanceField) {
  38798. var sfont = this.getSuperSampleFont(font);
  38799. if (sfont) {
  38800. this._superSample = true;
  38801. font = sfont;
  38802. }
  38803. }
  38804. // First canvas creation to determine the size of the texture to create
  38805. this._canvas = document.createElement("canvas");
  38806. this._context = this._canvas.getContext("2d");
  38807. this._context.font = font;
  38808. this._context.fillStyle = "white";
  38809. this._context.textBaseline = "top";
  38810. this._cachedFontId = null;
  38811. var res = this.getFontHeight(font);
  38812. this._lineHeightSuper = res.height + 4;
  38813. this._lineHeight = this._superSample ? (Math.ceil(this._lineHeightSuper / 2)) : this._lineHeightSuper;
  38814. this._offset = res.offset - 1;
  38815. this._xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  38816. this._yMargin = this._xMargin;
  38817. var maxCharWidth = this._context.measureText("W").width;
  38818. this._spaceWidthSuper = this._context.measureText(" ").width;
  38819. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  38820. // This is an approximate size, but should always be able to fit at least the maxCharCount
  38821. var totalEstSurface = (this._lineHeightSuper + this._yMargin) * (maxCharWidth + this._xMargin) * maxCharCount;
  38822. var edge = Math.sqrt(totalEstSurface);
  38823. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  38824. // Create the texture that will store the font characters
  38825. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  38826. var textureSize = this.getSize();
  38827. this.hasAlpha = this._signedDistanceField === false;
  38828. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  38829. this._canvas = document.createElement("canvas");
  38830. this._canvas.width = textureSize.width;
  38831. this._canvas.height = textureSize.height;
  38832. this._context = this._canvas.getContext("2d");
  38833. this._context.textBaseline = "top";
  38834. this._context.font = font;
  38835. this._context.fillStyle = "white";
  38836. this._context.imageSmoothingEnabled = false;
  38837. this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  38838. // Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times
  38839. // into this 2D context, then get the bitmap data, create the sdf char and push the result in the _context (which hold the whole Font Texture content)
  38840. // So you can see this context as an intermediate one, because it is.
  38841. if (this._signedDistanceField) {
  38842. var sdfC = document.createElement("canvas");
  38843. var s = this._sdfScale;
  38844. sdfC.width = maxCharWidth * s;
  38845. sdfC.height = this._lineHeightSuper * s;
  38846. var sdfCtx = sdfC.getContext("2d");
  38847. sdfCtx.scale(s, s);
  38848. sdfCtx.textBaseline = "top";
  38849. sdfCtx.font = font;
  38850. sdfCtx.fillStyle = "white";
  38851. sdfCtx.imageSmoothingEnabled = false;
  38852. this._sdfCanvas = sdfC;
  38853. this._sdfContext = sdfCtx;
  38854. }
  38855. this._currentFreePosition = BABYLON.Vector2.Zero();
  38856. // Add the basic ASCII based characters
  38857. for (var i = 0x20; i < 0x7F; i++) {
  38858. var c = String.fromCharCode(i);
  38859. this.getChar(c);
  38860. }
  38861. this.update();
  38862. }
  38863. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  38864. get: function () {
  38865. return this._superSample;
  38866. },
  38867. enumerable: true,
  38868. configurable: true
  38869. });
  38870. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  38871. get: function () {
  38872. return this._signedDistanceField;
  38873. },
  38874. enumerable: true,
  38875. configurable: true
  38876. });
  38877. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  38878. get: function () {
  38879. return this._spaceWidth;
  38880. },
  38881. enumerable: true,
  38882. configurable: true
  38883. });
  38884. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  38885. get: function () {
  38886. return this._lineHeight;
  38887. },
  38888. enumerable: true,
  38889. configurable: true
  38890. });
  38891. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  38892. if (supersample === void 0) { supersample = false; }
  38893. if (signedDistanceField === void 0) { signedDistanceField = false; }
  38894. var s = scene;
  38895. if (!s.__fontTextureCache__) {
  38896. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  38897. }
  38898. var dic = s.__fontTextureCache__;
  38899. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  38900. var ft = dic.get(lfn);
  38901. if (ft) {
  38902. ++ft._usedCounter;
  38903. return ft;
  38904. }
  38905. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  38906. ft._cachedFontId = lfn;
  38907. dic.add(lfn, ft);
  38908. return ft;
  38909. };
  38910. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  38911. if (supersample === void 0) { supersample = false; }
  38912. if (signedDistanceField === void 0) { signedDistanceField = false; }
  38913. var s = scene;
  38914. var dic = s.__fontTextureCache__;
  38915. if (!dic) {
  38916. return;
  38917. }
  38918. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  38919. var font = dic.get(lfn);
  38920. if (--font._usedCounter === 0) {
  38921. dic.remove(lfn);
  38922. font.dispose();
  38923. }
  38924. };
  38925. /**
  38926. * Make sure the given char is present in the font map.
  38927. * @param char the character to get or add
  38928. * @return the CharInfo instance corresponding to the given character
  38929. */
  38930. FontTexture.prototype.getChar = function (char) {
  38931. if (char.length !== 1) {
  38932. return null;
  38933. }
  38934. var info = this._charInfos[char];
  38935. if (info) {
  38936. return info;
  38937. }
  38938. info = new CharInfo();
  38939. var measure = this._context.measureText(char);
  38940. var textureSize = this.getSize();
  38941. // we reached the end of the current line?
  38942. var width = Math.round(measure.width);
  38943. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  38944. this._currentFreePosition.x = 0;
  38945. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  38946. // No more room?
  38947. if (this._currentFreePosition.y > textureSize.height) {
  38948. return this.getChar("!");
  38949. }
  38950. }
  38951. // In sdf mode we render the character in an intermediate 2D context which scale the character this._sdfScale times (which is required to compute the sdf map accurately)
  38952. if (this._signedDistanceField) {
  38953. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  38954. this._sdfContext.fillText(char, 0, -this._offset);
  38955. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  38956. var res = this._computeSDFChar(data);
  38957. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  38958. }
  38959. else {
  38960. // Draw the character in the HTML canvas
  38961. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  38962. }
  38963. // Fill the CharInfo object
  38964. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  38965. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  38966. if (this._signedDistanceField) {
  38967. var off = 1 / textureSize.width;
  38968. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  38969. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  38970. }
  38971. info.charWidth = this._superSample ? (width / 2) : width;
  38972. // Add the info structure
  38973. this._charInfos[char] = info;
  38974. this._curCharCount++;
  38975. // Set the next position
  38976. this._currentFreePosition.x += width + this._xMargin;
  38977. return info;
  38978. };
  38979. FontTexture.prototype._computeSDFChar = function (source) {
  38980. var scl = this._sdfScale;
  38981. var sw = source.width;
  38982. var sh = source.height;
  38983. var dw = sw / scl;
  38984. var dh = sh / scl;
  38985. var roffx = 0;
  38986. var roffy = 0;
  38987. // We shouldn't look beyond half of the biggest between width and height
  38988. var radius = scl;
  38989. var br = radius - 1;
  38990. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  38991. var sx = dx * scl;
  38992. var sy = dy * scl;
  38993. // Looking out of the area? return true to make the test going on
  38994. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  38995. return true;
  38996. }
  38997. // Get the pixel we want
  38998. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  38999. var res = (val > 0) === lookVis;
  39000. if (!res) {
  39001. roffx = offX;
  39002. roffy = offY;
  39003. }
  39004. return res;
  39005. };
  39006. var lookupArea = function (dx, dy, lookVis) {
  39007. // Fast rejection test, if we have the same result in N, S, W, E at a distance which is the radius-1 then it means the data will be consistent in this area. That's because we've scale the rendering of the letter "radius" times, so a letter's pixel will be at least radius wide
  39008. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  39009. lookupSrc(dx, dy, 0, -br, lookVis) &&
  39010. lookupSrc(dx, dy, -br, 0, lookVis) &&
  39011. lookupSrc(dx, dy, br, 0, lookVis)) {
  39012. return 0;
  39013. }
  39014. for (var i = 1; i <= radius; i++) {
  39015. // Quick test N, S, W, E
  39016. if (!lookupSrc(dx, dy, 0, i, lookVis) || !lookupSrc(dx, dy, 0, -i, lookVis) || !lookupSrc(dx, dy, -i, 0, lookVis) || !lookupSrc(dx, dy, i, 0, lookVis)) {
  39017. return i * i; // Squared Distance is simple to compute in this case
  39018. }
  39019. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  39020. for (var j = 1; j <= i; j++) {
  39021. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  39022. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  39023. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  39024. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  39025. // We found the nearest texel having and opposite state, store the squared length
  39026. var res_1 = (i * i) + (j * j);
  39027. var count = 1;
  39028. // To improve quality we will sample the texels around this one, so it's 8 samples, we consider only the one having an opposite state, add them to the current res and will will compute the average at the end
  39029. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  39030. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  39031. ++count;
  39032. }
  39033. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  39034. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  39035. ++count;
  39036. }
  39037. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  39038. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  39039. ++count;
  39040. }
  39041. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  39042. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  39043. ++count;
  39044. }
  39045. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  39046. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  39047. ++count;
  39048. }
  39049. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  39050. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  39051. ++count;
  39052. }
  39053. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  39054. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  39055. ++count;
  39056. }
  39057. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  39058. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  39059. ++count;
  39060. }
  39061. // Compute the average based on the accumulated distance
  39062. return res_1 / count;
  39063. }
  39064. }
  39065. }
  39066. return 0;
  39067. };
  39068. var tmp = new Array(dw * dh);
  39069. for (var y = 0; y < dh; y++) {
  39070. for (var x = 0; x < dw; x++) {
  39071. var curState = lookupSrc(x, y, 0, 0, true);
  39072. var d = lookupArea(x, y, curState);
  39073. if (d === 0) {
  39074. d = radius * radius * 2;
  39075. }
  39076. tmp[(y * dw) + x] = curState ? d : -d;
  39077. }
  39078. }
  39079. var res = this._context.createImageData(dw, dh);
  39080. var size = dw * dh;
  39081. for (var j = 0; j < size; j++) {
  39082. var d = tmp[j];
  39083. var sign = (d < 0) ? -1 : 1;
  39084. d = Math.sqrt(Math.abs(d)) * sign;
  39085. d *= 127.5 / radius;
  39086. d += 127.5;
  39087. if (d < 0) {
  39088. d = 0;
  39089. }
  39090. else if (d > 255) {
  39091. d = 255;
  39092. }
  39093. d += 0.5;
  39094. res.data[j * 4 + 0] = d;
  39095. res.data[j * 4 + 1] = d;
  39096. res.data[j * 4 + 2] = d;
  39097. res.data[j * 4 + 3] = 255;
  39098. }
  39099. return res;
  39100. };
  39101. FontTexture.prototype.measureText = function (text, tabulationSize) {
  39102. if (tabulationSize === void 0) { tabulationSize = 4; }
  39103. var maxWidth = 0;
  39104. var curWidth = 0;
  39105. var lineCount = 1;
  39106. var charxpos = 0;
  39107. // Parse each char of the string
  39108. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  39109. var char = text_1[_i];
  39110. // Next line feed?
  39111. if (char === "\n") {
  39112. maxWidth = Math.max(maxWidth, curWidth);
  39113. charxpos = 0;
  39114. curWidth = 0;
  39115. ++lineCount;
  39116. continue;
  39117. }
  39118. // Tabulation ?
  39119. if (char === "\t") {
  39120. var nextPos = charxpos + tabulationSize;
  39121. nextPos = nextPos - (nextPos % tabulationSize);
  39122. curWidth += (nextPos - charxpos) * this.spaceWidth;
  39123. charxpos = nextPos;
  39124. continue;
  39125. }
  39126. if (char < " ") {
  39127. continue;
  39128. }
  39129. curWidth += this.getChar(char).charWidth;
  39130. ++charxpos;
  39131. }
  39132. maxWidth = Math.max(maxWidth, curWidth);
  39133. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  39134. };
  39135. FontTexture.prototype.getSuperSampleFont = function (font) {
  39136. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  39137. var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
  39138. var res = font.toLocaleLowerCase().match(regex);
  39139. if (res == null) {
  39140. return null;
  39141. }
  39142. var size = parseInt(res[4]);
  39143. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  39144. var newFont = "";
  39145. for (var j = 1; j < res.length; j++) {
  39146. if (res[j] != null) {
  39147. newFont += res[j] + " ";
  39148. }
  39149. }
  39150. return newFont;
  39151. };
  39152. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  39153. FontTexture.prototype.getFontHeight = function (font) {
  39154. var fontDraw = document.createElement("canvas");
  39155. var ctx = fontDraw.getContext('2d');
  39156. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  39157. ctx.textBaseline = 'top';
  39158. ctx.fillStyle = 'white';
  39159. ctx.font = font;
  39160. ctx.fillText('jH|', 0, 0);
  39161. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  39162. var start = -1;
  39163. var end = -1;
  39164. for (var row = 0; row < fontDraw.height; row++) {
  39165. for (var column = 0; column < fontDraw.width; column++) {
  39166. var index = (row * fontDraw.width + column) * 4;
  39167. if (pixels[index] === 0) {
  39168. if (column === fontDraw.width - 1 && start !== -1) {
  39169. end = row;
  39170. row = fontDraw.height;
  39171. break;
  39172. }
  39173. continue;
  39174. }
  39175. else {
  39176. if (start === -1) {
  39177. start = row;
  39178. }
  39179. break;
  39180. }
  39181. }
  39182. }
  39183. return { height: (end - start) + 1, offset: start - 1 };
  39184. };
  39185. Object.defineProperty(FontTexture.prototype, "canRescale", {
  39186. get: function () {
  39187. return false;
  39188. },
  39189. enumerable: true,
  39190. configurable: true
  39191. });
  39192. FontTexture.prototype.getContext = function () {
  39193. return this._context;
  39194. };
  39195. /**
  39196. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  39197. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  39198. */
  39199. FontTexture.prototype.update = function () {
  39200. // Update only if there's new char added since the previous update
  39201. if (this._lastUpdateCharCount < this._curCharCount) {
  39202. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  39203. this._lastUpdateCharCount = this._curCharCount;
  39204. }
  39205. };
  39206. // cloning should be prohibited, there's no point to duplicate this texture at all
  39207. FontTexture.prototype.clone = function () {
  39208. return null;
  39209. };
  39210. /**
  39211. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  39212. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  39213. */
  39214. FontTexture.prototype.incCachedFontTextureCounter = function () {
  39215. ++this._usedCounter;
  39216. };
  39217. /**
  39218. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  39219. */
  39220. FontTexture.prototype.decCachedFontTextureCounter = function () {
  39221. var s = this.getScene();
  39222. var dic = s.__fontTextureCache__;
  39223. if (!dic) {
  39224. return;
  39225. }
  39226. if (--this._usedCounter === 0) {
  39227. dic.remove(this._cachedFontId);
  39228. this.dispose();
  39229. }
  39230. };
  39231. return FontTexture;
  39232. }(BABYLON.Texture));
  39233. BABYLON.FontTexture = FontTexture;
  39234. })(BABYLON || (BABYLON = {}));
  39235. var BABYLON;
  39236. (function (BABYLON) {
  39237. var MapTexture = (function (_super) {
  39238. __extends(MapTexture, _super);
  39239. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  39240. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39241. if (useMipMap === void 0) { useMipMap = false; }
  39242. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  39243. this.name = name;
  39244. this._size = size;
  39245. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39246. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39247. // Create the rectPackMap that will allocate portion of the texture
  39248. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  39249. // Create the texture that will store the content
  39250. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  39251. }
  39252. /**
  39253. * Allocate a rectangle of a given size in the texture map
  39254. * @param size the size of the rectangle to allocation
  39255. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  39256. */
  39257. MapTexture.prototype.allocateRect = function (size) {
  39258. return this._rectPackingMap.addRect(size);
  39259. };
  39260. /**
  39261. * Free a given rectangle from the texture map
  39262. * @param rectInfo the instance corresponding to the rect to free.
  39263. */
  39264. MapTexture.prototype.freeRect = function (rectInfo) {
  39265. if (rectInfo) {
  39266. rectInfo.freeContent();
  39267. }
  39268. };
  39269. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  39270. /**
  39271. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  39272. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  39273. * @returns {}
  39274. */
  39275. get: function () {
  39276. return this._rectPackingMap.freeSpace;
  39277. },
  39278. enumerable: true,
  39279. configurable: true
  39280. });
  39281. /**
  39282. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  39283. * 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.
  39284. * Don't forget to call unbindTexture when you're done rendering
  39285. * @param rect the zone to render to
  39286. * @param clear true to clear the portion's color/depth data
  39287. */
  39288. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  39289. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  39290. };
  39291. /**
  39292. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  39293. * 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.
  39294. * Don't forget to call unbindTexture when you're done rendering
  39295. * @param pos the position into the texture
  39296. * @param size the portion to fit the clip space to
  39297. * @param clear true to clear the portion's color/depth data
  39298. */
  39299. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  39300. var engine = this.getScene().getEngine();
  39301. engine.bindFramebuffer(this._texture);
  39302. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  39303. if (clear) {
  39304. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  39305. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  39306. }
  39307. };
  39308. /**
  39309. * Unbind the texture map from the rendering engine.
  39310. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  39311. * @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.
  39312. */
  39313. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  39314. // Dump ?
  39315. if (dumpForDebug) {
  39316. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  39317. }
  39318. var engine = this.getScene().getEngine();
  39319. if (this._replacedViewport) {
  39320. engine.setViewport(this._replacedViewport);
  39321. this._replacedViewport = null;
  39322. }
  39323. engine.unBindFramebuffer(this._texture);
  39324. };
  39325. Object.defineProperty(MapTexture.prototype, "canRescale", {
  39326. get: function () {
  39327. return false;
  39328. },
  39329. enumerable: true,
  39330. configurable: true
  39331. });
  39332. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  39333. // Anyway, there's not much point to use this method for this kind of texture I guess
  39334. MapTexture.prototype.clone = function () {
  39335. return null;
  39336. };
  39337. return MapTexture;
  39338. }(BABYLON.Texture));
  39339. BABYLON.MapTexture = MapTexture;
  39340. })(BABYLON || (BABYLON = {}));
  39341. var BABYLON;
  39342. (function (BABYLON) {
  39343. var ShaderMaterial = (function (_super) {
  39344. __extends(ShaderMaterial, _super);
  39345. function ShaderMaterial(name, scene, shaderPath, options) {
  39346. _super.call(this, name, scene);
  39347. this._textures = {};
  39348. this._textureArrays = {};
  39349. this._floats = {};
  39350. this._floatsArrays = {};
  39351. this._colors3 = {};
  39352. this._colors4 = {};
  39353. this._vectors2 = {};
  39354. this._vectors3 = {};
  39355. this._vectors4 = {};
  39356. this._matrices = {};
  39357. this._matrices3x3 = {};
  39358. this._matrices2x2 = {};
  39359. this._vectors3Arrays = {};
  39360. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39361. this._shaderPath = shaderPath;
  39362. options.needAlphaBlending = options.needAlphaBlending || false;
  39363. options.needAlphaTesting = options.needAlphaTesting || false;
  39364. options.attributes = options.attributes || ["position", "normal", "uv"];
  39365. options.uniforms = options.uniforms || ["worldViewProjection"];
  39366. options.samplers = options.samplers || [];
  39367. options.defines = options.defines || [];
  39368. this._options = options;
  39369. }
  39370. ShaderMaterial.prototype.needAlphaBlending = function () {
  39371. return this._options.needAlphaBlending;
  39372. };
  39373. ShaderMaterial.prototype.needAlphaTesting = function () {
  39374. return this._options.needAlphaTesting;
  39375. };
  39376. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39377. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39378. this._options.uniforms.push(uniformName);
  39379. }
  39380. };
  39381. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39382. if (this._options.samplers.indexOf(name) === -1) {
  39383. this._options.samplers.push(name);
  39384. }
  39385. this._textures[name] = texture;
  39386. return this;
  39387. };
  39388. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39389. if (this._options.samplers.indexOf(name) === -1) {
  39390. this._options.samplers.push(name);
  39391. }
  39392. this._checkUniform(name);
  39393. this._textureArrays[name] = textures;
  39394. return this;
  39395. };
  39396. ShaderMaterial.prototype.setFloat = function (name, value) {
  39397. this._checkUniform(name);
  39398. this._floats[name] = value;
  39399. return this;
  39400. };
  39401. ShaderMaterial.prototype.setFloats = function (name, value) {
  39402. this._checkUniform(name);
  39403. this._floatsArrays[name] = value;
  39404. return this;
  39405. };
  39406. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39407. this._checkUniform(name);
  39408. this._colors3[name] = value;
  39409. return this;
  39410. };
  39411. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39412. this._checkUniform(name);
  39413. this._colors4[name] = value;
  39414. return this;
  39415. };
  39416. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39417. this._checkUniform(name);
  39418. this._vectors2[name] = value;
  39419. return this;
  39420. };
  39421. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39422. this._checkUniform(name);
  39423. this._vectors3[name] = value;
  39424. return this;
  39425. };
  39426. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39427. this._checkUniform(name);
  39428. this._vectors4[name] = value;
  39429. return this;
  39430. };
  39431. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39432. this._checkUniform(name);
  39433. this._matrices[name] = value;
  39434. return this;
  39435. };
  39436. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39437. this._checkUniform(name);
  39438. this._matrices3x3[name] = value;
  39439. return this;
  39440. };
  39441. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39442. this._checkUniform(name);
  39443. this._matrices2x2[name] = value;
  39444. return this;
  39445. };
  39446. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39447. this._checkUniform(name);
  39448. this._vectors3Arrays[name] = value;
  39449. return this;
  39450. };
  39451. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39452. var scene = this.getScene();
  39453. var engine = scene.getEngine();
  39454. if (!this.checkReadyOnEveryCall) {
  39455. if (this._renderId === scene.getRenderId()) {
  39456. return true;
  39457. }
  39458. }
  39459. // Instances
  39460. var defines = [];
  39461. var fallbacks = new BABYLON.EffectFallbacks();
  39462. if (useInstances) {
  39463. defines.push("#define INSTANCES");
  39464. }
  39465. for (var index = 0; index < this._options.defines.length; index++) {
  39466. defines.push(this._options.defines[index]);
  39467. }
  39468. // Bones
  39469. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39470. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39471. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39472. fallbacks.addCPUSkinningFallback(0, mesh);
  39473. }
  39474. // Alpha test
  39475. if (engine.getAlphaTesting()) {
  39476. defines.push("#define ALPHATEST");
  39477. }
  39478. var previousEffect = this._effect;
  39479. var join = defines.join("\n");
  39480. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  39481. if (!this._effect.isReady()) {
  39482. return false;
  39483. }
  39484. if (previousEffect !== this._effect) {
  39485. scene.resetCachedMaterial();
  39486. }
  39487. this._renderId = scene.getRenderId();
  39488. return true;
  39489. };
  39490. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39491. var scene = this.getScene();
  39492. if (this._options.uniforms.indexOf("world") !== -1) {
  39493. this._effect.setMatrix("world", world);
  39494. }
  39495. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39496. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39497. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39498. }
  39499. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39500. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39501. }
  39502. };
  39503. ShaderMaterial.prototype.bind = function (world, mesh) {
  39504. // Std values
  39505. this.bindOnlyWorldMatrix(world);
  39506. if (this.getScene().getCachedMaterial() !== this) {
  39507. if (this._options.uniforms.indexOf("view") !== -1) {
  39508. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39509. }
  39510. if (this._options.uniforms.indexOf("projection") !== -1) {
  39511. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39512. }
  39513. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39514. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39515. }
  39516. // Bones
  39517. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39518. var name;
  39519. // Texture
  39520. for (name in this._textures) {
  39521. this._effect.setTexture(name, this._textures[name]);
  39522. }
  39523. // Texture arrays
  39524. for (name in this._textureArrays) {
  39525. this._effect.setTextureArray(name, this._textureArrays[name]);
  39526. }
  39527. // Float
  39528. for (name in this._floats) {
  39529. this._effect.setFloat(name, this._floats[name]);
  39530. }
  39531. // Float s
  39532. for (name in this._floatsArrays) {
  39533. this._effect.setArray(name, this._floatsArrays[name]);
  39534. }
  39535. // Color3
  39536. for (name in this._colors3) {
  39537. this._effect.setColor3(name, this._colors3[name]);
  39538. }
  39539. // Color4
  39540. for (name in this._colors4) {
  39541. var color = this._colors4[name];
  39542. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39543. }
  39544. // Vector2
  39545. for (name in this._vectors2) {
  39546. this._effect.setVector2(name, this._vectors2[name]);
  39547. }
  39548. // Vector3
  39549. for (name in this._vectors3) {
  39550. this._effect.setVector3(name, this._vectors3[name]);
  39551. }
  39552. // Vector4
  39553. for (name in this._vectors4) {
  39554. this._effect.setVector4(name, this._vectors4[name]);
  39555. }
  39556. // Matrix
  39557. for (name in this._matrices) {
  39558. this._effect.setMatrix(name, this._matrices[name]);
  39559. }
  39560. // Matrix 3x3
  39561. for (name in this._matrices3x3) {
  39562. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39563. }
  39564. // Matrix 2x2
  39565. for (name in this._matrices2x2) {
  39566. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39567. }
  39568. // Vector3Array
  39569. for (name in this._vectors3Arrays) {
  39570. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39571. }
  39572. }
  39573. _super.prototype.bind.call(this, world, mesh);
  39574. };
  39575. ShaderMaterial.prototype.clone = function (name) {
  39576. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39577. return newShaderMaterial;
  39578. };
  39579. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39580. if (forceDisposeTextures) {
  39581. var name;
  39582. for (name in this._textures) {
  39583. this._textures[name].dispose();
  39584. }
  39585. for (name in this._textureArrays) {
  39586. var array = this._textureArrays[name];
  39587. for (var index = 0; index < array.length; index++) {
  39588. array[index].dispose();
  39589. }
  39590. }
  39591. }
  39592. this._textures = {};
  39593. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39594. };
  39595. ShaderMaterial.prototype.serialize = function () {
  39596. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39597. serializationObject.customType = "BABYLON.ShaderMaterial";
  39598. serializationObject.options = this._options;
  39599. serializationObject.shaderPath = this._shaderPath;
  39600. var name;
  39601. // Texture
  39602. serializationObject.textures = {};
  39603. for (name in this._textures) {
  39604. serializationObject.textures[name] = this._textures[name].serialize();
  39605. }
  39606. // Texture arrays
  39607. serializationObject.textureArrays = {};
  39608. for (name in this._textureArrays) {
  39609. serializationObject.textureArrays[name] = [];
  39610. var array = this._textureArrays[name];
  39611. for (var index = 0; index < array.length; index++) {
  39612. serializationObject.textureArrays[name].push(array[index].serialize());
  39613. }
  39614. }
  39615. // Float
  39616. serializationObject.floats = {};
  39617. for (name in this._floats) {
  39618. serializationObject.floats[name] = this._floats[name];
  39619. }
  39620. // Float s
  39621. serializationObject.floatArrays = {};
  39622. for (name in this._floatsArrays) {
  39623. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39624. }
  39625. // Color3
  39626. serializationObject.colors3 = {};
  39627. for (name in this._colors3) {
  39628. serializationObject.colors3[name] = this._colors3[name].asArray();
  39629. }
  39630. // Color4
  39631. serializationObject.colors4 = {};
  39632. for (name in this._colors4) {
  39633. serializationObject.colors4[name] = this._colors4[name].asArray();
  39634. }
  39635. // Vector2
  39636. serializationObject.vectors2 = {};
  39637. for (name in this._vectors2) {
  39638. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39639. }
  39640. // Vector3
  39641. serializationObject.vectors3 = {};
  39642. for (name in this._vectors3) {
  39643. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39644. }
  39645. // Vector4
  39646. serializationObject.vectors4 = {};
  39647. for (name in this._vectors4) {
  39648. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39649. }
  39650. // Matrix
  39651. serializationObject.matrices = {};
  39652. for (name in this._matrices) {
  39653. serializationObject.matrices[name] = this._matrices[name].asArray();
  39654. }
  39655. // Matrix 3x3
  39656. serializationObject.matrices3x3 = {};
  39657. for (name in this._matrices3x3) {
  39658. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39659. }
  39660. // Matrix 2x2
  39661. serializationObject.matrices2x2 = {};
  39662. for (name in this._matrices2x2) {
  39663. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39664. }
  39665. // Vector3Array
  39666. serializationObject.vectors3Arrays = {};
  39667. for (name in this._vectors3Arrays) {
  39668. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  39669. }
  39670. return serializationObject;
  39671. };
  39672. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39673. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39674. var name;
  39675. // Texture
  39676. for (name in source.textures) {
  39677. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39678. }
  39679. // Texture arrays
  39680. for (name in source.textureArrays) {
  39681. var array = source.textureArrays[name];
  39682. var textureArray = new Array();
  39683. for (var index = 0; index < array.length; index++) {
  39684. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  39685. }
  39686. material.setTextureArray(name, textureArray);
  39687. }
  39688. // Float
  39689. for (name in source.floats) {
  39690. material.setFloat(name, source.floats[name]);
  39691. }
  39692. // Float s
  39693. for (name in source.floatsArrays) {
  39694. material.setFloats(name, source.floatsArrays[name]);
  39695. }
  39696. // Color3
  39697. for (name in source.colors3) {
  39698. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  39699. }
  39700. // Color4
  39701. for (name in source.colors4) {
  39702. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  39703. }
  39704. // Vector2
  39705. for (name in source.vectors2) {
  39706. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  39707. }
  39708. // Vector3
  39709. for (name in source.vectors3) {
  39710. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  39711. }
  39712. // Vector4
  39713. for (name in source.vectors4) {
  39714. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  39715. }
  39716. // Matrix
  39717. for (name in source.matrices) {
  39718. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  39719. }
  39720. // Matrix 3x3
  39721. for (name in source.matrices3x3) {
  39722. material.setMatrix3x3(name, source.matrices3x3[name]);
  39723. }
  39724. // Matrix 2x2
  39725. for (name in source.matrices2x2) {
  39726. material.setMatrix2x2(name, source.matrices2x2[name]);
  39727. }
  39728. // Vector3Array
  39729. for (name in source.vectors3Arrays) {
  39730. material.setArray3(name, source.vectors3Arrays[name]);
  39731. }
  39732. return material;
  39733. };
  39734. return ShaderMaterial;
  39735. }(BABYLON.Material));
  39736. BABYLON.ShaderMaterial = ShaderMaterial;
  39737. })(BABYLON || (BABYLON = {}));
  39738. var BABYLON;
  39739. (function (BABYLON) {
  39740. var Internals;
  39741. (function (Internals) {
  39742. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  39743. // All values and structures referenced from:
  39744. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  39745. var DDS_MAGIC = 0x20534444;
  39746. 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;
  39747. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  39748. 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;
  39749. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  39750. function FourCCToInt32(value) {
  39751. return value.charCodeAt(0) +
  39752. (value.charCodeAt(1) << 8) +
  39753. (value.charCodeAt(2) << 16) +
  39754. (value.charCodeAt(3) << 24);
  39755. }
  39756. function Int32ToFourCC(value) {
  39757. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  39758. }
  39759. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  39760. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  39761. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  39762. var headerLengthInt = 31; // The header length in 32 bit ints
  39763. // Offsets into the header array
  39764. var off_magic = 0;
  39765. var off_size = 1;
  39766. var off_flags = 2;
  39767. var off_height = 3;
  39768. var off_width = 4;
  39769. var off_mipmapCount = 7;
  39770. var off_pfFlags = 20;
  39771. var off_pfFourCC = 21;
  39772. var off_RGBbpp = 22;
  39773. var off_RMask = 23;
  39774. var off_GMask = 24;
  39775. var off_BMask = 25;
  39776. var off_AMask = 26;
  39777. var off_caps1 = 27;
  39778. var off_caps2 = 28;
  39779. ;
  39780. var DDSTools = (function () {
  39781. function DDSTools() {
  39782. }
  39783. DDSTools.GetDDSInfo = function (arrayBuffer) {
  39784. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  39785. var mipmapCount = 1;
  39786. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  39787. mipmapCount = Math.max(1, header[off_mipmapCount]);
  39788. }
  39789. return {
  39790. width: header[off_width],
  39791. height: header[off_height],
  39792. mipmapCount: mipmapCount,
  39793. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  39794. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  39795. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  39796. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  39797. };
  39798. };
  39799. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39800. var byteArray = new Uint8Array(dataLength);
  39801. var srcData = new Uint8Array(arrayBuffer);
  39802. var index = 0;
  39803. for (var y = height - 1; y >= 0; y--) {
  39804. for (var x = 0; x < width; x++) {
  39805. var srcPos = dataOffset + (x + y * width) * 4;
  39806. byteArray[index + 2] = srcData[srcPos];
  39807. byteArray[index + 1] = srcData[srcPos + 1];
  39808. byteArray[index] = srcData[srcPos + 2];
  39809. byteArray[index + 3] = srcData[srcPos + 3];
  39810. index += 4;
  39811. }
  39812. }
  39813. return byteArray;
  39814. };
  39815. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39816. var byteArray = new Uint8Array(dataLength);
  39817. var srcData = new Uint8Array(arrayBuffer);
  39818. var index = 0;
  39819. for (var y = height - 1; y >= 0; y--) {
  39820. for (var x = 0; x < width; x++) {
  39821. var srcPos = dataOffset + (x + y * width) * 3;
  39822. byteArray[index + 2] = srcData[srcPos];
  39823. byteArray[index + 1] = srcData[srcPos + 1];
  39824. byteArray[index] = srcData[srcPos + 2];
  39825. index += 3;
  39826. }
  39827. }
  39828. return byteArray;
  39829. };
  39830. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39831. var byteArray = new Uint8Array(dataLength);
  39832. var srcData = new Uint8Array(arrayBuffer);
  39833. var index = 0;
  39834. for (var y = height - 1; y >= 0; y--) {
  39835. for (var x = 0; x < width; x++) {
  39836. var srcPos = dataOffset + (x + y * width);
  39837. byteArray[index] = srcData[srcPos];
  39838. index++;
  39839. }
  39840. }
  39841. return byteArray;
  39842. };
  39843. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  39844. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  39845. if (header[off_magic] != DDS_MAGIC) {
  39846. BABYLON.Tools.Error("Invalid magic number in DDS header");
  39847. return;
  39848. }
  39849. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  39850. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  39851. return;
  39852. }
  39853. if (info.isFourCC) {
  39854. fourCC = header[off_pfFourCC];
  39855. switch (fourCC) {
  39856. case FOURCC_DXT1:
  39857. blockBytes = 8;
  39858. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39859. break;
  39860. case FOURCC_DXT3:
  39861. blockBytes = 16;
  39862. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39863. break;
  39864. case FOURCC_DXT5:
  39865. blockBytes = 16;
  39866. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39867. break;
  39868. default:
  39869. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  39870. return;
  39871. }
  39872. }
  39873. mipmapCount = 1;
  39874. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  39875. mipmapCount = Math.max(1, header[off_mipmapCount]);
  39876. }
  39877. var bpp = header[off_RGBbpp];
  39878. for (var face = 0; face < faces; face++) {
  39879. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  39880. width = header[off_width];
  39881. height = header[off_height];
  39882. dataOffset = header[off_size] + 4;
  39883. for (i = 0; i < mipmapCount; ++i) {
  39884. if (info.isRGB) {
  39885. if (bpp === 24) {
  39886. dataLength = width * height * 3;
  39887. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39888. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  39889. }
  39890. else {
  39891. dataLength = width * height * 4;
  39892. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39893. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  39894. }
  39895. }
  39896. else if (info.isLuminance) {
  39897. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  39898. var unpaddedRowSize = width;
  39899. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  39900. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  39901. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39902. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  39903. }
  39904. else {
  39905. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  39906. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  39907. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  39908. }
  39909. dataOffset += dataLength;
  39910. width *= 0.5;
  39911. height *= 0.5;
  39912. width = Math.max(1.0, width);
  39913. height = Math.max(1.0, height);
  39914. }
  39915. }
  39916. };
  39917. return DDSTools;
  39918. }());
  39919. Internals.DDSTools = DDSTools;
  39920. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39921. })(BABYLON || (BABYLON = {}));
  39922. var BABYLON;
  39923. (function (BABYLON) {
  39924. var CannonJSPlugin = (function () {
  39925. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  39926. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  39927. if (iterations === void 0) { iterations = 10; }
  39928. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  39929. this.name = "CannonJSPlugin";
  39930. this._physicsMaterials = [];
  39931. this._fixedTimeStep = 1 / 60;
  39932. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  39933. this._currentCollisionGroup = 2;
  39934. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  39935. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  39936. this._tmpPosition = BABYLON.Vector3.Zero();
  39937. this._tmpQuaternion = new BABYLON.Quaternion();
  39938. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  39939. this._tmpDeltaRotation = new BABYLON.Quaternion();
  39940. this._tmpUnityRotation = new BABYLON.Quaternion();
  39941. if (!this.isSupported()) {
  39942. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  39943. return;
  39944. }
  39945. this.world = new CANNON.World();
  39946. this.world.broadphase = new CANNON.NaiveBroadphase();
  39947. this.world.solver.iterations = iterations;
  39948. }
  39949. CannonJSPlugin.prototype.setGravity = function (gravity) {
  39950. this.world.gravity.copy(gravity);
  39951. };
  39952. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  39953. this._fixedTimeStep = timeStep;
  39954. };
  39955. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  39956. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  39957. };
  39958. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  39959. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  39960. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  39961. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  39962. };
  39963. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  39964. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  39965. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  39966. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  39967. };
  39968. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  39969. //parent-child relationship. Does this impostor has a parent impostor?
  39970. if (impostor.parent) {
  39971. if (impostor.physicsBody) {
  39972. this.removePhysicsBody(impostor);
  39973. //TODO is that needed?
  39974. impostor.forceUpdate();
  39975. }
  39976. return;
  39977. }
  39978. //should a new body be created for this impostor?
  39979. if (impostor.isBodyInitRequired()) {
  39980. var shape = this._createShape(impostor);
  39981. //unregister events, if body is being changed
  39982. var oldBody = impostor.physicsBody;
  39983. if (oldBody) {
  39984. this.removePhysicsBody(impostor);
  39985. }
  39986. //create the body and material
  39987. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  39988. var bodyCreationObject = {
  39989. mass: impostor.getParam("mass"),
  39990. material: material
  39991. };
  39992. // A simple extend, in case native options were used.
  39993. var nativeOptions = impostor.getParam("nativeOptions");
  39994. for (var key in nativeOptions) {
  39995. if (nativeOptions.hasOwnProperty(key)) {
  39996. bodyCreationObject[key] = nativeOptions[key];
  39997. }
  39998. }
  39999. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  40000. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  40001. this.world.addEventListener("preStep", impostor.beforeStep);
  40002. this.world.addEventListener("postStep", impostor.afterStep);
  40003. impostor.physicsBody.addShape(shape);
  40004. this.world.add(impostor.physicsBody);
  40005. //try to keep the body moving in the right direction by taking old properties.
  40006. //Should be tested!
  40007. if (oldBody) {
  40008. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  40009. impostor.physicsBody[param].copy(oldBody[param]);
  40010. });
  40011. }
  40012. this._processChildMeshes(impostor);
  40013. }
  40014. //now update the body's transformation
  40015. this._updatePhysicsBodyTransformation(impostor);
  40016. };
  40017. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  40018. var _this = this;
  40019. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  40020. if (meshChildren.length) {
  40021. var processMesh = function (localPosition, mesh) {
  40022. var childImpostor = mesh.getPhysicsImpostor();
  40023. if (childImpostor) {
  40024. var parent = childImpostor.parent;
  40025. if (parent !== mainImpostor) {
  40026. var localPosition = mesh.position;
  40027. if (childImpostor.physicsBody) {
  40028. _this.removePhysicsBody(childImpostor);
  40029. childImpostor.physicsBody = null;
  40030. }
  40031. childImpostor.parent = mainImpostor;
  40032. childImpostor.resetUpdateFlags();
  40033. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  40034. //Add the mass of the children.
  40035. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  40036. }
  40037. }
  40038. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  40039. };
  40040. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  40041. }
  40042. };
  40043. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  40044. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  40045. this.world.removeEventListener("preStep", impostor.beforeStep);
  40046. this.world.removeEventListener("postStep", impostor.afterStep);
  40047. this.world.remove(impostor.physicsBody);
  40048. };
  40049. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  40050. var mainBody = impostorJoint.mainImpostor.physicsBody;
  40051. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  40052. if (!mainBody || !connectedBody) {
  40053. return;
  40054. }
  40055. var constraint;
  40056. var jointData = impostorJoint.joint.jointData;
  40057. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  40058. var constraintData = {
  40059. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  40060. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  40061. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  40062. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  40063. maxForce: jointData.nativeParams.maxForce,
  40064. collideConnected: !!jointData.collision
  40065. };
  40066. //Not needed, Cannon has a collideConnected flag
  40067. /*if (!jointData.collision) {
  40068. //add 1st body to a collision group of its own, if it is not in 1
  40069. if (mainBody.collisionFilterGroup === 1) {
  40070. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  40071. this._currentCollisionGroup <<= 1;
  40072. }
  40073. if (connectedBody.collisionFilterGroup === 1) {
  40074. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  40075. this._currentCollisionGroup <<= 1;
  40076. }
  40077. //add their mask to the collisionFilterMask of each other:
  40078. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  40079. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  40080. }*/
  40081. switch (impostorJoint.joint.type) {
  40082. case BABYLON.PhysicsJoint.HingeJoint:
  40083. case BABYLON.PhysicsJoint.Hinge2Joint:
  40084. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  40085. break;
  40086. case BABYLON.PhysicsJoint.DistanceJoint:
  40087. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  40088. break;
  40089. case BABYLON.PhysicsJoint.SpringJoint:
  40090. var springData = jointData;
  40091. constraint = new CANNON.Spring(mainBody, connectedBody, {
  40092. restLength: springData.length,
  40093. stiffness: springData.stiffness,
  40094. damping: springData.damping,
  40095. localAnchorA: constraintData.pivotA,
  40096. localAnchorB: constraintData.pivotB
  40097. });
  40098. break;
  40099. case BABYLON.PhysicsJoint.LockJoint:
  40100. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  40101. break;
  40102. case BABYLON.PhysicsJoint.PointToPointJoint:
  40103. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  40104. default:
  40105. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  40106. break;
  40107. }
  40108. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  40109. constraint.collideConnected = !!jointData.collision;
  40110. impostorJoint.joint.physicsJoint = constraint;
  40111. //don't add spring as constraint, as it is not one.
  40112. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  40113. this.world.addConstraint(constraint);
  40114. }
  40115. else {
  40116. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  40117. constraint.applyForce();
  40118. });
  40119. }
  40120. };
  40121. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  40122. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  40123. };
  40124. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  40125. var index;
  40126. var mat;
  40127. for (index = 0; index < this._physicsMaterials.length; index++) {
  40128. mat = this._physicsMaterials[index];
  40129. if (mat.friction === friction && mat.restitution === restitution) {
  40130. return mat;
  40131. }
  40132. }
  40133. var currentMat = new CANNON.Material(name);
  40134. currentMat.friction = friction;
  40135. currentMat.restitution = restitution;
  40136. this._physicsMaterials.push(currentMat);
  40137. return currentMat;
  40138. };
  40139. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  40140. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  40141. };
  40142. CannonJSPlugin.prototype._createShape = function (impostor) {
  40143. var object = impostor.object;
  40144. var returnValue;
  40145. var extendSize = impostor.getObjectExtendSize();
  40146. switch (impostor.type) {
  40147. case BABYLON.PhysicsEngine.SphereImpostor:
  40148. var radiusX = extendSize.x;
  40149. var radiusY = extendSize.y;
  40150. var radiusZ = extendSize.z;
  40151. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  40152. break;
  40153. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  40154. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40155. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  40156. break;
  40157. case BABYLON.PhysicsImpostor.BoxImpostor:
  40158. var box = extendSize.scale(0.5);
  40159. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  40160. break;
  40161. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40162. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  40163. returnValue = new CANNON.Plane();
  40164. break;
  40165. case BABYLON.PhysicsImpostor.MeshImpostor:
  40166. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  40167. var rawFaces = object.getIndices ? object.getIndices() : [];
  40168. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  40169. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  40170. break;
  40171. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  40172. returnValue = this._createHeightmap(object);
  40173. break;
  40174. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40175. returnValue = new CANNON.Particle();
  40176. break;
  40177. }
  40178. return returnValue;
  40179. };
  40180. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  40181. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40182. var matrix = [];
  40183. //For now pointDepth will not be used and will be automatically calculated.
  40184. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  40185. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  40186. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  40187. var elementSize = dim * 2 / arraySize;
  40188. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  40189. for (var i = 0; i < pos.length; i = i + 3) {
  40190. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  40191. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  40192. var y = pos[i + 1] + minY;
  40193. if (!matrix[x]) {
  40194. matrix[x] = [];
  40195. }
  40196. if (!matrix[x][z]) {
  40197. matrix[x][z] = y;
  40198. }
  40199. matrix[x][z] = Math.max(y, matrix[x][z]);
  40200. }
  40201. for (var x = 0; x <= arraySize; ++x) {
  40202. if (!matrix[x]) {
  40203. var loc = 1;
  40204. while (!matrix[(x + loc) % arraySize]) {
  40205. loc++;
  40206. }
  40207. matrix[x] = matrix[(x + loc) % arraySize].slice();
  40208. }
  40209. for (var z = 0; z <= arraySize; ++z) {
  40210. if (!matrix[x][z]) {
  40211. var loc = 1;
  40212. var newValue;
  40213. while (newValue === undefined) {
  40214. newValue = matrix[x][(z + loc++) % arraySize];
  40215. }
  40216. matrix[x][z] = newValue;
  40217. }
  40218. }
  40219. }
  40220. var shape = new CANNON.Heightfield(matrix, {
  40221. elementSize: elementSize
  40222. });
  40223. //For future reference, needed for body transformation
  40224. shape.minY = minY;
  40225. return shape;
  40226. };
  40227. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  40228. var object = impostor.object;
  40229. //make sure it is updated...
  40230. object.computeWorldMatrix && object.computeWorldMatrix(true);
  40231. // The delta between the mesh position and the mesh bounding box center
  40232. var center = impostor.getObjectCenter();
  40233. var extendSize = impostor.getObjectExtendSize();
  40234. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  40235. this._tmpPosition.copyFrom(center);
  40236. var quaternion = object.rotationQuaternion;
  40237. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  40238. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  40239. //-90 DEG in X, precalculated
  40240. quaternion = quaternion.multiply(this._minus90X);
  40241. //Invert! (Precalculated, 90 deg in X)
  40242. //No need to clone. this will never change.
  40243. impostor.setDeltaRotation(this._plus90X);
  40244. }
  40245. //If it is a heightfield, if should be centered.
  40246. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  40247. var mesh = object;
  40248. //calculate the correct body position:
  40249. var rotationQuaternion = mesh.rotationQuaternion;
  40250. mesh.rotationQuaternion = this._tmpUnityRotation;
  40251. mesh.computeWorldMatrix(true);
  40252. //get original center with no rotation
  40253. var c = center.clone();
  40254. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  40255. //rotation is back
  40256. mesh.rotationQuaternion = rotationQuaternion;
  40257. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  40258. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  40259. mesh.setPivotMatrix(p);
  40260. mesh.computeWorldMatrix(true);
  40261. //calculate the translation
  40262. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  40263. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  40264. //add it inverted to the delta
  40265. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  40266. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  40267. mesh.setPivotMatrix(oldPivot);
  40268. mesh.computeWorldMatrix(true);
  40269. }
  40270. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  40271. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  40272. this._tmpPosition.copyFrom(object.position);
  40273. }
  40274. impostor.setDeltaPosition(this._tmpDeltaPosition);
  40275. //Now update the impostor object
  40276. impostor.physicsBody.position.copy(this._tmpPosition);
  40277. impostor.physicsBody.quaternion.copy(quaternion);
  40278. };
  40279. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40280. impostor.object.position.copyFrom(impostor.physicsBody.position);
  40281. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  40282. };
  40283. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  40284. impostor.physicsBody.position.copy(newPosition);
  40285. impostor.physicsBody.quaternion.copy(newRotation);
  40286. };
  40287. CannonJSPlugin.prototype.isSupported = function () {
  40288. return window.CANNON !== undefined;
  40289. };
  40290. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  40291. impostor.physicsBody.velocity.copy(velocity);
  40292. };
  40293. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  40294. impostor.physicsBody.angularVelocity.copy(velocity);
  40295. };
  40296. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  40297. var v = impostor.physicsBody.velocity;
  40298. if (!v)
  40299. return null;
  40300. return new BABYLON.Vector3(v.x, v.y, v.z);
  40301. };
  40302. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  40303. var v = impostor.physicsBody.angularVelocity;
  40304. if (!v)
  40305. return null;
  40306. return new BABYLON.Vector3(v.x, v.y, v.z);
  40307. };
  40308. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  40309. impostor.physicsBody.mass = mass;
  40310. impostor.physicsBody.updateMassProperties();
  40311. };
  40312. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  40313. impostor.physicsBody.sleep();
  40314. };
  40315. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  40316. impostor.physicsBody.wakeUp();
  40317. };
  40318. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  40319. joint.physicsJoint.distance = maxDistance;
  40320. };
  40321. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  40322. if (!motorIndex) {
  40323. joint.physicsJoint.enableMotor();
  40324. }
  40325. };
  40326. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  40327. if (!motorIndex) {
  40328. joint.physicsJoint.disableMotor();
  40329. }
  40330. };
  40331. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  40332. if (!motorIndex) {
  40333. joint.physicsJoint.enableMotor();
  40334. joint.physicsJoint.setMotorSpeed(speed);
  40335. if (maxForce) {
  40336. this.setLimit(joint, maxForce);
  40337. }
  40338. }
  40339. };
  40340. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  40341. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  40342. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  40343. };
  40344. CannonJSPlugin.prototype.dispose = function () {
  40345. //nothing to do, actually.
  40346. };
  40347. return CannonJSPlugin;
  40348. }());
  40349. BABYLON.CannonJSPlugin = CannonJSPlugin;
  40350. })(BABYLON || (BABYLON = {}));
  40351. var BABYLON;
  40352. (function (BABYLON) {
  40353. var OimoJSPlugin = (function () {
  40354. function OimoJSPlugin(iterations) {
  40355. this.name = "OimoJSPlugin";
  40356. this._tmpImpostorsArray = [];
  40357. this._tmpPositionVector = BABYLON.Vector3.Zero();
  40358. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  40359. this.world.worldscale(1);
  40360. this.world.clear();
  40361. //making sure no stats are calculated
  40362. this.world.isNoStat = true;
  40363. }
  40364. OimoJSPlugin.prototype.setGravity = function (gravity) {
  40365. this.world.gravity.copy(gravity);
  40366. };
  40367. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  40368. this.world.timeStep = timeStep;
  40369. };
  40370. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  40371. var _this = this;
  40372. impostors.forEach(function (impostor) {
  40373. impostor.beforeStep();
  40374. });
  40375. this.world.step();
  40376. impostors.forEach(function (impostor) {
  40377. impostor.afterStep();
  40378. //update the ordered impostors array
  40379. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  40380. });
  40381. //check for collisions
  40382. var contact = this.world.contacts;
  40383. while (contact !== null) {
  40384. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  40385. contact = contact.next;
  40386. continue;
  40387. }
  40388. //is this body colliding with any other? get the impostor
  40389. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  40390. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  40391. if (!mainImpostor || !collidingImpostor) {
  40392. contact = contact.next;
  40393. continue;
  40394. }
  40395. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  40396. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  40397. contact = contact.next;
  40398. }
  40399. };
  40400. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  40401. var mass = impostor.physicsBody.massInfo.mass;
  40402. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  40403. };
  40404. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  40405. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  40406. this.applyImpulse(impostor, force, contactPoint);
  40407. };
  40408. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  40409. var _this = this;
  40410. //parent-child relationship. Does this impostor has a parent impostor?
  40411. if (impostor.parent) {
  40412. if (impostor.physicsBody) {
  40413. this.removePhysicsBody(impostor);
  40414. //TODO is that needed?
  40415. impostor.forceUpdate();
  40416. }
  40417. return;
  40418. }
  40419. if (impostor.isBodyInitRequired()) {
  40420. var bodyConfig = {
  40421. name: impostor.uniqueId,
  40422. //Oimo must have mass, also for static objects.
  40423. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  40424. size: [],
  40425. type: [],
  40426. pos: [],
  40427. rot: [],
  40428. move: impostor.getParam("mass") !== 0,
  40429. //Supporting older versions of Oimo
  40430. world: this.world
  40431. };
  40432. var impostors = [impostor];
  40433. var addToArray = function (parent) {
  40434. if (!parent.getChildMeshes)
  40435. return;
  40436. parent.getChildMeshes().forEach(function (m) {
  40437. if (m.physicsImpostor) {
  40438. impostors.push(m.physicsImpostor);
  40439. m.physicsImpostor._init();
  40440. }
  40441. });
  40442. };
  40443. addToArray(impostor.object);
  40444. var checkWithEpsilon_1 = function (value) {
  40445. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  40446. };
  40447. impostors.forEach(function (i) {
  40448. //get the correct bounding box
  40449. var oldQuaternion = i.object.rotationQuaternion;
  40450. var rot = new OIMO.Euler().setFromQuaternion({
  40451. x: impostor.object.rotationQuaternion.x,
  40452. y: impostor.object.rotationQuaternion.y,
  40453. z: impostor.object.rotationQuaternion.z,
  40454. s: impostor.object.rotationQuaternion.w
  40455. });
  40456. var extendSize = i.getObjectExtendSize();
  40457. if (i === impostor) {
  40458. var center = impostor.getObjectCenter();
  40459. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  40460. //Can also use Array.prototype.push.apply
  40461. bodyConfig.pos.push(center.x);
  40462. bodyConfig.pos.push(center.y);
  40463. bodyConfig.pos.push(center.z);
  40464. //tmp solution
  40465. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  40466. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  40467. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  40468. }
  40469. else {
  40470. bodyConfig.pos.push(i.object.position.x);
  40471. bodyConfig.pos.push(i.object.position.y);
  40472. bodyConfig.pos.push(i.object.position.z);
  40473. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  40474. bodyConfig.rot.push(0);
  40475. bodyConfig.rot.push(0);
  40476. bodyConfig.rot.push(0);
  40477. }
  40478. // register mesh
  40479. switch (i.type) {
  40480. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40481. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  40482. case BABYLON.PhysicsImpostor.SphereImpostor:
  40483. var radiusX = extendSize.x;
  40484. var radiusY = extendSize.y;
  40485. var radiusZ = extendSize.z;
  40486. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  40487. bodyConfig.type.push('sphere');
  40488. //due to the way oimo works with compounds, add 3 times
  40489. bodyConfig.size.push(size);
  40490. bodyConfig.size.push(size);
  40491. bodyConfig.size.push(size);
  40492. break;
  40493. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40494. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  40495. var sizeY = checkWithEpsilon_1(extendSize.y);
  40496. bodyConfig.type.push('cylinder');
  40497. bodyConfig.size.push(sizeX);
  40498. bodyConfig.size.push(sizeY);
  40499. //due to the way oimo works with compounds, add one more value.
  40500. bodyConfig.size.push(sizeY);
  40501. break;
  40502. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40503. case BABYLON.PhysicsImpostor.BoxImpostor:
  40504. default:
  40505. var sizeX = checkWithEpsilon_1(extendSize.x);
  40506. var sizeY = checkWithEpsilon_1(extendSize.y);
  40507. var sizeZ = checkWithEpsilon_1(extendSize.z);
  40508. bodyConfig.type.push('box');
  40509. bodyConfig.size.push(sizeX);
  40510. bodyConfig.size.push(sizeY);
  40511. bodyConfig.size.push(sizeZ);
  40512. break;
  40513. }
  40514. //actually not needed, but hey...
  40515. i.object.rotationQuaternion = oldQuaternion;
  40516. });
  40517. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  40518. }
  40519. else {
  40520. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  40521. }
  40522. impostor.setDeltaPosition(this._tmpPositionVector);
  40523. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  40524. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  40525. };
  40526. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  40527. //impostor.physicsBody.dispose();
  40528. //Same as : (older oimo versions)
  40529. this.world.removeRigidBody(impostor.physicsBody);
  40530. };
  40531. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  40532. var mainBody = impostorJoint.mainImpostor.physicsBody;
  40533. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  40534. if (!mainBody || !connectedBody) {
  40535. return;
  40536. }
  40537. var jointData = impostorJoint.joint.jointData;
  40538. var options = jointData.nativeParams || {};
  40539. var type;
  40540. var nativeJointData = {
  40541. body1: mainBody,
  40542. body2: connectedBody,
  40543. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  40544. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  40545. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  40546. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  40547. min: options.min,
  40548. max: options.max,
  40549. collision: options.collision || jointData.collision,
  40550. spring: options.spring,
  40551. //supporting older version of Oimo
  40552. world: this.world
  40553. };
  40554. switch (impostorJoint.joint.type) {
  40555. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  40556. type = "jointBall";
  40557. break;
  40558. case BABYLON.PhysicsJoint.SpringJoint:
  40559. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  40560. var springData = jointData;
  40561. nativeJointData.min = springData.length || nativeJointData.min;
  40562. //Max should also be set, just make sure it is at least min
  40563. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  40564. case BABYLON.PhysicsJoint.DistanceJoint:
  40565. type = "jointDistance";
  40566. nativeJointData.max = jointData.maxDistance;
  40567. break;
  40568. case BABYLON.PhysicsJoint.PrismaticJoint:
  40569. type = "jointPrisme";
  40570. break;
  40571. case BABYLON.PhysicsJoint.SliderJoint:
  40572. type = "jointSlide";
  40573. break;
  40574. case BABYLON.PhysicsJoint.WheelJoint:
  40575. type = "jointWheel";
  40576. break;
  40577. case BABYLON.PhysicsJoint.HingeJoint:
  40578. default:
  40579. type = "jointHinge";
  40580. break;
  40581. }
  40582. nativeJointData.type = type;
  40583. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  40584. };
  40585. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  40586. //Bug in Oimo prevents us from disposing a joint in the playground
  40587. //joint.joint.physicsJoint.dispose();
  40588. //So we will bruteforce it!
  40589. try {
  40590. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  40591. }
  40592. catch (e) {
  40593. BABYLON.Tools.Warn(e);
  40594. }
  40595. };
  40596. OimoJSPlugin.prototype.isSupported = function () {
  40597. return OIMO !== undefined;
  40598. };
  40599. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40600. if (!impostor.physicsBody.sleeping) {
  40601. //TODO check that
  40602. if (impostor.physicsBody.shapes.next) {
  40603. var parentShape = this._getLastShape(impostor.physicsBody);
  40604. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  40605. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  40606. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  40607. }
  40608. else {
  40609. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  40610. }
  40611. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  40612. impostor.object.rotationQuaternion.normalize();
  40613. }
  40614. };
  40615. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  40616. var body = impostor.physicsBody;
  40617. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  40618. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  40619. body.syncShapes();
  40620. body.awake();
  40621. };
  40622. OimoJSPlugin.prototype._getLastShape = function (body) {
  40623. var lastShape = body.shapes;
  40624. while (lastShape.next) {
  40625. lastShape = lastShape.next;
  40626. }
  40627. return lastShape;
  40628. };
  40629. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  40630. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  40631. };
  40632. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  40633. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  40634. };
  40635. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  40636. var v = impostor.physicsBody.linearVelocity;
  40637. if (!v)
  40638. return null;
  40639. return new BABYLON.Vector3(v.x, v.y, v.z);
  40640. };
  40641. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  40642. var v = impostor.physicsBody.angularVelocity;
  40643. if (!v)
  40644. return null;
  40645. return new BABYLON.Vector3(v.x, v.y, v.z);
  40646. };
  40647. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  40648. var staticBody = mass === 0;
  40649. //this will actually set the body's density and not its mass.
  40650. //But this is how oimo treats the mass variable.
  40651. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  40652. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  40653. };
  40654. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  40655. impostor.physicsBody.sleep();
  40656. };
  40657. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  40658. impostor.physicsBody.awake();
  40659. };
  40660. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  40661. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  40662. if (minDistance !== void 0) {
  40663. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  40664. }
  40665. };
  40666. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  40667. //TODO separate rotational and transational motors.
  40668. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  40669. if (motor) {
  40670. motor.setMotor(speed, maxForce);
  40671. }
  40672. };
  40673. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  40674. //TODO separate rotational and transational motors.
  40675. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  40676. if (motor) {
  40677. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  40678. }
  40679. };
  40680. OimoJSPlugin.prototype.dispose = function () {
  40681. this.world.clear();
  40682. };
  40683. return OimoJSPlugin;
  40684. }());
  40685. BABYLON.OimoJSPlugin = OimoJSPlugin;
  40686. })(BABYLON || (BABYLON = {}));
  40687. var BABYLON;
  40688. (function (BABYLON) {
  40689. var DisplayPassPostProcess = (function (_super) {
  40690. __extends(DisplayPassPostProcess, _super);
  40691. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  40692. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  40693. }
  40694. return DisplayPassPostProcess;
  40695. }(BABYLON.PostProcess));
  40696. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  40697. })(BABYLON || (BABYLON = {}));
  40698. var BABYLON;
  40699. (function (BABYLON) {
  40700. var SimplificationSettings = (function () {
  40701. function SimplificationSettings(quality, distance, optimizeMesh) {
  40702. this.quality = quality;
  40703. this.distance = distance;
  40704. this.optimizeMesh = optimizeMesh;
  40705. }
  40706. return SimplificationSettings;
  40707. }());
  40708. BABYLON.SimplificationSettings = SimplificationSettings;
  40709. var SimplificationQueue = (function () {
  40710. function SimplificationQueue() {
  40711. this.running = false;
  40712. this._simplificationArray = [];
  40713. }
  40714. SimplificationQueue.prototype.addTask = function (task) {
  40715. this._simplificationArray.push(task);
  40716. };
  40717. SimplificationQueue.prototype.executeNext = function () {
  40718. var task = this._simplificationArray.pop();
  40719. if (task) {
  40720. this.running = true;
  40721. this.runSimplification(task);
  40722. }
  40723. else {
  40724. this.running = false;
  40725. }
  40726. };
  40727. SimplificationQueue.prototype.runSimplification = function (task) {
  40728. var _this = this;
  40729. if (task.parallelProcessing) {
  40730. //parallel simplifier
  40731. task.settings.forEach(function (setting) {
  40732. var simplifier = _this.getSimplifier(task);
  40733. simplifier.simplify(setting, function (newMesh) {
  40734. task.mesh.addLODLevel(setting.distance, newMesh);
  40735. newMesh.isVisible = true;
  40736. //check if it is the last
  40737. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  40738. //all done, run the success callback.
  40739. task.successCallback();
  40740. }
  40741. _this.executeNext();
  40742. });
  40743. });
  40744. }
  40745. else {
  40746. //single simplifier.
  40747. var simplifier = this.getSimplifier(task);
  40748. var runDecimation = function (setting, callback) {
  40749. simplifier.simplify(setting, function (newMesh) {
  40750. task.mesh.addLODLevel(setting.distance, newMesh);
  40751. newMesh.isVisible = true;
  40752. //run the next quality level
  40753. callback();
  40754. });
  40755. };
  40756. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  40757. runDecimation(task.settings[loop.index], function () {
  40758. loop.executeNext();
  40759. });
  40760. }, function () {
  40761. //execution ended, run the success callback.
  40762. if (task.successCallback) {
  40763. task.successCallback();
  40764. }
  40765. _this.executeNext();
  40766. });
  40767. }
  40768. };
  40769. SimplificationQueue.prototype.getSimplifier = function (task) {
  40770. switch (task.simplificationType) {
  40771. case SimplificationType.QUADRATIC:
  40772. default:
  40773. return new QuadraticErrorSimplification(task.mesh);
  40774. }
  40775. };
  40776. return SimplificationQueue;
  40777. }());
  40778. BABYLON.SimplificationQueue = SimplificationQueue;
  40779. /**
  40780. * The implemented types of simplification.
  40781. * At the moment only Quadratic Error Decimation is implemented.
  40782. */
  40783. (function (SimplificationType) {
  40784. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  40785. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  40786. var SimplificationType = BABYLON.SimplificationType;
  40787. var DecimationTriangle = (function () {
  40788. function DecimationTriangle(vertices) {
  40789. this.vertices = vertices;
  40790. this.error = new Array(4);
  40791. this.deleted = false;
  40792. this.isDirty = false;
  40793. this.deletePending = false;
  40794. this.borderFactor = 0;
  40795. }
  40796. return DecimationTriangle;
  40797. }());
  40798. BABYLON.DecimationTriangle = DecimationTriangle;
  40799. var DecimationVertex = (function () {
  40800. function DecimationVertex(position, id) {
  40801. this.position = position;
  40802. this.id = id;
  40803. this.isBorder = true;
  40804. this.q = new QuadraticMatrix();
  40805. this.triangleCount = 0;
  40806. this.triangleStart = 0;
  40807. this.originalOffsets = [];
  40808. }
  40809. DecimationVertex.prototype.updatePosition = function (newPosition) {
  40810. this.position.copyFrom(newPosition);
  40811. };
  40812. return DecimationVertex;
  40813. }());
  40814. BABYLON.DecimationVertex = DecimationVertex;
  40815. var QuadraticMatrix = (function () {
  40816. function QuadraticMatrix(data) {
  40817. this.data = new Array(10);
  40818. for (var i = 0; i < 10; ++i) {
  40819. if (data && data[i]) {
  40820. this.data[i] = data[i];
  40821. }
  40822. else {
  40823. this.data[i] = 0;
  40824. }
  40825. }
  40826. }
  40827. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  40828. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  40829. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  40830. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  40831. return det;
  40832. };
  40833. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  40834. for (var i = 0; i < 10; ++i) {
  40835. this.data[i] += matrix.data[i];
  40836. }
  40837. };
  40838. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  40839. for (var i = 0; i < 10; ++i) {
  40840. this.data[i] += data[i];
  40841. }
  40842. };
  40843. QuadraticMatrix.prototype.add = function (matrix) {
  40844. var m = new QuadraticMatrix();
  40845. for (var i = 0; i < 10; ++i) {
  40846. m.data[i] = this.data[i] + matrix.data[i];
  40847. }
  40848. return m;
  40849. };
  40850. QuadraticMatrix.FromData = function (a, b, c, d) {
  40851. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  40852. };
  40853. //returning an array to avoid garbage collection
  40854. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  40855. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  40856. };
  40857. return QuadraticMatrix;
  40858. }());
  40859. BABYLON.QuadraticMatrix = QuadraticMatrix;
  40860. var Reference = (function () {
  40861. function Reference(vertexId, triangleId) {
  40862. this.vertexId = vertexId;
  40863. this.triangleId = triangleId;
  40864. }
  40865. return Reference;
  40866. }());
  40867. BABYLON.Reference = Reference;
  40868. /**
  40869. * An implementation of the Quadratic Error simplification algorithm.
  40870. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  40871. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  40872. * @author RaananW
  40873. */
  40874. var QuadraticErrorSimplification = (function () {
  40875. function QuadraticErrorSimplification(_mesh) {
  40876. this._mesh = _mesh;
  40877. this.initialized = false;
  40878. this.syncIterations = 5000;
  40879. this.aggressiveness = 7;
  40880. this.decimationIterations = 100;
  40881. this.boundingBoxEpsilon = BABYLON.Epsilon;
  40882. }
  40883. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  40884. var _this = this;
  40885. this.initDecimatedMesh();
  40886. //iterating through the submeshes array, one after the other.
  40887. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  40888. _this.initWithMesh(loop.index, function () {
  40889. _this.runDecimation(settings, loop.index, function () {
  40890. loop.executeNext();
  40891. });
  40892. }, settings.optimizeMesh);
  40893. }, function () {
  40894. setTimeout(function () {
  40895. successCallback(_this._reconstructedMesh);
  40896. }, 0);
  40897. });
  40898. };
  40899. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  40900. var _this = this;
  40901. var gCount = 0;
  40902. triangle.vertices.forEach(function (vertex) {
  40903. var count = 0;
  40904. var vPos = vertex.position;
  40905. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  40906. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  40907. ++count;
  40908. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  40909. ++count;
  40910. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  40911. ++count;
  40912. if (count > 1) {
  40913. ++gCount;
  40914. }
  40915. ;
  40916. });
  40917. if (gCount > 1) {
  40918. console.log(triangle, gCount);
  40919. }
  40920. return gCount > 1;
  40921. };
  40922. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  40923. var _this = this;
  40924. var targetCount = ~~(this.triangles.length * settings.quality);
  40925. var deletedTriangles = 0;
  40926. var triangleCount = this.triangles.length;
  40927. var iterationFunction = function (iteration, callback) {
  40928. setTimeout(function () {
  40929. if (iteration % 5 === 0) {
  40930. _this.updateMesh(iteration === 0);
  40931. }
  40932. for (var i = 0; i < _this.triangles.length; ++i) {
  40933. _this.triangles[i].isDirty = false;
  40934. }
  40935. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  40936. var trianglesIterator = function (i) {
  40937. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  40938. var t = _this.triangles[tIdx];
  40939. if (!t)
  40940. return;
  40941. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  40942. return;
  40943. }
  40944. for (var j = 0; j < 3; ++j) {
  40945. if (t.error[j] < threshold) {
  40946. var deleted0 = [];
  40947. var deleted1 = [];
  40948. var v0 = t.vertices[j];
  40949. var v1 = t.vertices[(j + 1) % 3];
  40950. if (v0.isBorder || v1.isBorder)
  40951. continue;
  40952. var p = BABYLON.Vector3.Zero();
  40953. var n = BABYLON.Vector3.Zero();
  40954. var uv = BABYLON.Vector2.Zero();
  40955. var color = new BABYLON.Color4(0, 0, 0, 1);
  40956. _this.calculateError(v0, v1, p, n, uv, color);
  40957. var delTr = [];
  40958. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  40959. continue;
  40960. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  40961. continue;
  40962. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  40963. continue;
  40964. var uniqueArray = [];
  40965. delTr.forEach(function (deletedT) {
  40966. if (uniqueArray.indexOf(deletedT) === -1) {
  40967. deletedT.deletePending = true;
  40968. uniqueArray.push(deletedT);
  40969. }
  40970. });
  40971. if (uniqueArray.length % 2 !== 0) {
  40972. continue;
  40973. }
  40974. v0.q = v1.q.add(v0.q);
  40975. v0.updatePosition(p);
  40976. var tStart = _this.references.length;
  40977. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  40978. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  40979. var tCount = _this.references.length - tStart;
  40980. if (tCount <= v0.triangleCount) {
  40981. if (tCount) {
  40982. for (var c = 0; c < tCount; c++) {
  40983. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  40984. }
  40985. }
  40986. }
  40987. else {
  40988. v0.triangleStart = tStart;
  40989. }
  40990. v0.triangleCount = tCount;
  40991. break;
  40992. }
  40993. }
  40994. };
  40995. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  40996. }, 0);
  40997. };
  40998. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  40999. if (triangleCount - deletedTriangles <= targetCount)
  41000. loop.breakLoop();
  41001. else {
  41002. iterationFunction(loop.index, function () {
  41003. loop.executeNext();
  41004. });
  41005. }
  41006. }, function () {
  41007. setTimeout(function () {
  41008. //reconstruct this part of the mesh
  41009. _this.reconstructMesh(submeshIndex);
  41010. successCallback();
  41011. }, 0);
  41012. });
  41013. };
  41014. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  41015. var _this = this;
  41016. this.vertices = [];
  41017. this.triangles = [];
  41018. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41019. var indices = this._mesh.getIndices();
  41020. var submesh = this._mesh.subMeshes[submeshIndex];
  41021. var findInVertices = function (positionToSearch) {
  41022. if (optimizeMesh) {
  41023. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  41024. if (_this.vertices[ii].position.equals(positionToSearch)) {
  41025. return _this.vertices[ii];
  41026. }
  41027. }
  41028. }
  41029. return null;
  41030. };
  41031. var vertexReferences = [];
  41032. var vertexInit = function (i) {
  41033. var offset = i + submesh.verticesStart;
  41034. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  41035. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  41036. vertex.originalOffsets.push(offset);
  41037. if (vertex.id === _this.vertices.length) {
  41038. _this.vertices.push(vertex);
  41039. }
  41040. vertexReferences.push(vertex.id);
  41041. };
  41042. //var totalVertices = mesh.getTotalVertices();
  41043. var totalVertices = submesh.verticesCount;
  41044. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  41045. var indicesInit = function (i) {
  41046. var offset = (submesh.indexStart / 3) + i;
  41047. var pos = (offset * 3);
  41048. var i0 = indices[pos + 0];
  41049. var i1 = indices[pos + 1];
  41050. var i2 = indices[pos + 2];
  41051. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  41052. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  41053. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  41054. var triangle = new DecimationTriangle([v0, v1, v2]);
  41055. triangle.originalOffset = pos;
  41056. _this.triangles.push(triangle);
  41057. };
  41058. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  41059. _this.init(callback);
  41060. });
  41061. });
  41062. };
  41063. QuadraticErrorSimplification.prototype.init = function (callback) {
  41064. var _this = this;
  41065. var triangleInit1 = function (i) {
  41066. var t = _this.triangles[i];
  41067. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  41068. for (var j = 0; j < 3; j++) {
  41069. 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))));
  41070. }
  41071. };
  41072. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  41073. var triangleInit2 = function (i) {
  41074. var t = _this.triangles[i];
  41075. for (var j = 0; j < 3; ++j) {
  41076. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  41077. }
  41078. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41079. };
  41080. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  41081. _this.initialized = true;
  41082. callback();
  41083. });
  41084. });
  41085. };
  41086. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  41087. var newTriangles = [];
  41088. var i;
  41089. for (i = 0; i < this.vertices.length; ++i) {
  41090. this.vertices[i].triangleCount = 0;
  41091. }
  41092. var t;
  41093. var j;
  41094. for (i = 0; i < this.triangles.length; ++i) {
  41095. if (!this.triangles[i].deleted) {
  41096. t = this.triangles[i];
  41097. for (j = 0; j < 3; ++j) {
  41098. t.vertices[j].triangleCount = 1;
  41099. }
  41100. newTriangles.push(t);
  41101. }
  41102. }
  41103. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  41104. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  41105. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  41106. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  41107. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41108. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41109. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41110. var vertexCount = 0;
  41111. for (i = 0; i < this.vertices.length; ++i) {
  41112. var vertex = this.vertices[i];
  41113. vertex.id = vertexCount;
  41114. if (vertex.triangleCount) {
  41115. vertex.originalOffsets.forEach(function (originalOffset) {
  41116. newPositionData.push(vertex.position.x);
  41117. newPositionData.push(vertex.position.y);
  41118. newPositionData.push(vertex.position.z);
  41119. newNormalData.push(normalData[originalOffset * 3]);
  41120. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  41121. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  41122. if (uvs && uvs.length) {
  41123. newUVsData.push(uvs[(originalOffset * 2)]);
  41124. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  41125. }
  41126. else if (colorsData && colorsData.length) {
  41127. newColorsData.push(colorsData[(originalOffset * 4)]);
  41128. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  41129. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  41130. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  41131. }
  41132. ++vertexCount;
  41133. });
  41134. }
  41135. }
  41136. var startingIndex = this._reconstructedMesh.getTotalIndices();
  41137. var startingVertex = this._reconstructedMesh.getTotalVertices();
  41138. var submeshesArray = this._reconstructedMesh.subMeshes;
  41139. this._reconstructedMesh.subMeshes = [];
  41140. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  41141. var originalIndices = this._mesh.getIndices();
  41142. for (i = 0; i < newTriangles.length; ++i) {
  41143. t = newTriangles[i]; //now get the new referencing point for each vertex
  41144. [0, 1, 2].forEach(function (idx) {
  41145. var id = originalIndices[t.originalOffset + idx];
  41146. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  41147. if (offset < 0)
  41148. offset = 0;
  41149. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  41150. });
  41151. }
  41152. //overwriting the old vertex buffers and indices.
  41153. this._reconstructedMesh.setIndices(newIndicesArray);
  41154. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  41155. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  41156. if (newUVsData.length > 0)
  41157. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  41158. if (newColorsData.length > 0)
  41159. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  41160. //create submesh
  41161. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  41162. if (submeshIndex > 0) {
  41163. this._reconstructedMesh.subMeshes = [];
  41164. submeshesArray.forEach(function (submesh) {
  41165. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  41166. });
  41167. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  41168. }
  41169. };
  41170. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  41171. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  41172. this._reconstructedMesh.material = this._mesh.material;
  41173. this._reconstructedMesh.parent = this._mesh.parent;
  41174. this._reconstructedMesh.isVisible = false;
  41175. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  41176. };
  41177. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  41178. for (var i = 0; i < vertex1.triangleCount; ++i) {
  41179. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  41180. if (t.deleted)
  41181. continue;
  41182. var s = this.references[vertex1.triangleStart + i].vertexId;
  41183. var v1 = t.vertices[(s + 1) % 3];
  41184. var v2 = t.vertices[(s + 2) % 3];
  41185. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  41186. deletedArray[i] = true;
  41187. delTr.push(t);
  41188. continue;
  41189. }
  41190. var d1 = v1.position.subtract(point);
  41191. d1 = d1.normalize();
  41192. var d2 = v2.position.subtract(point);
  41193. d2 = d2.normalize();
  41194. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  41195. return true;
  41196. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  41197. deletedArray[i] = false;
  41198. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  41199. return true;
  41200. }
  41201. return false;
  41202. };
  41203. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  41204. var newDeleted = deletedTriangles;
  41205. for (var i = 0; i < vertex.triangleCount; ++i) {
  41206. var ref = this.references[vertex.triangleStart + i];
  41207. var t = this.triangles[ref.triangleId];
  41208. if (t.deleted)
  41209. continue;
  41210. if (deletedArray[i] && t.deletePending) {
  41211. t.deleted = true;
  41212. newDeleted++;
  41213. continue;
  41214. }
  41215. t.vertices[ref.vertexId] = origVertex;
  41216. t.isDirty = true;
  41217. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  41218. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  41219. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  41220. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41221. this.references.push(ref);
  41222. }
  41223. return newDeleted;
  41224. };
  41225. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  41226. for (var i = 0; i < this.vertices.length; ++i) {
  41227. var vCount = [];
  41228. var vId = [];
  41229. var v = this.vertices[i];
  41230. var j;
  41231. for (j = 0; j < v.triangleCount; ++j) {
  41232. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  41233. for (var ii = 0; ii < 3; ii++) {
  41234. var ofs = 0;
  41235. var vv = triangle.vertices[ii];
  41236. while (ofs < vCount.length) {
  41237. if (vId[ofs] === vv.id)
  41238. break;
  41239. ++ofs;
  41240. }
  41241. if (ofs === vCount.length) {
  41242. vCount.push(1);
  41243. vId.push(vv.id);
  41244. }
  41245. else {
  41246. vCount[ofs]++;
  41247. }
  41248. }
  41249. }
  41250. for (j = 0; j < vCount.length; ++j) {
  41251. if (vCount[j] === 1) {
  41252. this.vertices[vId[j]].isBorder = true;
  41253. }
  41254. else {
  41255. this.vertices[vId[j]].isBorder = false;
  41256. }
  41257. }
  41258. }
  41259. };
  41260. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  41261. if (identifyBorders === void 0) { identifyBorders = false; }
  41262. var i;
  41263. if (!identifyBorders) {
  41264. var newTrianglesVector = [];
  41265. for (i = 0; i < this.triangles.length; ++i) {
  41266. if (!this.triangles[i].deleted) {
  41267. newTrianglesVector.push(this.triangles[i]);
  41268. }
  41269. }
  41270. this.triangles = newTrianglesVector;
  41271. }
  41272. for (i = 0; i < this.vertices.length; ++i) {
  41273. this.vertices[i].triangleCount = 0;
  41274. this.vertices[i].triangleStart = 0;
  41275. }
  41276. var t;
  41277. var j;
  41278. var v;
  41279. for (i = 0; i < this.triangles.length; ++i) {
  41280. t = this.triangles[i];
  41281. for (j = 0; j < 3; ++j) {
  41282. v = t.vertices[j];
  41283. v.triangleCount++;
  41284. }
  41285. }
  41286. var tStart = 0;
  41287. for (i = 0; i < this.vertices.length; ++i) {
  41288. this.vertices[i].triangleStart = tStart;
  41289. tStart += this.vertices[i].triangleCount;
  41290. this.vertices[i].triangleCount = 0;
  41291. }
  41292. var newReferences = new Array(this.triangles.length * 3);
  41293. for (i = 0; i < this.triangles.length; ++i) {
  41294. t = this.triangles[i];
  41295. for (j = 0; j < 3; ++j) {
  41296. v = t.vertices[j];
  41297. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  41298. v.triangleCount++;
  41299. }
  41300. }
  41301. this.references = newReferences;
  41302. if (identifyBorders) {
  41303. this.identifyBorder();
  41304. }
  41305. };
  41306. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  41307. var x = point.x;
  41308. var y = point.y;
  41309. var z = point.z;
  41310. 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
  41311. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  41312. };
  41313. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  41314. var q = vertex1.q.add(vertex2.q);
  41315. var border = vertex1.isBorder && vertex2.isBorder;
  41316. var error = 0;
  41317. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  41318. if (qDet !== 0 && !border) {
  41319. if (!pointResult) {
  41320. pointResult = BABYLON.Vector3.Zero();
  41321. }
  41322. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  41323. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  41324. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  41325. error = this.vertexError(q, pointResult);
  41326. }
  41327. else {
  41328. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  41329. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  41330. var error1 = this.vertexError(q, vertex1.position);
  41331. var error2 = this.vertexError(q, vertex2.position);
  41332. var error3 = this.vertexError(q, p3);
  41333. error = Math.min(error1, error2, error3);
  41334. if (error === error1) {
  41335. if (pointResult) {
  41336. pointResult.copyFrom(vertex1.position);
  41337. }
  41338. }
  41339. else if (error === error2) {
  41340. if (pointResult) {
  41341. pointResult.copyFrom(vertex2.position);
  41342. }
  41343. }
  41344. else {
  41345. if (pointResult) {
  41346. pointResult.copyFrom(p3);
  41347. }
  41348. }
  41349. }
  41350. return error;
  41351. };
  41352. return QuadraticErrorSimplification;
  41353. }());
  41354. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  41355. })(BABYLON || (BABYLON = {}));
  41356. var BABYLON;
  41357. (function (BABYLON) {
  41358. var serializedGeometries = [];
  41359. var serializeGeometry = function (geometry, serializationGeometries) {
  41360. if (serializedGeometries[geometry.id]) {
  41361. return;
  41362. }
  41363. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  41364. serializationGeometries.boxes.push(geometry.serialize());
  41365. }
  41366. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  41367. serializationGeometries.spheres.push(geometry.serialize());
  41368. }
  41369. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  41370. serializationGeometries.cylinders.push(geometry.serialize());
  41371. }
  41372. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  41373. serializationGeometries.toruses.push(geometry.serialize());
  41374. }
  41375. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  41376. serializationGeometries.grounds.push(geometry.serialize());
  41377. }
  41378. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  41379. serializationGeometries.planes.push(geometry.serialize());
  41380. }
  41381. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  41382. serializationGeometries.torusKnots.push(geometry.serialize());
  41383. }
  41384. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  41385. throw new Error("Unknown primitive type");
  41386. }
  41387. else {
  41388. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  41389. }
  41390. serializedGeometries[geometry.id] = true;
  41391. };
  41392. var serializeMesh = function (mesh, serializationScene) {
  41393. var serializationObject = {};
  41394. serializationObject.name = mesh.name;
  41395. serializationObject.id = mesh.id;
  41396. if (BABYLON.Tags.HasTags(mesh)) {
  41397. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  41398. }
  41399. serializationObject.position = mesh.position.asArray();
  41400. if (mesh.rotationQuaternion) {
  41401. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  41402. }
  41403. else if (mesh.rotation) {
  41404. serializationObject.rotation = mesh.rotation.asArray();
  41405. }
  41406. serializationObject.scaling = mesh.scaling.asArray();
  41407. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  41408. serializationObject.isEnabled = mesh.isEnabled();
  41409. serializationObject.isVisible = mesh.isVisible;
  41410. serializationObject.infiniteDistance = mesh.infiniteDistance;
  41411. serializationObject.pickable = mesh.isPickable;
  41412. serializationObject.receiveShadows = mesh.receiveShadows;
  41413. serializationObject.billboardMode = mesh.billboardMode;
  41414. serializationObject.visibility = mesh.visibility;
  41415. serializationObject.checkCollisions = mesh.checkCollisions;
  41416. // Parent
  41417. if (mesh.parent) {
  41418. serializationObject.parentId = mesh.parent.id;
  41419. }
  41420. // Geometry
  41421. var geometry = mesh._geometry;
  41422. if (geometry) {
  41423. var geometryId = geometry.id;
  41424. serializationObject.geometryId = geometryId;
  41425. if (!mesh.getScene().getGeometryByID(geometryId)) {
  41426. // 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
  41427. serializeGeometry(geometry, serializationScene.geometries);
  41428. }
  41429. // SubMeshes
  41430. serializationObject.subMeshes = [];
  41431. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41432. var subMesh = mesh.subMeshes[subIndex];
  41433. serializationObject.subMeshes.push({
  41434. materialIndex: subMesh.materialIndex,
  41435. verticesStart: subMesh.verticesStart,
  41436. verticesCount: subMesh.verticesCount,
  41437. indexStart: subMesh.indexStart,
  41438. indexCount: subMesh.indexCount
  41439. });
  41440. }
  41441. }
  41442. // Material
  41443. if (mesh.material) {
  41444. serializationObject.materialId = mesh.material.id;
  41445. }
  41446. else {
  41447. mesh.material = null;
  41448. }
  41449. // Skeleton
  41450. if (mesh.skeleton) {
  41451. serializationObject.skeletonId = mesh.skeleton.id;
  41452. }
  41453. // Physics
  41454. //TODO implement correct serialization for physics impostors.
  41455. if (mesh.getPhysicsImpostor()) {
  41456. serializationObject.physicsMass = mesh.getPhysicsMass();
  41457. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  41458. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  41459. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  41460. }
  41461. // Instances
  41462. serializationObject.instances = [];
  41463. for (var index = 0; index < mesh.instances.length; index++) {
  41464. var instance = mesh.instances[index];
  41465. var serializationInstance = {
  41466. name: instance.name,
  41467. position: instance.position.asArray(),
  41468. scaling: instance.scaling.asArray()
  41469. };
  41470. if (instance.rotationQuaternion) {
  41471. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  41472. }
  41473. else if (instance.rotation) {
  41474. serializationInstance.rotation = instance.rotation.asArray();
  41475. }
  41476. serializationObject.instances.push(serializationInstance);
  41477. // Animations
  41478. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  41479. serializationInstance.ranges = instance.serializeAnimationRanges();
  41480. }
  41481. // Animations
  41482. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  41483. serializationObject.ranges = mesh.serializeAnimationRanges();
  41484. // Layer mask
  41485. serializationObject.layerMask = mesh.layerMask;
  41486. // Action Manager
  41487. if (mesh.actionManager) {
  41488. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  41489. }
  41490. return serializationObject;
  41491. };
  41492. var finalizeSingleMesh = function (mesh, serializationObject) {
  41493. //only works if the mesh is already loaded
  41494. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  41495. //serialize material
  41496. if (mesh.material) {
  41497. if (mesh.material instanceof BABYLON.StandardMaterial) {
  41498. serializationObject.materials = serializationObject.materials || [];
  41499. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  41500. serializationObject.materials.push(mesh.material.serialize());
  41501. }
  41502. }
  41503. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  41504. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  41505. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  41506. serializationObject.multiMaterials.push(mesh.material.serialize());
  41507. }
  41508. }
  41509. }
  41510. //serialize geometry
  41511. var geometry = mesh._geometry;
  41512. if (geometry) {
  41513. if (!serializationObject.geometries) {
  41514. serializationObject.geometries = {};
  41515. serializationObject.geometries.boxes = [];
  41516. serializationObject.geometries.spheres = [];
  41517. serializationObject.geometries.cylinders = [];
  41518. serializationObject.geometries.toruses = [];
  41519. serializationObject.geometries.grounds = [];
  41520. serializationObject.geometries.planes = [];
  41521. serializationObject.geometries.torusKnots = [];
  41522. serializationObject.geometries.vertexData = [];
  41523. }
  41524. serializeGeometry(geometry, serializationObject.geometries);
  41525. }
  41526. // Skeletons
  41527. if (mesh.skeleton) {
  41528. serializationObject.skeletons = serializationObject.skeletons || [];
  41529. serializationObject.skeletons.push(mesh.skeleton.serialize());
  41530. }
  41531. //serialize the actual mesh
  41532. serializationObject.meshes = serializationObject.meshes || [];
  41533. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  41534. }
  41535. };
  41536. var SceneSerializer = (function () {
  41537. function SceneSerializer() {
  41538. }
  41539. SceneSerializer.ClearCache = function () {
  41540. serializedGeometries = [];
  41541. };
  41542. SceneSerializer.Serialize = function (scene) {
  41543. var serializationObject = {};
  41544. // Scene
  41545. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  41546. serializationObject.autoClear = scene.autoClear;
  41547. serializationObject.clearColor = scene.clearColor.asArray();
  41548. serializationObject.ambientColor = scene.ambientColor.asArray();
  41549. serializationObject.gravity = scene.gravity.asArray();
  41550. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  41551. serializationObject.workerCollisions = scene.workerCollisions;
  41552. // Fog
  41553. if (scene.fogMode && scene.fogMode !== 0) {
  41554. serializationObject.fogMode = scene.fogMode;
  41555. serializationObject.fogColor = scene.fogColor.asArray();
  41556. serializationObject.fogStart = scene.fogStart;
  41557. serializationObject.fogEnd = scene.fogEnd;
  41558. serializationObject.fogDensity = scene.fogDensity;
  41559. }
  41560. //Physics
  41561. if (scene.isPhysicsEnabled()) {
  41562. serializationObject.physicsEnabled = true;
  41563. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  41564. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  41565. }
  41566. // Lights
  41567. serializationObject.lights = [];
  41568. var index;
  41569. var light;
  41570. for (index = 0; index < scene.lights.length; index++) {
  41571. light = scene.lights[index];
  41572. serializationObject.lights.push(light.serialize());
  41573. }
  41574. // Cameras
  41575. serializationObject.cameras = [];
  41576. for (index = 0; index < scene.cameras.length; index++) {
  41577. var camera = scene.cameras[index];
  41578. serializationObject.cameras.push(camera.serialize());
  41579. }
  41580. if (scene.activeCamera) {
  41581. serializationObject.activeCameraID = scene.activeCamera.id;
  41582. }
  41583. // Animations
  41584. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  41585. // Materials
  41586. serializationObject.materials = [];
  41587. serializationObject.multiMaterials = [];
  41588. var material;
  41589. for (index = 0; index < scene.materials.length; index++) {
  41590. material = scene.materials[index];
  41591. serializationObject.materials.push(material.serialize());
  41592. }
  41593. // MultiMaterials
  41594. serializationObject.multiMaterials = [];
  41595. for (index = 0; index < scene.multiMaterials.length; index++) {
  41596. var multiMaterial = scene.multiMaterials[index];
  41597. serializationObject.multiMaterials.push(multiMaterial.serialize());
  41598. }
  41599. // Skeletons
  41600. serializationObject.skeletons = [];
  41601. for (index = 0; index < scene.skeletons.length; index++) {
  41602. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  41603. }
  41604. // Geometries
  41605. serializationObject.geometries = {};
  41606. serializationObject.geometries.boxes = [];
  41607. serializationObject.geometries.spheres = [];
  41608. serializationObject.geometries.cylinders = [];
  41609. serializationObject.geometries.toruses = [];
  41610. serializationObject.geometries.grounds = [];
  41611. serializationObject.geometries.planes = [];
  41612. serializationObject.geometries.torusKnots = [];
  41613. serializationObject.geometries.vertexData = [];
  41614. serializedGeometries = [];
  41615. var geometries = scene.getGeometries();
  41616. for (index = 0; index < geometries.length; index++) {
  41617. var geometry = geometries[index];
  41618. if (geometry.isReady()) {
  41619. serializeGeometry(geometry, serializationObject.geometries);
  41620. }
  41621. }
  41622. // Meshes
  41623. serializationObject.meshes = [];
  41624. for (index = 0; index < scene.meshes.length; index++) {
  41625. var abstractMesh = scene.meshes[index];
  41626. if (abstractMesh instanceof BABYLON.Mesh) {
  41627. var mesh = abstractMesh;
  41628. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  41629. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  41630. }
  41631. }
  41632. }
  41633. // Particles Systems
  41634. serializationObject.particleSystems = [];
  41635. for (index = 0; index < scene.particleSystems.length; index++) {
  41636. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  41637. }
  41638. // Lens flares
  41639. serializationObject.lensFlareSystems = [];
  41640. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  41641. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  41642. }
  41643. // Shadows
  41644. serializationObject.shadowGenerators = [];
  41645. for (index = 0; index < scene.lights.length; index++) {
  41646. light = scene.lights[index];
  41647. var shadowGenerator = light.getShadowGenerator();
  41648. // Only support serialization for official generator so far.
  41649. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  41650. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  41651. }
  41652. }
  41653. // Action Manager
  41654. if (scene.actionManager) {
  41655. serializationObject.actions = scene.actionManager.serialize("scene");
  41656. }
  41657. // Audio
  41658. serializationObject.sounds = [];
  41659. for (index = 0; index < scene.soundTracks.length; index++) {
  41660. var soundtrack = scene.soundTracks[index];
  41661. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  41662. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  41663. }
  41664. }
  41665. return serializationObject;
  41666. };
  41667. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  41668. if (withParents === void 0) { withParents = false; }
  41669. if (withChildren === void 0) { withChildren = false; }
  41670. var serializationObject = {};
  41671. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  41672. if (withParents || withChildren) {
  41673. //deliberate for loop! not for each, appended should be processed as well.
  41674. for (var i = 0; i < toSerialize.length; ++i) {
  41675. if (withChildren) {
  41676. toSerialize[i].getDescendants().forEach(function (node) {
  41677. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  41678. toSerialize.push(node);
  41679. }
  41680. });
  41681. }
  41682. //make sure the array doesn't contain the object already
  41683. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  41684. toSerialize.push(toSerialize[i].parent);
  41685. }
  41686. }
  41687. }
  41688. toSerialize.forEach(function (mesh) {
  41689. finalizeSingleMesh(mesh, serializationObject);
  41690. });
  41691. return serializationObject;
  41692. };
  41693. return SceneSerializer;
  41694. }());
  41695. BABYLON.SceneSerializer = SceneSerializer;
  41696. })(BABYLON || (BABYLON = {}));
  41697. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  41698. // Huge respect for a such great lib.
  41699. // Earcut license:
  41700. // Copyright (c) 2016, Mapbox
  41701. //
  41702. // Permission to use, copy, modify, and/or distribute this software for any purpose
  41703. // with or without fee is hereby granted, provided that the above copyright notice
  41704. // and this permission notice appear in all copies.
  41705. //
  41706. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  41707. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  41708. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  41709. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  41710. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  41711. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  41712. // THIS SOFTWARE.
  41713. var Earcut;
  41714. (function (Earcut) {
  41715. /**
  41716. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  41717. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  41718. * @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).
  41719. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  41720. */
  41721. function earcut(data, holeIndices, dim) {
  41722. dim = dim || 2;
  41723. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  41724. if (!outerNode)
  41725. return triangles;
  41726. var minX, minY, maxX, maxY, x, y, size;
  41727. if (hasHoles)
  41728. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  41729. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  41730. if (data.length > 80 * dim) {
  41731. minX = maxX = data[0];
  41732. minY = maxY = data[1];
  41733. for (var i = dim; i < outerLen; i += dim) {
  41734. x = data[i];
  41735. y = data[i + 1];
  41736. if (x < minX)
  41737. minX = x;
  41738. if (y < minY)
  41739. minY = y;
  41740. if (x > maxX)
  41741. maxX = x;
  41742. if (y > maxY)
  41743. maxY = y;
  41744. }
  41745. // minX, minY and size are later used to transform coords into integers for z-order calculation
  41746. size = Math.max(maxX - minX, maxY - minY);
  41747. }
  41748. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  41749. return triangles;
  41750. }
  41751. Earcut.earcut = earcut;
  41752. // create a circular doubly linked list from polygon points in the specified winding order
  41753. function linkedList(data, start, end, dim, clockwise) {
  41754. var i, last;
  41755. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  41756. for (i = start; i < end; i += dim)
  41757. last = insertNode(i, data[i], data[i + 1], last);
  41758. }
  41759. else {
  41760. for (i = end - dim; i >= start; i -= dim)
  41761. last = insertNode(i, data[i], data[i + 1], last);
  41762. }
  41763. if (last && equals(last, last.next)) {
  41764. removeNode(last);
  41765. last = last.next;
  41766. }
  41767. return last;
  41768. }
  41769. // eliminate colinear or duplicate points
  41770. function filterPoints(start, end) {
  41771. if (!start)
  41772. return start;
  41773. if (!end)
  41774. end = start;
  41775. var p = start, again;
  41776. do {
  41777. again = false;
  41778. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  41779. removeNode(p);
  41780. p = end = p.prev;
  41781. if (p === p.next)
  41782. return null;
  41783. again = true;
  41784. }
  41785. else {
  41786. p = p.next;
  41787. }
  41788. } while (again || p !== end);
  41789. return end;
  41790. }
  41791. // main ear slicing loop which triangulates a polygon (given as a linked list)
  41792. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  41793. if (!ear)
  41794. return;
  41795. // interlink polygon nodes in z-order
  41796. if (!pass && size)
  41797. indexCurve(ear, minX, minY, size);
  41798. var stop = ear, prev, next;
  41799. // iterate through ears, slicing them one by one
  41800. while (ear.prev !== ear.next) {
  41801. prev = ear.prev;
  41802. next = ear.next;
  41803. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  41804. // cut off the triangle
  41805. triangles.push(prev.i / dim);
  41806. triangles.push(ear.i / dim);
  41807. triangles.push(next.i / dim);
  41808. removeNode(ear);
  41809. // skipping the next vertice leads to less sliver triangles
  41810. ear = next.next;
  41811. stop = next.next;
  41812. continue;
  41813. }
  41814. ear = next;
  41815. // if we looped through the whole remaining polygon and can't find any more ears
  41816. if (ear === stop) {
  41817. // try filtering points and slicing again
  41818. if (!pass) {
  41819. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  41820. }
  41821. else if (pass === 1) {
  41822. ear = cureLocalIntersections(ear, triangles, dim);
  41823. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  41824. }
  41825. else if (pass === 2) {
  41826. splitEarcut(ear, triangles, dim, minX, minY, size);
  41827. }
  41828. break;
  41829. }
  41830. }
  41831. }
  41832. // check whether a polygon node forms a valid ear with adjacent nodes
  41833. function isEar(ear) {
  41834. var a = ear.prev, b = ear, c = ear.next;
  41835. if (area(a, b, c) >= 0)
  41836. return false; // reflex, can't be an ear
  41837. // now make sure we don't have other points inside the potential ear
  41838. var p = ear.next.next;
  41839. while (p !== ear.prev) {
  41840. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41841. area(p.prev, p, p.next) >= 0)
  41842. return false;
  41843. p = p.next;
  41844. }
  41845. return true;
  41846. }
  41847. function isEarHashed(ear, minX, minY, size) {
  41848. var a = ear.prev, b = ear, c = ear.next;
  41849. if (area(a, b, c) >= 0)
  41850. return false; // reflex, can't be an ear
  41851. // triangle bbox; min & max are calculated like this for speed
  41852. 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);
  41853. // z-order range for the current triangle bbox;
  41854. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  41855. // first look for points inside the triangle in increasing z-order
  41856. var p = ear.nextZ;
  41857. while (p && p.z <= maxZ) {
  41858. if (p !== ear.prev &&
  41859. p !== ear.next &&
  41860. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41861. area(p.prev, p, p.next) >= 0)
  41862. return false;
  41863. p = p.nextZ;
  41864. }
  41865. // then look for points in decreasing z-order
  41866. p = ear.prevZ;
  41867. while (p && p.z >= minZ) {
  41868. if (p !== ear.prev &&
  41869. p !== ear.next &&
  41870. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41871. area(p.prev, p, p.next) >= 0)
  41872. return false;
  41873. p = p.prevZ;
  41874. }
  41875. return true;
  41876. }
  41877. // go through all polygon nodes and cure small local self-intersections
  41878. function cureLocalIntersections(start, triangles, dim) {
  41879. var p = start;
  41880. do {
  41881. var a = p.prev, b = p.next.next;
  41882. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  41883. triangles.push(a.i / dim);
  41884. triangles.push(p.i / dim);
  41885. triangles.push(b.i / dim);
  41886. // remove two nodes involved
  41887. removeNode(p);
  41888. removeNode(p.next);
  41889. p = start = b;
  41890. }
  41891. p = p.next;
  41892. } while (p !== start);
  41893. return p;
  41894. }
  41895. // try splitting polygon into two and triangulate them independently
  41896. function splitEarcut(start, triangles, dim, minX, minY, size) {
  41897. // look for a valid diagonal that divides the polygon into two
  41898. var a = start;
  41899. do {
  41900. var b = a.next.next;
  41901. while (b !== a.prev) {
  41902. if (a.i !== b.i && isValidDiagonal(a, b)) {
  41903. // split the polygon in two by the diagonal
  41904. var c = splitPolygon(a, b);
  41905. // filter colinear points around the cuts
  41906. a = filterPoints(a, a.next);
  41907. c = filterPoints(c, c.next);
  41908. // run earcut on each half
  41909. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  41910. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  41911. return;
  41912. }
  41913. b = b.next;
  41914. }
  41915. a = a.next;
  41916. } while (a !== start);
  41917. }
  41918. // link every hole into the outer loop, producing a single-ring polygon without holes
  41919. function eliminateHoles(data, holeIndices, outerNode, dim) {
  41920. var queue = [], i, len, start, end, list;
  41921. for (i = 0, len = holeIndices.length; i < len; i++) {
  41922. start = holeIndices[i] * dim;
  41923. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  41924. list = linkedList(data, start, end, dim, false);
  41925. if (list === list.next)
  41926. list.steiner = true;
  41927. queue.push(getLeftmost(list));
  41928. }
  41929. queue.sort(compareX);
  41930. // process holes from left to right
  41931. for (i = 0; i < queue.length; i++) {
  41932. eliminateHole(queue[i], outerNode);
  41933. outerNode = filterPoints(outerNode, outerNode.next);
  41934. }
  41935. return outerNode;
  41936. }
  41937. function compareX(a, b) {
  41938. return a.x - b.x;
  41939. }
  41940. // find a bridge between vertices that connects hole with an outer ring and and link it
  41941. function eliminateHole(hole, outerNode) {
  41942. outerNode = findHoleBridge(hole, outerNode);
  41943. if (outerNode) {
  41944. var b = splitPolygon(outerNode, hole);
  41945. filterPoints(b, b.next);
  41946. }
  41947. }
  41948. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  41949. function findHoleBridge(hole, outerNode) {
  41950. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  41951. // find a segment intersected by a ray from the hole's leftmost point to the left;
  41952. // segment's endpoint with lesser x will be potential connection point
  41953. do {
  41954. if (hy <= p.y && hy >= p.next.y) {
  41955. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  41956. if (x <= hx && x > qx) {
  41957. qx = x;
  41958. if (x === hx) {
  41959. if (hy === p.y)
  41960. return p;
  41961. if (hy === p.next.y)
  41962. return p.next;
  41963. }
  41964. m = p.x < p.next.x ? p : p.next;
  41965. }
  41966. }
  41967. p = p.next;
  41968. } while (p !== outerNode);
  41969. if (!m)
  41970. return null;
  41971. if (hx === qx)
  41972. return m.prev; // hole touches outer segment; pick lower endpoint
  41973. // look for points inside the triangle of hole point, segment intersection and endpoint;
  41974. // if there are no points found, we have a valid connection;
  41975. // otherwise choose the point of the minimum angle with the ray as connection point
  41976. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  41977. p = m.next;
  41978. while (p !== stop) {
  41979. if (hx >= p.x &&
  41980. p.x >= mx &&
  41981. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  41982. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  41983. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  41984. m = p;
  41985. tanMin = tan;
  41986. }
  41987. }
  41988. p = p.next;
  41989. }
  41990. return m;
  41991. }
  41992. // interlink polygon nodes in z-order
  41993. function indexCurve(start, minX, minY, size) {
  41994. var p = start;
  41995. do {
  41996. if (p.z === null)
  41997. p.z = zOrder(p.x, p.y, minX, minY, size);
  41998. p.prevZ = p.prev;
  41999. p.nextZ = p.next;
  42000. p = p.next;
  42001. } while (p !== start);
  42002. p.prevZ.nextZ = null;
  42003. p.prevZ = null;
  42004. sortLinked(p);
  42005. }
  42006. // Simon Tatham's linked list merge sort algorithm
  42007. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  42008. function sortLinked(list) {
  42009. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  42010. do {
  42011. p = list;
  42012. list = null;
  42013. tail = null;
  42014. numMerges = 0;
  42015. while (p) {
  42016. numMerges++;
  42017. q = p;
  42018. pSize = 0;
  42019. for (i = 0; i < inSize; i++) {
  42020. pSize++;
  42021. q = q.nextZ;
  42022. if (!q)
  42023. break;
  42024. }
  42025. qSize = inSize;
  42026. while (pSize > 0 || (qSize > 0 && q)) {
  42027. if (pSize === 0) {
  42028. e = q;
  42029. q = q.nextZ;
  42030. qSize--;
  42031. }
  42032. else if (qSize === 0 || !q) {
  42033. e = p;
  42034. p = p.nextZ;
  42035. pSize--;
  42036. }
  42037. else if (p.z <= q.z) {
  42038. e = p;
  42039. p = p.nextZ;
  42040. pSize--;
  42041. }
  42042. else {
  42043. e = q;
  42044. q = q.nextZ;
  42045. qSize--;
  42046. }
  42047. if (tail)
  42048. tail.nextZ = e;
  42049. else
  42050. list = e;
  42051. e.prevZ = tail;
  42052. tail = e;
  42053. }
  42054. p = q;
  42055. }
  42056. tail.nextZ = null;
  42057. inSize *= 2;
  42058. } while (numMerges > 1);
  42059. return list;
  42060. }
  42061. // z-order of a point given coords and size of the data bounding box
  42062. function zOrder(x, y, minX, minY, size) {
  42063. // coords are transformed into non-negative 15-bit integer range
  42064. x = 32767 * (x - minX) / size;
  42065. y = 32767 * (y - minY) / size;
  42066. x = (x | (x << 8)) & 0x00FF00FF;
  42067. x = (x | (x << 4)) & 0x0F0F0F0F;
  42068. x = (x | (x << 2)) & 0x33333333;
  42069. x = (x | (x << 1)) & 0x55555555;
  42070. y = (y | (y << 8)) & 0x00FF00FF;
  42071. y = (y | (y << 4)) & 0x0F0F0F0F;
  42072. y = (y | (y << 2)) & 0x33333333;
  42073. y = (y | (y << 1)) & 0x55555555;
  42074. return x | (y << 1);
  42075. }
  42076. // find the leftmost node of a polygon ring
  42077. function getLeftmost(start) {
  42078. var p = start, leftmost = start;
  42079. do {
  42080. if (p.x < leftmost.x)
  42081. leftmost = p;
  42082. p = p.next;
  42083. } while (p !== start);
  42084. return leftmost;
  42085. }
  42086. // check if a point lies within a convex triangle
  42087. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  42088. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  42089. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  42090. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  42091. }
  42092. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  42093. function isValidDiagonal(a, b) {
  42094. return a.next.i !== b.i &&
  42095. a.prev.i !== b.i &&
  42096. !intersectsPolygon(a, b) &&
  42097. locallyInside(a, b) &&
  42098. locallyInside(b, a) &&
  42099. middleInside(a, b);
  42100. }
  42101. // signed area of a triangle
  42102. function area(p, q, r) {
  42103. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  42104. }
  42105. // check if two points are equal
  42106. function equals(p1, p2) {
  42107. return p1.x === p2.x && p1.y === p2.y;
  42108. }
  42109. // check if two segments intersect
  42110. function intersects(p1, q1, p2, q2) {
  42111. if ((equals(p1, q1) && equals(p2, q2)) ||
  42112. (equals(p1, q2) && equals(p2, q1)))
  42113. return true;
  42114. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  42115. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  42116. }
  42117. // check if a polygon diagonal intersects any polygon segments
  42118. function intersectsPolygon(a, b) {
  42119. var p = a;
  42120. do {
  42121. if (p.i !== a.i &&
  42122. p.next.i !== a.i &&
  42123. p.i !== b.i &&
  42124. p.next.i !== b.i &&
  42125. intersects(p, p.next, a, b))
  42126. return true;
  42127. p = p.next;
  42128. } while (p !== a);
  42129. return false;
  42130. }
  42131. // check if a polygon diagonal is locally inside the polygon
  42132. function locallyInside(a, b) {
  42133. return area(a.prev, a, a.next) < 0
  42134. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  42135. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  42136. }
  42137. // check if the middle point of a polygon diagonal is inside the polygon
  42138. function middleInside(a, b) {
  42139. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  42140. do {
  42141. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  42142. inside = !inside;
  42143. p = p.next;
  42144. } while (p !== a);
  42145. return inside;
  42146. }
  42147. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  42148. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  42149. function splitPolygon(a, b) {
  42150. 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;
  42151. a.next = b;
  42152. b.prev = a;
  42153. a2.next = an;
  42154. an.prev = a2;
  42155. b2.next = a2;
  42156. a2.prev = b2;
  42157. bp.next = b2;
  42158. b2.prev = bp;
  42159. return b2;
  42160. }
  42161. // create a node and optionally link it with previous one (in a circular doubly linked list)
  42162. function insertNode(i, x, y, last) {
  42163. var p = new Node(i, x, y);
  42164. if (!last) {
  42165. p.prev = p;
  42166. p.next = p;
  42167. }
  42168. else {
  42169. p.next = last.next;
  42170. p.prev = last;
  42171. last.next.prev = p;
  42172. last.next = p;
  42173. }
  42174. return p;
  42175. }
  42176. function removeNode(p) {
  42177. p.next.prev = p.prev;
  42178. p.prev.next = p.next;
  42179. if (p.prevZ)
  42180. p.prevZ.nextZ = p.nextZ;
  42181. if (p.nextZ)
  42182. p.nextZ.prevZ = p.prevZ;
  42183. }
  42184. function Node(i, x, y) {
  42185. // vertice index in coordinates array
  42186. this.i = i;
  42187. // vertex coordinates
  42188. this.x = x;
  42189. this.y = y;
  42190. // previous and next vertice nodes in a polygon ring
  42191. this.prev = null;
  42192. this.next = null;
  42193. // z-order curve value
  42194. this.z = null;
  42195. // previous and next nodes in z-order
  42196. this.prevZ = null;
  42197. this.nextZ = null;
  42198. // indicates whether this is a steiner point
  42199. this.steiner = false;
  42200. }
  42201. /**
  42202. * return a percentage difference between the polygon area and its triangulation area;
  42203. * used to verify correctness of triangulation
  42204. */
  42205. function deviation(data, holeIndices, dim, triangles) {
  42206. var hasHoles = holeIndices && holeIndices.length;
  42207. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  42208. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  42209. if (hasHoles) {
  42210. for (var i = 0, len = holeIndices.length; i < len; i++) {
  42211. var start = holeIndices[i] * dim;
  42212. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  42213. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  42214. }
  42215. }
  42216. var trianglesArea = 0;
  42217. for (i = 0; i < triangles.length; i += 3) {
  42218. var a = triangles[i] * dim;
  42219. var b = triangles[i + 1] * dim;
  42220. var c = triangles[i + 2] * dim;
  42221. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  42222. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  42223. }
  42224. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  42225. }
  42226. Earcut.deviation = deviation;
  42227. ;
  42228. function signedArea(data, start, end, dim) {
  42229. var sum = 0;
  42230. for (var i = start, j = end - dim; i < end; i += dim) {
  42231. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  42232. j = i;
  42233. }
  42234. return sum;
  42235. }
  42236. /**
  42237. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  42238. */
  42239. function flatten(data) {
  42240. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  42241. for (var i = 0; i < data.length; i++) {
  42242. for (var j = 0; j < data[i].length; j++) {
  42243. for (var d = 0; d < dim; d++)
  42244. result.vertices.push(data[i][j][d]);
  42245. }
  42246. if (i > 0) {
  42247. holeIndex += data[i - 1].length;
  42248. result.holes.push(holeIndex);
  42249. }
  42250. }
  42251. return result;
  42252. }
  42253. Earcut.flatten = flatten;
  42254. ;
  42255. })(Earcut || (Earcut = {}));
  42256. var BABYLON;
  42257. (function (BABYLON) {
  42258. // Unique ID when we import meshes from Babylon to CSG
  42259. var currentCSGMeshId = 0;
  42260. // # class Vertex
  42261. // Represents a vertex of a polygon. Use your own vertex class instead of this
  42262. // one to provide additional features like texture coordinates and vertex
  42263. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  42264. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  42265. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  42266. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  42267. // is not used anywhere else.
  42268. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  42269. var Vertex = (function () {
  42270. function Vertex(pos, normal, uv) {
  42271. this.pos = pos;
  42272. this.normal = normal;
  42273. this.uv = uv;
  42274. }
  42275. Vertex.prototype.clone = function () {
  42276. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  42277. };
  42278. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  42279. // orientation of a polygon is flipped.
  42280. Vertex.prototype.flip = function () {
  42281. this.normal = this.normal.scale(-1);
  42282. };
  42283. // Create a new vertex between this vertex and `other` by linearly
  42284. // interpolating all properties using a parameter of `t`. Subclasses should
  42285. // override this to interpolate additional properties.
  42286. Vertex.prototype.interpolate = function (other, t) {
  42287. 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));
  42288. };
  42289. return Vertex;
  42290. }());
  42291. // # class Plane
  42292. // Represents a plane in 3D space.
  42293. var Plane = (function () {
  42294. function Plane(normal, w) {
  42295. this.normal = normal;
  42296. this.w = w;
  42297. }
  42298. Plane.FromPoints = function (a, b, c) {
  42299. var v0 = c.subtract(a);
  42300. var v1 = b.subtract(a);
  42301. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  42302. return null;
  42303. }
  42304. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  42305. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  42306. };
  42307. Plane.prototype.clone = function () {
  42308. return new Plane(this.normal.clone(), this.w);
  42309. };
  42310. Plane.prototype.flip = function () {
  42311. this.normal.scaleInPlace(-1);
  42312. this.w = -this.w;
  42313. };
  42314. // Split `polygon` by this plane if needed, then put the polygon or polygon
  42315. // fragments in the appropriate lists. Coplanar polygons go into either
  42316. // `coplanarFront` or `coplanarBack` depending on their orientation with
  42317. // respect to this plane. Polygons in front or in back of this plane go into
  42318. // either `front` or `back`.
  42319. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  42320. var COPLANAR = 0;
  42321. var FRONT = 1;
  42322. var BACK = 2;
  42323. var SPANNING = 3;
  42324. // Classify each point as well as the entire polygon into one of the above
  42325. // four classes.
  42326. var polygonType = 0;
  42327. var types = [];
  42328. var i;
  42329. var t;
  42330. for (i = 0; i < polygon.vertices.length; i++) {
  42331. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  42332. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  42333. polygonType |= type;
  42334. types.push(type);
  42335. }
  42336. // Put the polygon in the correct list, splitting it when necessary.
  42337. switch (polygonType) {
  42338. case COPLANAR:
  42339. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  42340. break;
  42341. case FRONT:
  42342. front.push(polygon);
  42343. break;
  42344. case BACK:
  42345. back.push(polygon);
  42346. break;
  42347. case SPANNING:
  42348. var f = [], b = [];
  42349. for (i = 0; i < polygon.vertices.length; i++) {
  42350. var j = (i + 1) % polygon.vertices.length;
  42351. var ti = types[i], tj = types[j];
  42352. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  42353. if (ti !== BACK)
  42354. f.push(vi);
  42355. if (ti !== FRONT)
  42356. b.push(ti !== BACK ? vi.clone() : vi);
  42357. if ((ti | tj) === SPANNING) {
  42358. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  42359. var v = vi.interpolate(vj, t);
  42360. f.push(v);
  42361. b.push(v.clone());
  42362. }
  42363. }
  42364. var poly;
  42365. if (f.length >= 3) {
  42366. poly = new Polygon(f, polygon.shared);
  42367. if (poly.plane)
  42368. front.push(poly);
  42369. }
  42370. if (b.length >= 3) {
  42371. poly = new Polygon(b, polygon.shared);
  42372. if (poly.plane)
  42373. back.push(poly);
  42374. }
  42375. break;
  42376. }
  42377. };
  42378. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  42379. // point is on the plane.
  42380. Plane.EPSILON = 1e-5;
  42381. return Plane;
  42382. }());
  42383. // # class Polygon
  42384. // Represents a convex polygon. The vertices used to initialize a polygon must
  42385. // be coplanar and form a convex loop.
  42386. //
  42387. // Each convex polygon has a `shared` property, which is shared between all
  42388. // polygons that are clones of each other or were split from the same polygon.
  42389. // This can be used to define per-polygon properties (such as surface color).
  42390. var Polygon = (function () {
  42391. function Polygon(vertices, shared) {
  42392. this.vertices = vertices;
  42393. this.shared = shared;
  42394. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  42395. }
  42396. Polygon.prototype.clone = function () {
  42397. var vertices = this.vertices.map(function (v) { return v.clone(); });
  42398. return new Polygon(vertices, this.shared);
  42399. };
  42400. Polygon.prototype.flip = function () {
  42401. this.vertices.reverse().map(function (v) { v.flip(); });
  42402. this.plane.flip();
  42403. };
  42404. return Polygon;
  42405. }());
  42406. // # class Node
  42407. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  42408. // by picking a polygon to split along. That polygon (and all other coplanar
  42409. // polygons) are added directly to that node and the other polygons are added to
  42410. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  42411. // no distinction between internal and leaf nodes.
  42412. var Node = (function () {
  42413. function Node(polygons) {
  42414. this.plane = null;
  42415. this.front = null;
  42416. this.back = null;
  42417. this.polygons = [];
  42418. if (polygons) {
  42419. this.build(polygons);
  42420. }
  42421. }
  42422. Node.prototype.clone = function () {
  42423. var node = new Node();
  42424. node.plane = this.plane && this.plane.clone();
  42425. node.front = this.front && this.front.clone();
  42426. node.back = this.back && this.back.clone();
  42427. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  42428. return node;
  42429. };
  42430. // Convert solid space to empty space and empty space to solid space.
  42431. Node.prototype.invert = function () {
  42432. for (var i = 0; i < this.polygons.length; i++) {
  42433. this.polygons[i].flip();
  42434. }
  42435. if (this.plane) {
  42436. this.plane.flip();
  42437. }
  42438. if (this.front) {
  42439. this.front.invert();
  42440. }
  42441. if (this.back) {
  42442. this.back.invert();
  42443. }
  42444. var temp = this.front;
  42445. this.front = this.back;
  42446. this.back = temp;
  42447. };
  42448. // Recursively remove all polygons in `polygons` that are inside this BSP
  42449. // tree.
  42450. Node.prototype.clipPolygons = function (polygons) {
  42451. if (!this.plane)
  42452. return polygons.slice();
  42453. var front = [], back = [];
  42454. for (var i = 0; i < polygons.length; i++) {
  42455. this.plane.splitPolygon(polygons[i], front, back, front, back);
  42456. }
  42457. if (this.front) {
  42458. front = this.front.clipPolygons(front);
  42459. }
  42460. if (this.back) {
  42461. back = this.back.clipPolygons(back);
  42462. }
  42463. else {
  42464. back = [];
  42465. }
  42466. return front.concat(back);
  42467. };
  42468. // Remove all polygons in this BSP tree that are inside the other BSP tree
  42469. // `bsp`.
  42470. Node.prototype.clipTo = function (bsp) {
  42471. this.polygons = bsp.clipPolygons(this.polygons);
  42472. if (this.front)
  42473. this.front.clipTo(bsp);
  42474. if (this.back)
  42475. this.back.clipTo(bsp);
  42476. };
  42477. // Return a list of all polygons in this BSP tree.
  42478. Node.prototype.allPolygons = function () {
  42479. var polygons = this.polygons.slice();
  42480. if (this.front)
  42481. polygons = polygons.concat(this.front.allPolygons());
  42482. if (this.back)
  42483. polygons = polygons.concat(this.back.allPolygons());
  42484. return polygons;
  42485. };
  42486. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  42487. // new polygons are filtered down to the bottom of the tree and become new
  42488. // nodes there. Each set of polygons is partitioned using the first polygon
  42489. // (no heuristic is used to pick a good split).
  42490. Node.prototype.build = function (polygons) {
  42491. if (!polygons.length)
  42492. return;
  42493. if (!this.plane)
  42494. this.plane = polygons[0].plane.clone();
  42495. var front = [], back = [];
  42496. for (var i = 0; i < polygons.length; i++) {
  42497. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  42498. }
  42499. if (front.length) {
  42500. if (!this.front)
  42501. this.front = new Node();
  42502. this.front.build(front);
  42503. }
  42504. if (back.length) {
  42505. if (!this.back)
  42506. this.back = new Node();
  42507. this.back.build(back);
  42508. }
  42509. };
  42510. return Node;
  42511. }());
  42512. var CSG = (function () {
  42513. function CSG() {
  42514. this.polygons = new Array();
  42515. }
  42516. // Convert BABYLON.Mesh to BABYLON.CSG
  42517. CSG.FromMesh = function (mesh) {
  42518. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  42519. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  42520. if (mesh instanceof BABYLON.Mesh) {
  42521. mesh.computeWorldMatrix(true);
  42522. matrix = mesh.getWorldMatrix();
  42523. meshPosition = mesh.position.clone();
  42524. meshRotation = mesh.rotation.clone();
  42525. if (mesh.rotationQuaternion) {
  42526. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  42527. }
  42528. meshScaling = mesh.scaling.clone();
  42529. }
  42530. else {
  42531. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  42532. }
  42533. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42534. var subMeshes = mesh.subMeshes;
  42535. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  42536. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  42537. vertices = [];
  42538. for (var j = 0; j < 3; j++) {
  42539. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  42540. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  42541. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  42542. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  42543. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  42544. vertex = new Vertex(position, normal, uv);
  42545. vertices.push(vertex);
  42546. }
  42547. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  42548. // To handle the case of degenerated triangle
  42549. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  42550. if (polygon.plane)
  42551. polygons.push(polygon);
  42552. }
  42553. }
  42554. var csg = CSG.FromPolygons(polygons);
  42555. csg.matrix = matrix;
  42556. csg.position = meshPosition;
  42557. csg.rotation = meshRotation;
  42558. csg.scaling = meshScaling;
  42559. csg.rotationQuaternion = meshRotationQuaternion;
  42560. currentCSGMeshId++;
  42561. return csg;
  42562. };
  42563. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  42564. CSG.FromPolygons = function (polygons) {
  42565. var csg = new CSG();
  42566. csg.polygons = polygons;
  42567. return csg;
  42568. };
  42569. CSG.prototype.clone = function () {
  42570. var csg = new CSG();
  42571. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  42572. csg.copyTransformAttributes(this);
  42573. return csg;
  42574. };
  42575. CSG.prototype.toPolygons = function () {
  42576. return this.polygons;
  42577. };
  42578. CSG.prototype.union = function (csg) {
  42579. var a = new Node(this.clone().polygons);
  42580. var b = new Node(csg.clone().polygons);
  42581. a.clipTo(b);
  42582. b.clipTo(a);
  42583. b.invert();
  42584. b.clipTo(a);
  42585. b.invert();
  42586. a.build(b.allPolygons());
  42587. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42588. };
  42589. CSG.prototype.unionInPlace = function (csg) {
  42590. var a = new Node(this.polygons);
  42591. var b = new Node(csg.polygons);
  42592. a.clipTo(b);
  42593. b.clipTo(a);
  42594. b.invert();
  42595. b.clipTo(a);
  42596. b.invert();
  42597. a.build(b.allPolygons());
  42598. this.polygons = a.allPolygons();
  42599. };
  42600. CSG.prototype.subtract = function (csg) {
  42601. var a = new Node(this.clone().polygons);
  42602. var b = new Node(csg.clone().polygons);
  42603. a.invert();
  42604. a.clipTo(b);
  42605. b.clipTo(a);
  42606. b.invert();
  42607. b.clipTo(a);
  42608. b.invert();
  42609. a.build(b.allPolygons());
  42610. a.invert();
  42611. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42612. };
  42613. CSG.prototype.subtractInPlace = function (csg) {
  42614. var a = new Node(this.polygons);
  42615. var b = new Node(csg.polygons);
  42616. a.invert();
  42617. a.clipTo(b);
  42618. b.clipTo(a);
  42619. b.invert();
  42620. b.clipTo(a);
  42621. b.invert();
  42622. a.build(b.allPolygons());
  42623. a.invert();
  42624. this.polygons = a.allPolygons();
  42625. };
  42626. CSG.prototype.intersect = function (csg) {
  42627. var a = new Node(this.clone().polygons);
  42628. var b = new Node(csg.clone().polygons);
  42629. a.invert();
  42630. b.clipTo(a);
  42631. b.invert();
  42632. a.clipTo(b);
  42633. b.clipTo(a);
  42634. a.build(b.allPolygons());
  42635. a.invert();
  42636. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42637. };
  42638. CSG.prototype.intersectInPlace = function (csg) {
  42639. var a = new Node(this.polygons);
  42640. var b = new Node(csg.polygons);
  42641. a.invert();
  42642. b.clipTo(a);
  42643. b.invert();
  42644. a.clipTo(b);
  42645. b.clipTo(a);
  42646. a.build(b.allPolygons());
  42647. a.invert();
  42648. this.polygons = a.allPolygons();
  42649. };
  42650. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  42651. // not modified.
  42652. CSG.prototype.inverse = function () {
  42653. var csg = this.clone();
  42654. csg.inverseInPlace();
  42655. return csg;
  42656. };
  42657. CSG.prototype.inverseInPlace = function () {
  42658. this.polygons.map(function (p) { p.flip(); });
  42659. };
  42660. // This is used to keep meshes transformations so they can be restored
  42661. // when we build back a Babylon Mesh
  42662. // NB : All CSG operations are performed in world coordinates
  42663. CSG.prototype.copyTransformAttributes = function (csg) {
  42664. this.matrix = csg.matrix;
  42665. this.position = csg.position;
  42666. this.rotation = csg.rotation;
  42667. this.scaling = csg.scaling;
  42668. this.rotationQuaternion = csg.rotationQuaternion;
  42669. return this;
  42670. };
  42671. // Build Raw mesh from CSG
  42672. // Coordinates here are in world space
  42673. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  42674. var matrix = this.matrix.clone();
  42675. matrix.invert();
  42676. 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;
  42677. if (keepSubMeshes) {
  42678. // Sort Polygons, since subMeshes are indices range
  42679. polygons.sort(function (a, b) {
  42680. if (a.shared.meshId === b.shared.meshId) {
  42681. return a.shared.subMeshId - b.shared.subMeshId;
  42682. }
  42683. else {
  42684. return a.shared.meshId - b.shared.meshId;
  42685. }
  42686. });
  42687. }
  42688. for (var i = 0, il = polygons.length; i < il; i++) {
  42689. polygon = polygons[i];
  42690. // Building SubMeshes
  42691. if (!subMesh_dict[polygon.shared.meshId]) {
  42692. subMesh_dict[polygon.shared.meshId] = {};
  42693. }
  42694. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  42695. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  42696. indexStart: +Infinity,
  42697. indexEnd: -Infinity,
  42698. materialIndex: polygon.shared.materialIndex
  42699. };
  42700. }
  42701. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  42702. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  42703. polygonIndices[0] = 0;
  42704. polygonIndices[1] = j - 1;
  42705. polygonIndices[2] = j;
  42706. for (var k = 0; k < 3; k++) {
  42707. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  42708. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  42709. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  42710. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  42711. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  42712. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  42713. // Check if 2 points can be merged
  42714. if (!(typeof vertex_idx !== 'undefined' &&
  42715. normals[vertex_idx * 3] === localNormal.x &&
  42716. normals[vertex_idx * 3 + 1] === localNormal.y &&
  42717. normals[vertex_idx * 3 + 2] === localNormal.z &&
  42718. uvs[vertex_idx * 2] === uv.x &&
  42719. uvs[vertex_idx * 2 + 1] === uv.y)) {
  42720. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  42721. uvs.push(uv.x, uv.y);
  42722. normals.push(normal.x, normal.y, normal.z);
  42723. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  42724. }
  42725. indices.push(vertex_idx);
  42726. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  42727. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  42728. currentIndex++;
  42729. }
  42730. }
  42731. }
  42732. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  42733. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  42734. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  42735. mesh.setIndices(indices);
  42736. if (keepSubMeshes) {
  42737. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  42738. var materialIndexOffset = 0, materialMaxIndex;
  42739. mesh.subMeshes = new Array();
  42740. for (var m in subMesh_dict) {
  42741. materialMaxIndex = -1;
  42742. for (var sm in subMesh_dict[m]) {
  42743. subMesh_obj = subMesh_dict[m][sm];
  42744. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  42745. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  42746. }
  42747. materialIndexOffset += ++materialMaxIndex;
  42748. }
  42749. }
  42750. return mesh;
  42751. };
  42752. // Build Mesh from CSG taking material and transforms into account
  42753. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  42754. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  42755. mesh.material = material;
  42756. mesh.position.copyFrom(this.position);
  42757. mesh.rotation.copyFrom(this.rotation);
  42758. if (this.rotationQuaternion) {
  42759. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  42760. }
  42761. mesh.scaling.copyFrom(this.scaling);
  42762. mesh.computeWorldMatrix(true);
  42763. return mesh;
  42764. };
  42765. return CSG;
  42766. }());
  42767. BABYLON.CSG = CSG;
  42768. })(BABYLON || (BABYLON = {}));
  42769. var BABYLON;
  42770. (function (BABYLON) {
  42771. var VRDistortionCorrectionPostProcess = (function (_super) {
  42772. __extends(VRDistortionCorrectionPostProcess, _super);
  42773. //ANY
  42774. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  42775. var _this = this;
  42776. _super.call(this, name, "vrDistortionCorrection", [
  42777. 'LensCenter',
  42778. 'Scale',
  42779. 'ScaleIn',
  42780. 'HmdWarpParam'
  42781. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  42782. this._isRightEye = isRightEye;
  42783. this._distortionFactors = vrMetrics.distortionK;
  42784. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  42785. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  42786. this.onSizeChangedObservable.add(function () {
  42787. _this.aspectRatio = _this.width * .5 / _this.height;
  42788. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  42789. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  42790. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  42791. });
  42792. this.onApplyObservable.add(function (effect) {
  42793. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  42794. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  42795. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  42796. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  42797. });
  42798. }
  42799. return VRDistortionCorrectionPostProcess;
  42800. }(BABYLON.PostProcess));
  42801. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  42802. })(BABYLON || (BABYLON = {}));
  42803. // Mainly based on these 2 articles :
  42804. // 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
  42805. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  42806. var BABYLON;
  42807. (function (BABYLON) {
  42808. (function (JoystickAxis) {
  42809. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  42810. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  42811. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  42812. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  42813. var JoystickAxis = BABYLON.JoystickAxis;
  42814. var VirtualJoystick = (function () {
  42815. function VirtualJoystick(leftJoystick) {
  42816. var _this = this;
  42817. if (leftJoystick) {
  42818. this._leftJoystick = true;
  42819. }
  42820. else {
  42821. this._leftJoystick = false;
  42822. }
  42823. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  42824. VirtualJoystick._globalJoystickIndex++;
  42825. // By default left & right arrow keys are moving the X
  42826. // and up & down keys are moving the Y
  42827. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42828. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42829. this.reverseLeftRight = false;
  42830. this.reverseUpDown = false;
  42831. // collections of pointers
  42832. this._touches = new BABYLON.StringDictionary();
  42833. this.deltaPosition = BABYLON.Vector3.Zero();
  42834. this._joystickSensibility = 25;
  42835. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42836. this._rotationSpeed = 25;
  42837. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  42838. this._rotateOnAxisRelativeToMesh = false;
  42839. this._onResize = function (evt) {
  42840. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42841. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42842. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  42843. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  42844. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  42845. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  42846. };
  42847. // injecting a canvas element on top of the canvas 3D game
  42848. if (!VirtualJoystick.vjCanvas) {
  42849. window.addEventListener("resize", this._onResize, false);
  42850. VirtualJoystick.vjCanvas = document.createElement("canvas");
  42851. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42852. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42853. VirtualJoystick.vjCanvas.width = window.innerWidth;
  42854. VirtualJoystick.vjCanvas.height = window.innerHeight;
  42855. VirtualJoystick.vjCanvas.style.width = "100%";
  42856. VirtualJoystick.vjCanvas.style.height = "100%";
  42857. VirtualJoystick.vjCanvas.style.position = "absolute";
  42858. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  42859. VirtualJoystick.vjCanvas.style.top = "0px";
  42860. VirtualJoystick.vjCanvas.style.left = "0px";
  42861. VirtualJoystick.vjCanvas.style.zIndex = "5";
  42862. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  42863. // Support for jQuery PEP polyfill
  42864. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  42865. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  42866. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  42867. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42868. document.body.appendChild(VirtualJoystick.vjCanvas);
  42869. }
  42870. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  42871. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  42872. this.pressed = false;
  42873. // default joystick color
  42874. this._joystickColor = "cyan";
  42875. this._joystickPointerID = -1;
  42876. // current joystick position
  42877. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  42878. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  42879. // origin joystick position
  42880. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  42881. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  42882. this._onPointerDownHandlerRef = function (evt) {
  42883. _this._onPointerDown(evt);
  42884. };
  42885. this._onPointerMoveHandlerRef = function (evt) {
  42886. _this._onPointerMove(evt);
  42887. };
  42888. this._onPointerOutHandlerRef = function (evt) {
  42889. _this._onPointerUp(evt);
  42890. };
  42891. this._onPointerUpHandlerRef = function (evt) {
  42892. _this._onPointerUp(evt);
  42893. };
  42894. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  42895. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  42896. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  42897. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  42898. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  42899. evt.preventDefault(); // Disables system menu
  42900. }, false);
  42901. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42902. }
  42903. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  42904. this._joystickSensibility = newJoystickSensibility;
  42905. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42906. };
  42907. VirtualJoystick.prototype._onPointerDown = function (e) {
  42908. var positionOnScreenCondition;
  42909. e.preventDefault();
  42910. if (this._leftJoystick === true) {
  42911. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  42912. }
  42913. else {
  42914. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  42915. }
  42916. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  42917. // First contact will be dedicated to the virtual joystick
  42918. this._joystickPointerID = e.pointerId;
  42919. this._joystickPointerStartPos.x = e.clientX;
  42920. this._joystickPointerStartPos.y = e.clientY;
  42921. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  42922. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  42923. this._deltaJoystickVector.x = 0;
  42924. this._deltaJoystickVector.y = 0;
  42925. this.pressed = true;
  42926. this._touches.add(e.pointerId.toString(), e);
  42927. }
  42928. else {
  42929. // You can only trigger the action buttons with a joystick declared
  42930. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  42931. this._action();
  42932. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  42933. }
  42934. }
  42935. };
  42936. VirtualJoystick.prototype._onPointerMove = function (e) {
  42937. // If the current pointer is the one associated to the joystick (first touch contact)
  42938. if (this._joystickPointerID == e.pointerId) {
  42939. this._joystickPointerPos.x = e.clientX;
  42940. this._joystickPointerPos.y = e.clientY;
  42941. this._deltaJoystickVector = this._joystickPointerPos.clone();
  42942. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  42943. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  42944. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  42945. switch (this._axisTargetedByLeftAndRight) {
  42946. case JoystickAxis.X:
  42947. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  42948. break;
  42949. case JoystickAxis.Y:
  42950. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  42951. break;
  42952. case JoystickAxis.Z:
  42953. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  42954. break;
  42955. }
  42956. var directionUpDown = this.reverseUpDown ? 1 : -1;
  42957. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  42958. switch (this._axisTargetedByUpAndDown) {
  42959. case JoystickAxis.X:
  42960. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  42961. break;
  42962. case JoystickAxis.Y:
  42963. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  42964. break;
  42965. case JoystickAxis.Z:
  42966. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  42967. break;
  42968. }
  42969. }
  42970. else {
  42971. var data = this._touches.get(e.pointerId.toString());
  42972. if (data) {
  42973. data.x = e.clientX;
  42974. data.y = e.clientY;
  42975. }
  42976. }
  42977. };
  42978. VirtualJoystick.prototype._onPointerUp = function (e) {
  42979. if (this._joystickPointerID == e.pointerId) {
  42980. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  42981. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  42982. this._joystickPointerID = -1;
  42983. this.pressed = false;
  42984. }
  42985. else {
  42986. var touch = this._touches.get(e.pointerId.toString());
  42987. if (touch) {
  42988. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  42989. }
  42990. }
  42991. this._deltaJoystickVector.x = 0;
  42992. this._deltaJoystickVector.y = 0;
  42993. this._touches.remove(e.pointerId.toString());
  42994. };
  42995. /**
  42996. * Change the color of the virtual joystick
  42997. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  42998. */
  42999. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  43000. this._joystickColor = newColor;
  43001. };
  43002. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  43003. this._action = action;
  43004. };
  43005. // Define which axis you'd like to control for left & right
  43006. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  43007. switch (axis) {
  43008. case JoystickAxis.X:
  43009. case JoystickAxis.Y:
  43010. case JoystickAxis.Z:
  43011. this._axisTargetedByLeftAndRight = axis;
  43012. break;
  43013. default:
  43014. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  43015. break;
  43016. }
  43017. };
  43018. // Define which axis you'd like to control for up & down
  43019. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  43020. switch (axis) {
  43021. case JoystickAxis.X:
  43022. case JoystickAxis.Y:
  43023. case JoystickAxis.Z:
  43024. this._axisTargetedByUpAndDown = axis;
  43025. break;
  43026. default:
  43027. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  43028. break;
  43029. }
  43030. };
  43031. VirtualJoystick.prototype._clearCanvas = function () {
  43032. if (this._leftJoystick) {
  43033. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  43034. }
  43035. else {
  43036. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  43037. }
  43038. };
  43039. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  43040. var _this = this;
  43041. if (this.pressed) {
  43042. this._touches.forEach(function (touch) {
  43043. if (touch.pointerId === _this._joystickPointerID) {
  43044. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  43045. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  43046. VirtualJoystick.vjCanvasContext.beginPath();
  43047. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  43048. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43049. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  43050. VirtualJoystick.vjCanvasContext.stroke();
  43051. VirtualJoystick.vjCanvasContext.closePath();
  43052. VirtualJoystick.vjCanvasContext.beginPath();
  43053. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43054. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  43055. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  43056. VirtualJoystick.vjCanvasContext.stroke();
  43057. VirtualJoystick.vjCanvasContext.closePath();
  43058. VirtualJoystick.vjCanvasContext.beginPath();
  43059. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43060. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  43061. VirtualJoystick.vjCanvasContext.stroke();
  43062. VirtualJoystick.vjCanvasContext.closePath();
  43063. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  43064. }
  43065. else {
  43066. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  43067. VirtualJoystick.vjCanvasContext.beginPath();
  43068. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  43069. VirtualJoystick.vjCanvasContext.beginPath();
  43070. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  43071. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  43072. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  43073. VirtualJoystick.vjCanvasContext.stroke();
  43074. VirtualJoystick.vjCanvasContext.closePath();
  43075. touch.prevX = touch.x;
  43076. touch.prevY = touch.y;
  43077. }
  43078. ;
  43079. });
  43080. }
  43081. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  43082. };
  43083. VirtualJoystick.prototype.releaseCanvas = function () {
  43084. if (VirtualJoystick.vjCanvas) {
  43085. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  43086. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  43087. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  43088. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  43089. window.removeEventListener("resize", this._onResize);
  43090. document.body.removeChild(VirtualJoystick.vjCanvas);
  43091. VirtualJoystick.vjCanvas = null;
  43092. }
  43093. };
  43094. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  43095. VirtualJoystick._globalJoystickIndex = 0;
  43096. return VirtualJoystick;
  43097. }());
  43098. BABYLON.VirtualJoystick = VirtualJoystick;
  43099. })(BABYLON || (BABYLON = {}));
  43100. var BABYLON;
  43101. (function (BABYLON) {
  43102. // We're mainly based on the logic defined into the FreeCamera code
  43103. var VirtualJoysticksCamera = (function (_super) {
  43104. __extends(VirtualJoysticksCamera, _super);
  43105. function VirtualJoysticksCamera(name, position, scene) {
  43106. _super.call(this, name, position, scene);
  43107. this.inputs.addVirtualJoystick();
  43108. }
  43109. return VirtualJoysticksCamera;
  43110. }(BABYLON.FreeCamera));
  43111. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  43112. })(BABYLON || (BABYLON = {}));
  43113. var BABYLON;
  43114. (function (BABYLON) {
  43115. var FreeCameraVirtualJoystickInput = (function () {
  43116. function FreeCameraVirtualJoystickInput() {
  43117. }
  43118. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  43119. return this._leftjoystick;
  43120. };
  43121. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  43122. return this._rightjoystick;
  43123. };
  43124. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  43125. if (this._leftjoystick) {
  43126. var camera = this.camera;
  43127. var speed = camera._computeLocalCameraSpeed() * 50;
  43128. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  43129. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  43130. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  43131. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  43132. if (!this._leftjoystick.pressed) {
  43133. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  43134. }
  43135. if (!this._rightjoystick.pressed) {
  43136. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  43137. }
  43138. }
  43139. };
  43140. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  43141. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  43142. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  43143. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  43144. this._leftjoystick.setJoystickSensibility(0.15);
  43145. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  43146. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  43147. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  43148. this._rightjoystick.reverseUpDown = true;
  43149. this._rightjoystick.setJoystickSensibility(0.05);
  43150. this._rightjoystick.setJoystickColor("yellow");
  43151. };
  43152. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  43153. this._leftjoystick.releaseCanvas();
  43154. this._rightjoystick.releaseCanvas();
  43155. };
  43156. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  43157. return "FreeCameraVirtualJoystickInput";
  43158. };
  43159. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  43160. return "virtualJoystick";
  43161. };
  43162. return FreeCameraVirtualJoystickInput;
  43163. }());
  43164. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  43165. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  43166. })(BABYLON || (BABYLON = {}));
  43167. var BABYLON;
  43168. (function (BABYLON) {
  43169. var AnaglyphPostProcess = (function (_super) {
  43170. __extends(AnaglyphPostProcess, _super);
  43171. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  43172. var _this = this;
  43173. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  43174. this._passedProcess = rigCameras[0]._rigPostProcess;
  43175. this.onApplyObservable.add(function (effect) {
  43176. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  43177. });
  43178. }
  43179. return AnaglyphPostProcess;
  43180. }(BABYLON.PostProcess));
  43181. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  43182. })(BABYLON || (BABYLON = {}));
  43183. var BABYLON;
  43184. (function (BABYLON) {
  43185. var OutlineRenderer = (function () {
  43186. function OutlineRenderer(scene) {
  43187. this._scene = scene;
  43188. }
  43189. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  43190. var _this = this;
  43191. if (useOverlay === void 0) { useOverlay = false; }
  43192. var scene = this._scene;
  43193. var engine = this._scene.getEngine();
  43194. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43195. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  43196. return;
  43197. }
  43198. var mesh = subMesh.getRenderingMesh();
  43199. var material = subMesh.getMaterial();
  43200. engine.enableEffect(this._effect);
  43201. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  43202. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  43203. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  43204. // Bones
  43205. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43206. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43207. }
  43208. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  43209. // Alpha test
  43210. if (material && material.needAlphaTesting()) {
  43211. var alphaTexture = material.getAlphaTestTexture();
  43212. this._effect.setTexture("diffuseSampler", alphaTexture);
  43213. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43214. }
  43215. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  43216. };
  43217. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  43218. var defines = [];
  43219. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  43220. var mesh = subMesh.getMesh();
  43221. var material = subMesh.getMaterial();
  43222. // Alpha test
  43223. if (material && material.needAlphaTesting()) {
  43224. defines.push("#define ALPHATEST");
  43225. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43226. attribs.push(BABYLON.VertexBuffer.UVKind);
  43227. defines.push("#define UV1");
  43228. }
  43229. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  43230. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43231. defines.push("#define UV2");
  43232. }
  43233. }
  43234. // Bones
  43235. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43236. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43237. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43238. if (mesh.numBoneInfluencers > 4) {
  43239. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43240. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43241. }
  43242. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43243. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43244. }
  43245. else {
  43246. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43247. }
  43248. // Instances
  43249. if (useInstances) {
  43250. defines.push("#define INSTANCES");
  43251. attribs.push("world0");
  43252. attribs.push("world1");
  43253. attribs.push("world2");
  43254. attribs.push("world3");
  43255. }
  43256. // Get correct effect
  43257. var join = defines.join("\n");
  43258. if (this._cachedDefines !== join) {
  43259. this._cachedDefines = join;
  43260. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  43261. }
  43262. return this._effect.isReady();
  43263. };
  43264. return OutlineRenderer;
  43265. }());
  43266. BABYLON.OutlineRenderer = OutlineRenderer;
  43267. })(BABYLON || (BABYLON = {}));
  43268. var BABYLON;
  43269. (function (BABYLON) {
  43270. var MeshAssetTask = (function () {
  43271. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  43272. this.name = name;
  43273. this.meshesNames = meshesNames;
  43274. this.rootUrl = rootUrl;
  43275. this.sceneFilename = sceneFilename;
  43276. this.isCompleted = false;
  43277. }
  43278. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43279. var _this = this;
  43280. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  43281. _this.loadedMeshes = meshes;
  43282. _this.loadedParticleSystems = particleSystems;
  43283. _this.loadedSkeletons = skeletons;
  43284. _this.isCompleted = true;
  43285. if (_this.onSuccess) {
  43286. _this.onSuccess(_this);
  43287. }
  43288. onSuccess();
  43289. }, null, function () {
  43290. if (_this.onError) {
  43291. _this.onError(_this);
  43292. }
  43293. onError();
  43294. });
  43295. };
  43296. return MeshAssetTask;
  43297. }());
  43298. BABYLON.MeshAssetTask = MeshAssetTask;
  43299. var TextFileAssetTask = (function () {
  43300. function TextFileAssetTask(name, url) {
  43301. this.name = name;
  43302. this.url = url;
  43303. this.isCompleted = false;
  43304. }
  43305. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43306. var _this = this;
  43307. BABYLON.Tools.LoadFile(this.url, function (data) {
  43308. _this.text = data;
  43309. _this.isCompleted = true;
  43310. if (_this.onSuccess) {
  43311. _this.onSuccess(_this);
  43312. }
  43313. onSuccess();
  43314. }, null, scene.database, false, function () {
  43315. if (_this.onError) {
  43316. _this.onError(_this);
  43317. }
  43318. onError();
  43319. });
  43320. };
  43321. return TextFileAssetTask;
  43322. }());
  43323. BABYLON.TextFileAssetTask = TextFileAssetTask;
  43324. var BinaryFileAssetTask = (function () {
  43325. function BinaryFileAssetTask(name, url) {
  43326. this.name = name;
  43327. this.url = url;
  43328. this.isCompleted = false;
  43329. }
  43330. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43331. var _this = this;
  43332. BABYLON.Tools.LoadFile(this.url, function (data) {
  43333. _this.data = data;
  43334. _this.isCompleted = true;
  43335. if (_this.onSuccess) {
  43336. _this.onSuccess(_this);
  43337. }
  43338. onSuccess();
  43339. }, null, scene.database, true, function () {
  43340. if (_this.onError) {
  43341. _this.onError(_this);
  43342. }
  43343. onError();
  43344. });
  43345. };
  43346. return BinaryFileAssetTask;
  43347. }());
  43348. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  43349. var ImageAssetTask = (function () {
  43350. function ImageAssetTask(name, url) {
  43351. this.name = name;
  43352. this.url = url;
  43353. this.isCompleted = false;
  43354. }
  43355. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43356. var _this = this;
  43357. var img = new Image();
  43358. BABYLON.Tools.SetCorsBehavior(this.url, img);
  43359. img.onload = function () {
  43360. _this.image = img;
  43361. _this.isCompleted = true;
  43362. if (_this.onSuccess) {
  43363. _this.onSuccess(_this);
  43364. }
  43365. onSuccess();
  43366. };
  43367. img.onerror = function () {
  43368. if (_this.onError) {
  43369. _this.onError(_this);
  43370. }
  43371. onError();
  43372. };
  43373. img.src = this.url;
  43374. };
  43375. return ImageAssetTask;
  43376. }());
  43377. BABYLON.ImageAssetTask = ImageAssetTask;
  43378. var TextureAssetTask = (function () {
  43379. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  43380. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43381. this.name = name;
  43382. this.url = url;
  43383. this.noMipmap = noMipmap;
  43384. this.invertY = invertY;
  43385. this.samplingMode = samplingMode;
  43386. this.isCompleted = false;
  43387. }
  43388. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43389. var _this = this;
  43390. var onload = function () {
  43391. _this.isCompleted = true;
  43392. if (_this.onSuccess) {
  43393. _this.onSuccess(_this);
  43394. }
  43395. onSuccess();
  43396. };
  43397. var onerror = function () {
  43398. if (_this.onError) {
  43399. _this.onError(_this);
  43400. }
  43401. onError();
  43402. };
  43403. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  43404. };
  43405. return TextureAssetTask;
  43406. }());
  43407. BABYLON.TextureAssetTask = TextureAssetTask;
  43408. var CubeTextureAssetTask = (function () {
  43409. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  43410. this.name = name;
  43411. this.url = url;
  43412. this.extensions = extensions;
  43413. this.noMipmap = noMipmap;
  43414. this.files = files;
  43415. this.isCompleted = false;
  43416. }
  43417. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43418. var _this = this;
  43419. var onload = function () {
  43420. _this.isCompleted = true;
  43421. if (_this.onSuccess) {
  43422. _this.onSuccess(_this);
  43423. }
  43424. onSuccess();
  43425. };
  43426. var onerror = function () {
  43427. if (_this.onError) {
  43428. _this.onError(_this);
  43429. }
  43430. onError();
  43431. };
  43432. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  43433. };
  43434. return CubeTextureAssetTask;
  43435. }());
  43436. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  43437. var AssetsManager = (function () {
  43438. function AssetsManager(scene) {
  43439. this.tasks = new Array();
  43440. this.waitingTasksCount = 0;
  43441. this.useDefaultLoadingScreen = true;
  43442. this._scene = scene;
  43443. }
  43444. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  43445. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  43446. this.tasks.push(task);
  43447. return task;
  43448. };
  43449. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  43450. var task = new TextFileAssetTask(taskName, url);
  43451. this.tasks.push(task);
  43452. return task;
  43453. };
  43454. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  43455. var task = new BinaryFileAssetTask(taskName, url);
  43456. this.tasks.push(task);
  43457. return task;
  43458. };
  43459. AssetsManager.prototype.addImageTask = function (taskName, url) {
  43460. var task = new ImageAssetTask(taskName, url);
  43461. this.tasks.push(task);
  43462. return task;
  43463. };
  43464. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  43465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43466. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  43467. this.tasks.push(task);
  43468. return task;
  43469. };
  43470. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  43471. this.waitingTasksCount--;
  43472. if (this.waitingTasksCount === 0) {
  43473. if (this.onFinish) {
  43474. this.onFinish(this.tasks);
  43475. }
  43476. this._scene.getEngine().hideLoadingUI();
  43477. }
  43478. };
  43479. AssetsManager.prototype._runTask = function (task) {
  43480. var _this = this;
  43481. task.run(this._scene, function () {
  43482. if (_this.onTaskSuccess) {
  43483. _this.onTaskSuccess(task);
  43484. }
  43485. _this._decreaseWaitingTasksCount();
  43486. }, function () {
  43487. if (_this.onTaskError) {
  43488. _this.onTaskError(task);
  43489. }
  43490. _this._decreaseWaitingTasksCount();
  43491. });
  43492. };
  43493. AssetsManager.prototype.reset = function () {
  43494. this.tasks = new Array();
  43495. return this;
  43496. };
  43497. AssetsManager.prototype.load = function () {
  43498. this.waitingTasksCount = this.tasks.length;
  43499. if (this.waitingTasksCount === 0) {
  43500. if (this.onFinish) {
  43501. this.onFinish(this.tasks);
  43502. }
  43503. return this;
  43504. }
  43505. if (this.useDefaultLoadingScreen) {
  43506. this._scene.getEngine().displayLoadingUI();
  43507. }
  43508. for (var index = 0; index < this.tasks.length; index++) {
  43509. var task = this.tasks[index];
  43510. this._runTask(task);
  43511. }
  43512. return this;
  43513. };
  43514. return AssetsManager;
  43515. }());
  43516. BABYLON.AssetsManager = AssetsManager;
  43517. })(BABYLON || (BABYLON = {}));
  43518. var BABYLON;
  43519. (function (BABYLON) {
  43520. var VRCameraMetrics = (function () {
  43521. function VRCameraMetrics() {
  43522. this.compensateDistortion = true;
  43523. }
  43524. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  43525. get: function () {
  43526. return this.hResolution / (2 * this.vResolution);
  43527. },
  43528. enumerable: true,
  43529. configurable: true
  43530. });
  43531. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  43532. get: function () {
  43533. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  43534. },
  43535. enumerable: true,
  43536. configurable: true
  43537. });
  43538. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  43539. get: function () {
  43540. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43541. var h = (4 * meters) / this.hScreenSize;
  43542. return BABYLON.Matrix.Translation(h, 0, 0);
  43543. },
  43544. enumerable: true,
  43545. configurable: true
  43546. });
  43547. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  43548. get: function () {
  43549. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43550. var h = (4 * meters) / this.hScreenSize;
  43551. return BABYLON.Matrix.Translation(-h, 0, 0);
  43552. },
  43553. enumerable: true,
  43554. configurable: true
  43555. });
  43556. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  43557. get: function () {
  43558. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  43559. },
  43560. enumerable: true,
  43561. configurable: true
  43562. });
  43563. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  43564. get: function () {
  43565. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  43566. },
  43567. enumerable: true,
  43568. configurable: true
  43569. });
  43570. VRCameraMetrics.GetDefault = function () {
  43571. var result = new VRCameraMetrics();
  43572. result.hResolution = 1280;
  43573. result.vResolution = 800;
  43574. result.hScreenSize = 0.149759993;
  43575. result.vScreenSize = 0.0935999975;
  43576. result.vScreenCenter = 0.0467999987,
  43577. result.eyeToScreenDistance = 0.0410000011;
  43578. result.lensSeparationDistance = 0.0635000020;
  43579. result.interpupillaryDistance = 0.0640000030;
  43580. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  43581. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  43582. result.postProcessScaleFactor = 1.714605507808412;
  43583. result.lensCenterOffset = 0.151976421;
  43584. return result;
  43585. };
  43586. return VRCameraMetrics;
  43587. }());
  43588. BABYLON.VRCameraMetrics = VRCameraMetrics;
  43589. })(BABYLON || (BABYLON = {}));
  43590. var BABYLON;
  43591. (function (BABYLON) {
  43592. var WebVRFreeCamera = (function (_super) {
  43593. __extends(WebVRFreeCamera, _super);
  43594. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  43595. var _this = this;
  43596. if (compensateDistortion === void 0) { compensateDistortion = false; }
  43597. if (webVROptions === void 0) { webVROptions = {}; }
  43598. _super.call(this, name, position, scene);
  43599. this.webVROptions = webVROptions;
  43600. this._vrDevice = null;
  43601. this._cacheState = null;
  43602. this._vrEnabled = false;
  43603. this._attached = false;
  43604. //enable VR
  43605. this.getEngine().initWebVR();
  43606. if (!this.getEngine().vrDisplaysPromise) {
  43607. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  43608. }
  43609. else {
  43610. //TODO get the metrics updated using the device's eye parameters!
  43611. //TODO also check that the device has the right capabilities!
  43612. this._frameData = new VRFrameData();
  43613. this.getEngine().vrDisplaysPromise.then(function (devices) {
  43614. if (devices.length > 0) {
  43615. _this._vrEnabled = true;
  43616. if (_this.webVROptions.displayName) {
  43617. var found = devices.some(function (device) {
  43618. if (device.displayName === _this.webVROptions.displayName) {
  43619. _this._vrDevice = device;
  43620. return true;
  43621. }
  43622. else {
  43623. return false;
  43624. }
  43625. });
  43626. if (!found) {
  43627. _this._vrDevice = devices[0];
  43628. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  43629. }
  43630. }
  43631. else {
  43632. //choose the first one
  43633. _this._vrDevice = devices[0];
  43634. }
  43635. //reset the rig parameters.
  43636. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  43637. if (_this._attached) {
  43638. _this.getEngine().enableVR(_this._vrDevice);
  43639. }
  43640. }
  43641. else {
  43642. BABYLON.Tools.Error("No WebVR devices found!");
  43643. }
  43644. });
  43645. }
  43646. this.rotationQuaternion = new BABYLON.Quaternion();
  43647. this._quaternionCache = new BABYLON.Quaternion();
  43648. }
  43649. WebVRFreeCamera.prototype._checkInputs = function () {
  43650. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  43651. var currentPost = this._frameData.pose;
  43652. //make sure we have data
  43653. if (currentPost && currentPost.orientation) {
  43654. this._cacheState = currentPost;
  43655. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  43656. if (this.webVROptions.trackPosition && this._cacheState.position) {
  43657. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  43658. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  43659. }
  43660. }
  43661. }
  43662. _super.prototype._checkInputs.call(this);
  43663. };
  43664. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43665. _super.prototype.attachControl.call(this, element, noPreventDefault);
  43666. this._attached = true;
  43667. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43668. if (this._vrEnabled) {
  43669. this.getEngine().enableVR(this._vrDevice);
  43670. }
  43671. };
  43672. WebVRFreeCamera.prototype.detachControl = function (element) {
  43673. _super.prototype.detachControl.call(this, element);
  43674. this._vrEnabled = false;
  43675. this._attached = false;
  43676. this.getEngine().disableVR();
  43677. };
  43678. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  43679. //Backwards comp.
  43680. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  43681. //this.getEngine().switchFullscreen(requestPointerlock);
  43682. };
  43683. WebVRFreeCamera.prototype.getTypeName = function () {
  43684. return "WebVRFreeCamera";
  43685. };
  43686. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  43687. //uses the vrDisplay's "resetPose()".
  43688. //pitch and roll won't be affected.
  43689. this._vrDevice.resetPose();
  43690. };
  43691. return WebVRFreeCamera;
  43692. }(BABYLON.FreeCamera));
  43693. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  43694. })(BABYLON || (BABYLON = {}));
  43695. var BABYLON;
  43696. (function (BABYLON) {
  43697. // Standard optimizations
  43698. var SceneOptimization = (function () {
  43699. function SceneOptimization(priority) {
  43700. if (priority === void 0) { priority = 0; }
  43701. this.priority = priority;
  43702. this.apply = function (scene) {
  43703. return true; // Return true if everything that can be done was applied
  43704. };
  43705. }
  43706. return SceneOptimization;
  43707. }());
  43708. BABYLON.SceneOptimization = SceneOptimization;
  43709. var TextureOptimization = (function (_super) {
  43710. __extends(TextureOptimization, _super);
  43711. function TextureOptimization(priority, maximumSize) {
  43712. var _this = this;
  43713. if (priority === void 0) { priority = 0; }
  43714. if (maximumSize === void 0) { maximumSize = 1024; }
  43715. _super.call(this, priority);
  43716. this.priority = priority;
  43717. this.maximumSize = maximumSize;
  43718. this.apply = function (scene) {
  43719. var allDone = true;
  43720. for (var index = 0; index < scene.textures.length; index++) {
  43721. var texture = scene.textures[index];
  43722. if (!texture.canRescale) {
  43723. continue;
  43724. }
  43725. var currentSize = texture.getSize();
  43726. var maxDimension = Math.max(currentSize.width, currentSize.height);
  43727. if (maxDimension > _this.maximumSize) {
  43728. texture.scale(0.5);
  43729. allDone = false;
  43730. }
  43731. }
  43732. return allDone;
  43733. };
  43734. }
  43735. return TextureOptimization;
  43736. }(SceneOptimization));
  43737. BABYLON.TextureOptimization = TextureOptimization;
  43738. var HardwareScalingOptimization = (function (_super) {
  43739. __extends(HardwareScalingOptimization, _super);
  43740. function HardwareScalingOptimization(priority, maximumScale) {
  43741. var _this = this;
  43742. if (priority === void 0) { priority = 0; }
  43743. if (maximumScale === void 0) { maximumScale = 2; }
  43744. _super.call(this, priority);
  43745. this.priority = priority;
  43746. this.maximumScale = maximumScale;
  43747. this._currentScale = 1;
  43748. this.apply = function (scene) {
  43749. _this._currentScale++;
  43750. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  43751. return _this._currentScale >= _this.maximumScale;
  43752. };
  43753. }
  43754. return HardwareScalingOptimization;
  43755. }(SceneOptimization));
  43756. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  43757. var ShadowsOptimization = (function (_super) {
  43758. __extends(ShadowsOptimization, _super);
  43759. function ShadowsOptimization() {
  43760. _super.apply(this, arguments);
  43761. this.apply = function (scene) {
  43762. scene.shadowsEnabled = false;
  43763. return true;
  43764. };
  43765. }
  43766. return ShadowsOptimization;
  43767. }(SceneOptimization));
  43768. BABYLON.ShadowsOptimization = ShadowsOptimization;
  43769. var PostProcessesOptimization = (function (_super) {
  43770. __extends(PostProcessesOptimization, _super);
  43771. function PostProcessesOptimization() {
  43772. _super.apply(this, arguments);
  43773. this.apply = function (scene) {
  43774. scene.postProcessesEnabled = false;
  43775. return true;
  43776. };
  43777. }
  43778. return PostProcessesOptimization;
  43779. }(SceneOptimization));
  43780. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  43781. var LensFlaresOptimization = (function (_super) {
  43782. __extends(LensFlaresOptimization, _super);
  43783. function LensFlaresOptimization() {
  43784. _super.apply(this, arguments);
  43785. this.apply = function (scene) {
  43786. scene.lensFlaresEnabled = false;
  43787. return true;
  43788. };
  43789. }
  43790. return LensFlaresOptimization;
  43791. }(SceneOptimization));
  43792. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  43793. var ParticlesOptimization = (function (_super) {
  43794. __extends(ParticlesOptimization, _super);
  43795. function ParticlesOptimization() {
  43796. _super.apply(this, arguments);
  43797. this.apply = function (scene) {
  43798. scene.particlesEnabled = false;
  43799. return true;
  43800. };
  43801. }
  43802. return ParticlesOptimization;
  43803. }(SceneOptimization));
  43804. BABYLON.ParticlesOptimization = ParticlesOptimization;
  43805. var RenderTargetsOptimization = (function (_super) {
  43806. __extends(RenderTargetsOptimization, _super);
  43807. function RenderTargetsOptimization() {
  43808. _super.apply(this, arguments);
  43809. this.apply = function (scene) {
  43810. scene.renderTargetsEnabled = false;
  43811. return true;
  43812. };
  43813. }
  43814. return RenderTargetsOptimization;
  43815. }(SceneOptimization));
  43816. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  43817. var MergeMeshesOptimization = (function (_super) {
  43818. __extends(MergeMeshesOptimization, _super);
  43819. function MergeMeshesOptimization() {
  43820. var _this = this;
  43821. _super.apply(this, arguments);
  43822. this._canBeMerged = function (abstractMesh) {
  43823. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  43824. return false;
  43825. }
  43826. var mesh = abstractMesh;
  43827. if (!mesh.isVisible || !mesh.isEnabled()) {
  43828. return false;
  43829. }
  43830. if (mesh.instances.length > 0) {
  43831. return false;
  43832. }
  43833. if (mesh.skeleton || mesh.hasLODLevels) {
  43834. return false;
  43835. }
  43836. if (mesh.parent) {
  43837. return false;
  43838. }
  43839. return true;
  43840. };
  43841. this.apply = function (scene, updateSelectionTree) {
  43842. var globalPool = scene.meshes.slice(0);
  43843. var globalLength = globalPool.length;
  43844. for (var index = 0; index < globalLength; index++) {
  43845. var currentPool = new Array();
  43846. var current = globalPool[index];
  43847. // Checks
  43848. if (!_this._canBeMerged(current)) {
  43849. continue;
  43850. }
  43851. currentPool.push(current);
  43852. // Find compatible meshes
  43853. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  43854. var otherMesh = globalPool[subIndex];
  43855. if (!_this._canBeMerged(otherMesh)) {
  43856. continue;
  43857. }
  43858. if (otherMesh.material !== current.material) {
  43859. continue;
  43860. }
  43861. if (otherMesh.checkCollisions !== current.checkCollisions) {
  43862. continue;
  43863. }
  43864. currentPool.push(otherMesh);
  43865. globalLength--;
  43866. globalPool.splice(subIndex, 1);
  43867. subIndex--;
  43868. }
  43869. if (currentPool.length < 2) {
  43870. continue;
  43871. }
  43872. // Merge meshes
  43873. BABYLON.Mesh.MergeMeshes(currentPool);
  43874. }
  43875. if (updateSelectionTree != undefined) {
  43876. if (updateSelectionTree) {
  43877. scene.createOrUpdateSelectionOctree();
  43878. }
  43879. }
  43880. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  43881. scene.createOrUpdateSelectionOctree();
  43882. }
  43883. return true;
  43884. };
  43885. }
  43886. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  43887. get: function () {
  43888. return MergeMeshesOptimization._UpdateSelectionTree;
  43889. },
  43890. set: function (value) {
  43891. MergeMeshesOptimization._UpdateSelectionTree = value;
  43892. },
  43893. enumerable: true,
  43894. configurable: true
  43895. });
  43896. MergeMeshesOptimization._UpdateSelectionTree = false;
  43897. return MergeMeshesOptimization;
  43898. }(SceneOptimization));
  43899. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  43900. // Options
  43901. var SceneOptimizerOptions = (function () {
  43902. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  43903. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  43904. if (trackerDuration === void 0) { trackerDuration = 2000; }
  43905. this.targetFrameRate = targetFrameRate;
  43906. this.trackerDuration = trackerDuration;
  43907. this.optimizations = new Array();
  43908. }
  43909. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  43910. var result = new SceneOptimizerOptions(targetFrameRate);
  43911. var priority = 0;
  43912. result.optimizations.push(new MergeMeshesOptimization(priority));
  43913. result.optimizations.push(new ShadowsOptimization(priority));
  43914. result.optimizations.push(new LensFlaresOptimization(priority));
  43915. // Next priority
  43916. priority++;
  43917. result.optimizations.push(new PostProcessesOptimization(priority));
  43918. result.optimizations.push(new ParticlesOptimization(priority));
  43919. // Next priority
  43920. priority++;
  43921. result.optimizations.push(new TextureOptimization(priority, 1024));
  43922. return result;
  43923. };
  43924. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  43925. var result = new SceneOptimizerOptions(targetFrameRate);
  43926. var priority = 0;
  43927. result.optimizations.push(new MergeMeshesOptimization(priority));
  43928. result.optimizations.push(new ShadowsOptimization(priority));
  43929. result.optimizations.push(new LensFlaresOptimization(priority));
  43930. // Next priority
  43931. priority++;
  43932. result.optimizations.push(new PostProcessesOptimization(priority));
  43933. result.optimizations.push(new ParticlesOptimization(priority));
  43934. // Next priority
  43935. priority++;
  43936. result.optimizations.push(new TextureOptimization(priority, 512));
  43937. // Next priority
  43938. priority++;
  43939. result.optimizations.push(new RenderTargetsOptimization(priority));
  43940. // Next priority
  43941. priority++;
  43942. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  43943. return result;
  43944. };
  43945. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  43946. var result = new SceneOptimizerOptions(targetFrameRate);
  43947. var priority = 0;
  43948. result.optimizations.push(new MergeMeshesOptimization(priority));
  43949. result.optimizations.push(new ShadowsOptimization(priority));
  43950. result.optimizations.push(new LensFlaresOptimization(priority));
  43951. // Next priority
  43952. priority++;
  43953. result.optimizations.push(new PostProcessesOptimization(priority));
  43954. result.optimizations.push(new ParticlesOptimization(priority));
  43955. // Next priority
  43956. priority++;
  43957. result.optimizations.push(new TextureOptimization(priority, 256));
  43958. // Next priority
  43959. priority++;
  43960. result.optimizations.push(new RenderTargetsOptimization(priority));
  43961. // Next priority
  43962. priority++;
  43963. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  43964. return result;
  43965. };
  43966. return SceneOptimizerOptions;
  43967. }());
  43968. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  43969. // Scene optimizer tool
  43970. var SceneOptimizer = (function () {
  43971. function SceneOptimizer() {
  43972. }
  43973. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  43974. // TODO: add an epsilon
  43975. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  43976. if (onSuccess) {
  43977. onSuccess();
  43978. }
  43979. return;
  43980. }
  43981. // Apply current level of optimizations
  43982. var allDone = true;
  43983. var noOptimizationApplied = true;
  43984. for (var index = 0; index < options.optimizations.length; index++) {
  43985. var optimization = options.optimizations[index];
  43986. if (optimization.priority === currentPriorityLevel) {
  43987. noOptimizationApplied = false;
  43988. allDone = allDone && optimization.apply(scene);
  43989. }
  43990. }
  43991. // If no optimization was applied, this is a failure :(
  43992. if (noOptimizationApplied) {
  43993. if (onFailure) {
  43994. onFailure();
  43995. }
  43996. return;
  43997. }
  43998. // If all optimizations were done, move to next level
  43999. if (allDone) {
  44000. currentPriorityLevel++;
  44001. }
  44002. // Let's the system running for a specific amount of time before checking FPS
  44003. scene.executeWhenReady(function () {
  44004. setTimeout(function () {
  44005. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  44006. }, options.trackerDuration);
  44007. });
  44008. };
  44009. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  44010. if (!options) {
  44011. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  44012. }
  44013. // Let's the system running for a specific amount of time before checking FPS
  44014. scene.executeWhenReady(function () {
  44015. setTimeout(function () {
  44016. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  44017. }, options.trackerDuration);
  44018. });
  44019. };
  44020. return SceneOptimizer;
  44021. }());
  44022. BABYLON.SceneOptimizer = SceneOptimizer;
  44023. })(BABYLON || (BABYLON = {}));
  44024. var BABYLON;
  44025. (function (BABYLON) {
  44026. var Internals;
  44027. (function (Internals) {
  44028. var MeshLODLevel = (function () {
  44029. function MeshLODLevel(distance, mesh) {
  44030. this.distance = distance;
  44031. this.mesh = mesh;
  44032. }
  44033. return MeshLODLevel;
  44034. }());
  44035. Internals.MeshLODLevel = MeshLODLevel;
  44036. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44037. })(BABYLON || (BABYLON = {}));
  44038. var BABYLON;
  44039. (function (BABYLON) {
  44040. var RawTexture = (function (_super) {
  44041. __extends(RawTexture, _super);
  44042. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  44043. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44044. if (invertY === void 0) { invertY = false; }
  44045. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44046. _super.call(this, null, scene, !generateMipMaps, invertY);
  44047. this.format = format;
  44048. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  44049. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44050. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44051. }
  44052. RawTexture.prototype.update = function (data) {
  44053. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  44054. };
  44055. // Statics
  44056. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44057. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44058. if (invertY === void 0) { invertY = false; }
  44059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44060. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  44061. };
  44062. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44063. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44064. if (invertY === void 0) { invertY = false; }
  44065. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44066. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44067. };
  44068. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44069. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44070. if (invertY === void 0) { invertY = false; }
  44071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44072. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44073. };
  44074. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44075. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44076. if (invertY === void 0) { invertY = false; }
  44077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44078. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  44079. };
  44080. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44081. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44082. if (invertY === void 0) { invertY = false; }
  44083. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44084. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  44085. };
  44086. return RawTexture;
  44087. }(BABYLON.Texture));
  44088. BABYLON.RawTexture = RawTexture;
  44089. })(BABYLON || (BABYLON = {}));
  44090. var BABYLON;
  44091. (function (BABYLON) {
  44092. var IndexedVector2 = (function (_super) {
  44093. __extends(IndexedVector2, _super);
  44094. function IndexedVector2(original, index) {
  44095. _super.call(this, original.x, original.y);
  44096. this.index = index;
  44097. }
  44098. return IndexedVector2;
  44099. }(BABYLON.Vector2));
  44100. var PolygonPoints = (function () {
  44101. function PolygonPoints() {
  44102. this.elements = new Array();
  44103. }
  44104. PolygonPoints.prototype.add = function (originalPoints) {
  44105. var _this = this;
  44106. var result = new Array();
  44107. originalPoints.forEach(function (point) {
  44108. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  44109. var newPoint = new IndexedVector2(point, _this.elements.length);
  44110. result.push(newPoint);
  44111. _this.elements.push(newPoint);
  44112. }
  44113. });
  44114. return result;
  44115. };
  44116. PolygonPoints.prototype.computeBounds = function () {
  44117. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  44118. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  44119. this.elements.forEach(function (point) {
  44120. // x
  44121. if (point.x < lmin.x) {
  44122. lmin.x = point.x;
  44123. }
  44124. else if (point.x > lmax.x) {
  44125. lmax.x = point.x;
  44126. }
  44127. // y
  44128. if (point.y < lmin.y) {
  44129. lmin.y = point.y;
  44130. }
  44131. else if (point.y > lmax.y) {
  44132. lmax.y = point.y;
  44133. }
  44134. });
  44135. return {
  44136. min: lmin,
  44137. max: lmax,
  44138. width: lmax.x - lmin.x,
  44139. height: lmax.y - lmin.y
  44140. };
  44141. };
  44142. return PolygonPoints;
  44143. }());
  44144. var Polygon = (function () {
  44145. function Polygon() {
  44146. }
  44147. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  44148. return [
  44149. new BABYLON.Vector2(xmin, ymin),
  44150. new BABYLON.Vector2(xmax, ymin),
  44151. new BABYLON.Vector2(xmax, ymax),
  44152. new BABYLON.Vector2(xmin, ymax)
  44153. ];
  44154. };
  44155. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  44156. if (cx === void 0) { cx = 0; }
  44157. if (cy === void 0) { cy = 0; }
  44158. if (numberOfSides === void 0) { numberOfSides = 32; }
  44159. var result = new Array();
  44160. var angle = 0;
  44161. var increment = (Math.PI * 2) / numberOfSides;
  44162. for (var i = 0; i < numberOfSides; i++) {
  44163. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  44164. angle -= increment;
  44165. }
  44166. return result;
  44167. };
  44168. Polygon.Parse = function (input) {
  44169. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  44170. var i, result = [];
  44171. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  44172. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  44173. }
  44174. return result;
  44175. };
  44176. Polygon.StartingAt = function (x, y) {
  44177. return BABYLON.Path2.StartingAt(x, y);
  44178. };
  44179. return Polygon;
  44180. }());
  44181. BABYLON.Polygon = Polygon;
  44182. var PolygonMeshBuilder = (function () {
  44183. function PolygonMeshBuilder(name, contours, scene) {
  44184. this._points = new PolygonPoints();
  44185. this._outlinepoints = new PolygonPoints();
  44186. this._holes = [];
  44187. this._epoints = new Array();
  44188. this._eholes = new Array();
  44189. this._name = name;
  44190. this._scene = scene;
  44191. var points;
  44192. if (contours instanceof BABYLON.Path2) {
  44193. points = contours.getPoints();
  44194. }
  44195. else {
  44196. points = contours;
  44197. }
  44198. this._addToepoint(points);
  44199. this._points.add(points);
  44200. this._outlinepoints.add(points);
  44201. }
  44202. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  44203. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  44204. var p = points_1[_i];
  44205. this._epoints.push(p.x, p.y);
  44206. }
  44207. };
  44208. PolygonMeshBuilder.prototype.addHole = function (hole) {
  44209. this._points.add(hole);
  44210. var holepoints = new PolygonPoints();
  44211. holepoints.add(hole);
  44212. this._holes.push(holepoints);
  44213. this._eholes.push(this._epoints.length / 2);
  44214. this._addToepoint(hole);
  44215. return this;
  44216. };
  44217. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  44218. var _this = this;
  44219. if (updatable === void 0) { updatable = false; }
  44220. var result = new BABYLON.Mesh(this._name, this._scene);
  44221. var normals = [];
  44222. var positions = [];
  44223. var uvs = [];
  44224. var bounds = this._points.computeBounds();
  44225. this._points.elements.forEach(function (p) {
  44226. normals.push(0, 1.0, 0);
  44227. positions.push(p.x, 0, p.y);
  44228. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  44229. });
  44230. var indices = [];
  44231. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  44232. for (var i = 0; i < res.length; i++) {
  44233. indices.push(res[i]);
  44234. }
  44235. if (depth > 0) {
  44236. var positionscount = (positions.length / 3); //get the current pointcount
  44237. this._points.elements.forEach(function (p) {
  44238. normals.push(0, -1.0, 0);
  44239. positions.push(p.x, -depth, p.y);
  44240. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  44241. });
  44242. var totalCount = indices.length;
  44243. for (var i = 0; i < totalCount; i += 3) {
  44244. var i0 = indices[i + 0];
  44245. var i1 = indices[i + 1];
  44246. var i2 = indices[i + 2];
  44247. indices.push(i2 + positionscount);
  44248. indices.push(i1 + positionscount);
  44249. indices.push(i0 + positionscount);
  44250. }
  44251. //Add the sides
  44252. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  44253. this._holes.forEach(function (hole) {
  44254. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  44255. });
  44256. }
  44257. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  44258. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  44259. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  44260. result.setIndices(indices);
  44261. return result;
  44262. };
  44263. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  44264. var StartIndex = positions.length / 3;
  44265. var ulength = 0;
  44266. for (var i = 0; i < points.elements.length; i++) {
  44267. var p = points.elements[i];
  44268. var p1;
  44269. if ((i + 1) > points.elements.length - 1) {
  44270. p1 = points.elements[0];
  44271. }
  44272. else {
  44273. p1 = points.elements[i + 1];
  44274. }
  44275. positions.push(p.x, 0, p.y);
  44276. positions.push(p.x, -depth, p.y);
  44277. positions.push(p1.x, 0, p1.y);
  44278. positions.push(p1.x, -depth, p1.y);
  44279. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  44280. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  44281. var v3 = v2.subtract(v1);
  44282. var v4 = new BABYLON.Vector3(0, 1, 0);
  44283. var vn = BABYLON.Vector3.Cross(v3, v4);
  44284. vn = vn.normalize();
  44285. uvs.push(ulength / bounds.width, 0);
  44286. uvs.push(ulength / bounds.width, 1);
  44287. ulength += v3.length();
  44288. uvs.push((ulength / bounds.width), 0);
  44289. uvs.push((ulength / bounds.width), 1);
  44290. if (!flip) {
  44291. normals.push(-vn.x, -vn.y, -vn.z);
  44292. normals.push(-vn.x, -vn.y, -vn.z);
  44293. normals.push(-vn.x, -vn.y, -vn.z);
  44294. normals.push(-vn.x, -vn.y, -vn.z);
  44295. indices.push(StartIndex);
  44296. indices.push(StartIndex + 1);
  44297. indices.push(StartIndex + 2);
  44298. indices.push(StartIndex + 1);
  44299. indices.push(StartIndex + 3);
  44300. indices.push(StartIndex + 2);
  44301. }
  44302. else {
  44303. normals.push(vn.x, vn.y, vn.z);
  44304. normals.push(vn.x, vn.y, vn.z);
  44305. normals.push(vn.x, vn.y, vn.z);
  44306. normals.push(vn.x, vn.y, vn.z);
  44307. indices.push(StartIndex);
  44308. indices.push(StartIndex + 2);
  44309. indices.push(StartIndex + 1);
  44310. indices.push(StartIndex + 1);
  44311. indices.push(StartIndex + 2);
  44312. indices.push(StartIndex + 3);
  44313. }
  44314. StartIndex += 4;
  44315. }
  44316. ;
  44317. };
  44318. return PolygonMeshBuilder;
  44319. }());
  44320. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  44321. })(BABYLON || (BABYLON = {}));
  44322. var BABYLON;
  44323. (function (BABYLON) {
  44324. var Octree = (function () {
  44325. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  44326. if (maxDepth === void 0) { maxDepth = 2; }
  44327. this.maxDepth = maxDepth;
  44328. this.dynamicContent = new Array();
  44329. this._maxBlockCapacity = maxBlockCapacity || 64;
  44330. this._selectionContent = new BABYLON.SmartArray(1024);
  44331. this._creationFunc = creationFunc;
  44332. }
  44333. // Methods
  44334. Octree.prototype.update = function (worldMin, worldMax, entries) {
  44335. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  44336. };
  44337. Octree.prototype.addMesh = function (entry) {
  44338. for (var index = 0; index < this.blocks.length; index++) {
  44339. var block = this.blocks[index];
  44340. block.addEntry(entry);
  44341. }
  44342. };
  44343. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  44344. this._selectionContent.reset();
  44345. for (var index = 0; index < this.blocks.length; index++) {
  44346. var block = this.blocks[index];
  44347. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  44348. }
  44349. if (allowDuplicate) {
  44350. this._selectionContent.concat(this.dynamicContent);
  44351. }
  44352. else {
  44353. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44354. }
  44355. return this._selectionContent;
  44356. };
  44357. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  44358. this._selectionContent.reset();
  44359. for (var index = 0; index < this.blocks.length; index++) {
  44360. var block = this.blocks[index];
  44361. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  44362. }
  44363. if (allowDuplicate) {
  44364. this._selectionContent.concat(this.dynamicContent);
  44365. }
  44366. else {
  44367. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44368. }
  44369. return this._selectionContent;
  44370. };
  44371. Octree.prototype.intersectsRay = function (ray) {
  44372. this._selectionContent.reset();
  44373. for (var index = 0; index < this.blocks.length; index++) {
  44374. var block = this.blocks[index];
  44375. block.intersectsRay(ray, this._selectionContent);
  44376. }
  44377. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44378. return this._selectionContent;
  44379. };
  44380. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  44381. target.blocks = new Array();
  44382. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  44383. // Segmenting space
  44384. for (var x = 0; x < 2; x++) {
  44385. for (var y = 0; y < 2; y++) {
  44386. for (var z = 0; z < 2; z++) {
  44387. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  44388. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  44389. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  44390. block.addEntries(entries);
  44391. target.blocks.push(block);
  44392. }
  44393. }
  44394. }
  44395. };
  44396. Octree.CreationFuncForMeshes = function (entry, block) {
  44397. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44398. block.entries.push(entry);
  44399. }
  44400. };
  44401. Octree.CreationFuncForSubMeshes = function (entry, block) {
  44402. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44403. block.entries.push(entry);
  44404. }
  44405. };
  44406. return Octree;
  44407. }());
  44408. BABYLON.Octree = Octree;
  44409. })(BABYLON || (BABYLON = {}));
  44410. var BABYLON;
  44411. (function (BABYLON) {
  44412. var OctreeBlock = (function () {
  44413. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  44414. this.entries = new Array();
  44415. this._boundingVectors = new Array();
  44416. this._capacity = capacity;
  44417. this._depth = depth;
  44418. this._maxDepth = maxDepth;
  44419. this._creationFunc = creationFunc;
  44420. this._minPoint = minPoint;
  44421. this._maxPoint = maxPoint;
  44422. this._boundingVectors.push(minPoint.clone());
  44423. this._boundingVectors.push(maxPoint.clone());
  44424. this._boundingVectors.push(minPoint.clone());
  44425. this._boundingVectors[2].x = maxPoint.x;
  44426. this._boundingVectors.push(minPoint.clone());
  44427. this._boundingVectors[3].y = maxPoint.y;
  44428. this._boundingVectors.push(minPoint.clone());
  44429. this._boundingVectors[4].z = maxPoint.z;
  44430. this._boundingVectors.push(maxPoint.clone());
  44431. this._boundingVectors[5].z = minPoint.z;
  44432. this._boundingVectors.push(maxPoint.clone());
  44433. this._boundingVectors[6].x = minPoint.x;
  44434. this._boundingVectors.push(maxPoint.clone());
  44435. this._boundingVectors[7].y = minPoint.y;
  44436. }
  44437. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  44438. // Property
  44439. get: function () {
  44440. return this._capacity;
  44441. },
  44442. enumerable: true,
  44443. configurable: true
  44444. });
  44445. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  44446. get: function () {
  44447. return this._minPoint;
  44448. },
  44449. enumerable: true,
  44450. configurable: true
  44451. });
  44452. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  44453. get: function () {
  44454. return this._maxPoint;
  44455. },
  44456. enumerable: true,
  44457. configurable: true
  44458. });
  44459. // Methods
  44460. OctreeBlock.prototype.addEntry = function (entry) {
  44461. if (this.blocks) {
  44462. for (var index = 0; index < this.blocks.length; index++) {
  44463. var block = this.blocks[index];
  44464. block.addEntry(entry);
  44465. }
  44466. return;
  44467. }
  44468. this._creationFunc(entry, this);
  44469. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  44470. this.createInnerBlocks();
  44471. }
  44472. };
  44473. OctreeBlock.prototype.addEntries = function (entries) {
  44474. for (var index = 0; index < entries.length; index++) {
  44475. var mesh = entries[index];
  44476. this.addEntry(mesh);
  44477. }
  44478. };
  44479. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  44480. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  44481. if (this.blocks) {
  44482. for (var index = 0; index < this.blocks.length; index++) {
  44483. var block = this.blocks[index];
  44484. block.select(frustumPlanes, selection, allowDuplicate);
  44485. }
  44486. return;
  44487. }
  44488. if (allowDuplicate) {
  44489. selection.concat(this.entries);
  44490. }
  44491. else {
  44492. selection.concatWithNoDuplicate(this.entries);
  44493. }
  44494. }
  44495. };
  44496. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  44497. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  44498. if (this.blocks) {
  44499. for (var index = 0; index < this.blocks.length; index++) {
  44500. var block = this.blocks[index];
  44501. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  44502. }
  44503. return;
  44504. }
  44505. if (allowDuplicate) {
  44506. selection.concat(this.entries);
  44507. }
  44508. else {
  44509. selection.concatWithNoDuplicate(this.entries);
  44510. }
  44511. }
  44512. };
  44513. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  44514. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  44515. if (this.blocks) {
  44516. for (var index = 0; index < this.blocks.length; index++) {
  44517. var block = this.blocks[index];
  44518. block.intersectsRay(ray, selection);
  44519. }
  44520. return;
  44521. }
  44522. selection.concatWithNoDuplicate(this.entries);
  44523. }
  44524. };
  44525. OctreeBlock.prototype.createInnerBlocks = function () {
  44526. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  44527. };
  44528. return OctreeBlock;
  44529. }());
  44530. BABYLON.OctreeBlock = OctreeBlock;
  44531. })(BABYLON || (BABYLON = {}));
  44532. var BABYLON;
  44533. (function (BABYLON) {
  44534. var BlurPostProcess = (function (_super) {
  44535. __extends(BlurPostProcess, _super);
  44536. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  44537. var _this = this;
  44538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  44539. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  44540. this.direction = direction;
  44541. this.blurWidth = blurWidth;
  44542. this.onApplyObservable.add(function (effect) {
  44543. effect.setFloat2("screenSize", _this.width, _this.height);
  44544. effect.setVector2("direction", _this.direction);
  44545. effect.setFloat("blurWidth", _this.blurWidth);
  44546. });
  44547. }
  44548. return BlurPostProcess;
  44549. }(BABYLON.PostProcess));
  44550. BABYLON.BlurPostProcess = BlurPostProcess;
  44551. })(BABYLON || (BABYLON = {}));
  44552. var BABYLON;
  44553. (function (BABYLON) {
  44554. var RefractionPostProcess = (function (_super) {
  44555. __extends(RefractionPostProcess, _super);
  44556. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  44557. var _this = this;
  44558. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  44559. this.color = color;
  44560. this.depth = depth;
  44561. this.colorLevel = colorLevel;
  44562. this.onActivateObservable.add(function (cam) {
  44563. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  44564. });
  44565. this.onApplyObservable.add(function (effect) {
  44566. effect.setColor3("baseColor", _this.color);
  44567. effect.setFloat("depth", _this.depth);
  44568. effect.setFloat("colorLevel", _this.colorLevel);
  44569. effect.setTexture("refractionSampler", _this._refRexture);
  44570. });
  44571. }
  44572. // Methods
  44573. RefractionPostProcess.prototype.dispose = function (camera) {
  44574. if (this._refRexture) {
  44575. this._refRexture.dispose();
  44576. }
  44577. _super.prototype.dispose.call(this, camera);
  44578. };
  44579. return RefractionPostProcess;
  44580. }(BABYLON.PostProcess));
  44581. BABYLON.RefractionPostProcess = RefractionPostProcess;
  44582. })(BABYLON || (BABYLON = {}));
  44583. var BABYLON;
  44584. (function (BABYLON) {
  44585. var BlackAndWhitePostProcess = (function (_super) {
  44586. __extends(BlackAndWhitePostProcess, _super);
  44587. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  44588. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  44589. }
  44590. return BlackAndWhitePostProcess;
  44591. }(BABYLON.PostProcess));
  44592. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  44593. })(BABYLON || (BABYLON = {}));
  44594. var BABYLON;
  44595. (function (BABYLON) {
  44596. var ConvolutionPostProcess = (function (_super) {
  44597. __extends(ConvolutionPostProcess, _super);
  44598. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  44599. var _this = this;
  44600. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  44601. this.kernel = kernel;
  44602. this.onApply = function (effect) {
  44603. effect.setFloat2("screenSize", _this.width, _this.height);
  44604. effect.setArray("kernel", _this.kernel);
  44605. };
  44606. }
  44607. // Statics
  44608. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  44609. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  44610. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  44611. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  44612. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  44613. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  44614. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  44615. return ConvolutionPostProcess;
  44616. }(BABYLON.PostProcess));
  44617. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  44618. })(BABYLON || (BABYLON = {}));
  44619. var BABYLON;
  44620. (function (BABYLON) {
  44621. var FilterPostProcess = (function (_super) {
  44622. __extends(FilterPostProcess, _super);
  44623. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  44624. var _this = this;
  44625. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  44626. this.kernelMatrix = kernelMatrix;
  44627. this.onApply = function (effect) {
  44628. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  44629. };
  44630. }
  44631. return FilterPostProcess;
  44632. }(BABYLON.PostProcess));
  44633. BABYLON.FilterPostProcess = FilterPostProcess;
  44634. })(BABYLON || (BABYLON = {}));
  44635. var BABYLON;
  44636. (function (BABYLON) {
  44637. var FxaaPostProcess = (function (_super) {
  44638. __extends(FxaaPostProcess, _super);
  44639. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  44640. var _this = this;
  44641. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  44642. this.onSizeChangedObservable.add(function () {
  44643. _this.texelWidth = 1.0 / _this.width;
  44644. _this.texelHeight = 1.0 / _this.height;
  44645. });
  44646. this.onApplyObservable.add(function (effect) {
  44647. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  44648. });
  44649. }
  44650. return FxaaPostProcess;
  44651. }(BABYLON.PostProcess));
  44652. BABYLON.FxaaPostProcess = FxaaPostProcess;
  44653. })(BABYLON || (BABYLON = {}));
  44654. var BABYLON;
  44655. (function (BABYLON) {
  44656. var StereoscopicInterlacePostProcess = (function (_super) {
  44657. __extends(StereoscopicInterlacePostProcess, _super);
  44658. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  44659. var _this = this;
  44660. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  44661. this._passedProcess = rigCameras[0]._rigPostProcess;
  44662. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  44663. this.onSizeChangedObservable.add(function () {
  44664. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  44665. });
  44666. this.onApplyObservable.add(function (effect) {
  44667. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  44668. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  44669. });
  44670. }
  44671. return StereoscopicInterlacePostProcess;
  44672. }(BABYLON.PostProcess));
  44673. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  44674. })(BABYLON || (BABYLON = {}));
  44675. var BABYLON;
  44676. (function (BABYLON) {
  44677. var LensFlare = (function () {
  44678. function LensFlare(size, position, color, imgUrl, system) {
  44679. this.size = size;
  44680. this.position = position;
  44681. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  44682. this.dispose = function () {
  44683. if (this.texture) {
  44684. this.texture.dispose();
  44685. }
  44686. // Remove from scene
  44687. var index = this._system.lensFlares.indexOf(this);
  44688. this._system.lensFlares.splice(index, 1);
  44689. };
  44690. this.color = color || new BABYLON.Color3(1, 1, 1);
  44691. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  44692. this._system = system;
  44693. system.lensFlares.push(this);
  44694. }
  44695. return LensFlare;
  44696. }());
  44697. BABYLON.LensFlare = LensFlare;
  44698. })(BABYLON || (BABYLON = {}));
  44699. var BABYLON;
  44700. (function (BABYLON) {
  44701. var LensFlareSystem = (function () {
  44702. function LensFlareSystem(name, emitter, scene) {
  44703. this.name = name;
  44704. this.lensFlares = new Array();
  44705. this.borderLimit = 300;
  44706. this.viewportBorder = 0;
  44707. this.layerMask = 0x0FFFFFFF;
  44708. this._vertexBuffers = {};
  44709. this._isEnabled = true;
  44710. this._scene = scene;
  44711. this._emitter = emitter;
  44712. this.id = name;
  44713. scene.lensFlareSystems.push(this);
  44714. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  44715. var engine = scene.getEngine();
  44716. // VBO
  44717. var vertices = [];
  44718. vertices.push(1, 1);
  44719. vertices.push(-1, 1);
  44720. vertices.push(-1, -1);
  44721. vertices.push(1, -1);
  44722. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44723. // Indices
  44724. var indices = [];
  44725. indices.push(0);
  44726. indices.push(1);
  44727. indices.push(2);
  44728. indices.push(0);
  44729. indices.push(2);
  44730. indices.push(3);
  44731. this._indexBuffer = engine.createIndexBuffer(indices);
  44732. // Effects
  44733. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  44734. }
  44735. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  44736. get: function () {
  44737. return this._isEnabled;
  44738. },
  44739. set: function (value) {
  44740. this._isEnabled = value;
  44741. },
  44742. enumerable: true,
  44743. configurable: true
  44744. });
  44745. LensFlareSystem.prototype.getScene = function () {
  44746. return this._scene;
  44747. };
  44748. LensFlareSystem.prototype.getEmitter = function () {
  44749. return this._emitter;
  44750. };
  44751. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  44752. this._emitter = newEmitter;
  44753. };
  44754. LensFlareSystem.prototype.getEmitterPosition = function () {
  44755. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  44756. };
  44757. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  44758. var position = this.getEmitterPosition();
  44759. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  44760. this._positionX = position.x;
  44761. this._positionY = position.y;
  44762. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  44763. if (this.viewportBorder > 0) {
  44764. globalViewport.x -= this.viewportBorder;
  44765. globalViewport.y -= this.viewportBorder;
  44766. globalViewport.width += this.viewportBorder * 2;
  44767. globalViewport.height += this.viewportBorder * 2;
  44768. position.x += this.viewportBorder;
  44769. position.y += this.viewportBorder;
  44770. this._positionX += this.viewportBorder;
  44771. this._positionY += this.viewportBorder;
  44772. }
  44773. if (position.z > 0) {
  44774. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  44775. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  44776. return true;
  44777. }
  44778. return true;
  44779. }
  44780. return false;
  44781. };
  44782. LensFlareSystem.prototype._isVisible = function () {
  44783. if (!this._isEnabled) {
  44784. return false;
  44785. }
  44786. var emitterPosition = this.getEmitterPosition();
  44787. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  44788. var distance = direction.length();
  44789. direction.normalize();
  44790. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  44791. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  44792. return !pickInfo.hit || pickInfo.distance > distance;
  44793. };
  44794. LensFlareSystem.prototype.render = function () {
  44795. if (!this._effect.isReady())
  44796. return false;
  44797. var engine = this._scene.getEngine();
  44798. var viewport = this._scene.activeCamera.viewport;
  44799. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  44800. // Position
  44801. if (!this.computeEffectivePosition(globalViewport)) {
  44802. return false;
  44803. }
  44804. // Visibility
  44805. if (!this._isVisible()) {
  44806. return false;
  44807. }
  44808. // Intensity
  44809. var awayX;
  44810. var awayY;
  44811. if (this._positionX < this.borderLimit + globalViewport.x) {
  44812. awayX = this.borderLimit + globalViewport.x - this._positionX;
  44813. }
  44814. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  44815. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  44816. }
  44817. else {
  44818. awayX = 0;
  44819. }
  44820. if (this._positionY < this.borderLimit + globalViewport.y) {
  44821. awayY = this.borderLimit + globalViewport.y - this._positionY;
  44822. }
  44823. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  44824. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  44825. }
  44826. else {
  44827. awayY = 0;
  44828. }
  44829. var away = (awayX > awayY) ? awayX : awayY;
  44830. away -= this.viewportBorder;
  44831. if (away > this.borderLimit) {
  44832. away = this.borderLimit;
  44833. }
  44834. var intensity = 1.0 - (away / this.borderLimit);
  44835. if (intensity < 0) {
  44836. return false;
  44837. }
  44838. if (intensity > 1.0) {
  44839. intensity = 1.0;
  44840. }
  44841. if (this.viewportBorder > 0) {
  44842. globalViewport.x += this.viewportBorder;
  44843. globalViewport.y += this.viewportBorder;
  44844. globalViewport.width -= this.viewportBorder * 2;
  44845. globalViewport.height -= this.viewportBorder * 2;
  44846. this._positionX -= this.viewportBorder;
  44847. this._positionY -= this.viewportBorder;
  44848. }
  44849. // Position
  44850. var centerX = globalViewport.x + globalViewport.width / 2;
  44851. var centerY = globalViewport.y + globalViewport.height / 2;
  44852. var distX = centerX - this._positionX;
  44853. var distY = centerY - this._positionY;
  44854. // Effects
  44855. engine.enableEffect(this._effect);
  44856. engine.setState(false);
  44857. engine.setDepthBuffer(false);
  44858. // VBOs
  44859. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44860. // Flares
  44861. for (var index = 0; index < this.lensFlares.length; index++) {
  44862. var flare = this.lensFlares[index];
  44863. engine.setAlphaMode(flare.alphaMode);
  44864. var x = centerX - (distX * flare.position);
  44865. var y = centerY - (distY * flare.position);
  44866. var cw = flare.size;
  44867. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  44868. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  44869. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  44870. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  44871. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  44872. // Texture
  44873. this._effect.setTexture("textureSampler", flare.texture);
  44874. // Color
  44875. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  44876. // Draw order
  44877. engine.draw(true, 0, 6);
  44878. }
  44879. engine.setDepthBuffer(true);
  44880. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44881. return true;
  44882. };
  44883. LensFlareSystem.prototype.dispose = function () {
  44884. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  44885. if (vertexBuffer) {
  44886. vertexBuffer.dispose();
  44887. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  44888. }
  44889. if (this._indexBuffer) {
  44890. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44891. this._indexBuffer = null;
  44892. }
  44893. while (this.lensFlares.length) {
  44894. this.lensFlares[0].dispose();
  44895. }
  44896. // Remove from scene
  44897. var index = this._scene.lensFlareSystems.indexOf(this);
  44898. this._scene.lensFlareSystems.splice(index, 1);
  44899. };
  44900. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  44901. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  44902. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  44903. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  44904. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  44905. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  44906. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  44907. var parsedFlare = parsedLensFlareSystem.flares[index];
  44908. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  44909. }
  44910. return lensFlareSystem;
  44911. };
  44912. LensFlareSystem.prototype.serialize = function () {
  44913. var serializationObject = {};
  44914. serializationObject.id = this.id;
  44915. serializationObject.name = this.name;
  44916. serializationObject.emitterId = this.getEmitter().id;
  44917. serializationObject.borderLimit = this.borderLimit;
  44918. serializationObject.flares = [];
  44919. for (var index = 0; index < this.lensFlares.length; index++) {
  44920. var flare = this.lensFlares[index];
  44921. serializationObject.flares.push({
  44922. size: flare.size,
  44923. position: flare.position,
  44924. color: flare.color.asArray(),
  44925. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  44926. });
  44927. }
  44928. return serializationObject;
  44929. };
  44930. return LensFlareSystem;
  44931. }());
  44932. BABYLON.LensFlareSystem = LensFlareSystem;
  44933. })(BABYLON || (BABYLON = {}));
  44934. var BABYLON;
  44935. (function (BABYLON) {
  44936. // We're mainly based on the logic defined into the FreeCamera code
  44937. var DeviceOrientationCamera = (function (_super) {
  44938. __extends(DeviceOrientationCamera, _super);
  44939. function DeviceOrientationCamera(name, position, scene) {
  44940. _super.call(this, name, position, scene);
  44941. this._quaternionCache = new BABYLON.Quaternion();
  44942. this.inputs.addDeviceOrientation();
  44943. }
  44944. DeviceOrientationCamera.prototype.getTypeName = function () {
  44945. return "DeviceOrientationCamera";
  44946. };
  44947. DeviceOrientationCamera.prototype._checkInputs = function () {
  44948. _super.prototype._checkInputs.call(this);
  44949. this._quaternionCache.copyFrom(this.rotationQuaternion);
  44950. if (this._initialQuaternion) {
  44951. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  44952. }
  44953. };
  44954. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  44955. var _this = this;
  44956. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  44957. //can only work if this camera has a rotation quaternion already.
  44958. if (!this.rotationQuaternion)
  44959. return;
  44960. if (!this._initialQuaternion) {
  44961. this._initialQuaternion = new BABYLON.Quaternion();
  44962. }
  44963. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  44964. ['x', 'y', 'z'].forEach(function (axisName) {
  44965. if (!axis[axisName]) {
  44966. _this._initialQuaternion[axisName] = 0;
  44967. }
  44968. else {
  44969. _this._initialQuaternion[axisName] *= -1;
  44970. }
  44971. });
  44972. this._initialQuaternion.normalize();
  44973. //force rotation update
  44974. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  44975. };
  44976. return DeviceOrientationCamera;
  44977. }(BABYLON.FreeCamera));
  44978. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  44979. })(BABYLON || (BABYLON = {}));
  44980. var BABYLON;
  44981. (function (BABYLON) {
  44982. var VRDeviceOrientationFreeCamera = (function (_super) {
  44983. __extends(VRDeviceOrientationFreeCamera, _super);
  44984. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  44985. if (compensateDistortion === void 0) { compensateDistortion = true; }
  44986. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  44987. _super.call(this, name, position, scene);
  44988. vrCameraMetrics.compensateDistortion = compensateDistortion;
  44989. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  44990. }
  44991. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  44992. return "VRDeviceOrientationFreeCamera";
  44993. };
  44994. return VRDeviceOrientationFreeCamera;
  44995. }(BABYLON.DeviceOrientationCamera));
  44996. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  44997. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  44998. __extends(VRDeviceOrientationArcRotateCamera, _super);
  44999. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  45000. if (compensateDistortion === void 0) { compensateDistortion = true; }
  45001. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  45002. _super.call(this, name, alpha, beta, radius, target, scene);
  45003. vrCameraMetrics.compensateDistortion = compensateDistortion;
  45004. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  45005. this.inputs.addVRDeviceOrientation();
  45006. }
  45007. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  45008. return "VRDeviceOrientationArcRotateCamera";
  45009. };
  45010. return VRDeviceOrientationArcRotateCamera;
  45011. }(BABYLON.ArcRotateCamera));
  45012. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  45013. })(BABYLON || (BABYLON = {}));
  45014. var BABYLON;
  45015. (function (BABYLON) {
  45016. // We're mainly based on the logic defined into the FreeCamera code
  45017. var UniversalCamera = (function (_super) {
  45018. __extends(UniversalCamera, _super);
  45019. //-- end properties for backward compatibility for inputs
  45020. function UniversalCamera(name, position, scene) {
  45021. _super.call(this, name, position, scene);
  45022. this.inputs.addGamepad();
  45023. }
  45024. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  45025. //-- Begin properties for backward compatibility for inputs
  45026. get: function () {
  45027. var gamepad = this.inputs.attached["gamepad"];
  45028. if (gamepad)
  45029. return gamepad.gamepadAngularSensibility;
  45030. },
  45031. set: function (value) {
  45032. var gamepad = this.inputs.attached["gamepad"];
  45033. if (gamepad)
  45034. gamepad.gamepadAngularSensibility = value;
  45035. },
  45036. enumerable: true,
  45037. configurable: true
  45038. });
  45039. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  45040. get: function () {
  45041. var gamepad = this.inputs.attached["gamepad"];
  45042. if (gamepad)
  45043. return gamepad.gamepadMoveSensibility;
  45044. },
  45045. set: function (value) {
  45046. var gamepad = this.inputs.attached["gamepad"];
  45047. if (gamepad)
  45048. gamepad.gamepadMoveSensibility = value;
  45049. },
  45050. enumerable: true,
  45051. configurable: true
  45052. });
  45053. UniversalCamera.prototype.getTypeName = function () {
  45054. return "UniversalCamera";
  45055. };
  45056. return UniversalCamera;
  45057. }(BABYLON.TouchCamera));
  45058. BABYLON.UniversalCamera = UniversalCamera;
  45059. })(BABYLON || (BABYLON = {}));
  45060. var BABYLON;
  45061. (function (BABYLON) {
  45062. var Gamepads = (function () {
  45063. function Gamepads(ongamedpadconnected) {
  45064. var _this = this;
  45065. this.babylonGamepads = [];
  45066. this.oneGamepadConnected = false;
  45067. this.isMonitoring = false;
  45068. this.gamepadEventSupported = 'GamepadEvent' in window;
  45069. this.gamepadSupportAvailable = (navigator.getGamepads ||
  45070. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  45071. this._callbackGamepadConnected = ongamedpadconnected;
  45072. if (this.gamepadSupportAvailable) {
  45073. // Checking if the gamepad connected event is supported (like in Firefox)
  45074. if (this.gamepadEventSupported) {
  45075. this._onGamepadConnectedEvent = function (evt) {
  45076. _this._onGamepadConnected(evt);
  45077. };
  45078. this._onGamepadDisonnectedEvent = function (evt) {
  45079. _this._onGamepadDisconnected(evt);
  45080. };
  45081. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45082. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45083. }
  45084. else {
  45085. this._startMonitoringGamepads();
  45086. }
  45087. }
  45088. }
  45089. Gamepads.prototype.dispose = function () {
  45090. if (Gamepads.gamepadDOMInfo) {
  45091. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45092. }
  45093. if (this._onGamepadConnectedEvent) {
  45094. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45095. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45096. this._onGamepadConnectedEvent = null;
  45097. this._onGamepadDisonnectedEvent = null;
  45098. }
  45099. };
  45100. Gamepads.prototype._onGamepadConnected = function (evt) {
  45101. var newGamepad = this._addNewGamepad(evt.gamepad);
  45102. if (this._callbackGamepadConnected)
  45103. this._callbackGamepadConnected(newGamepad);
  45104. this._startMonitoringGamepads();
  45105. };
  45106. Gamepads.prototype._addNewGamepad = function (gamepad) {
  45107. if (!this.oneGamepadConnected) {
  45108. this.oneGamepadConnected = true;
  45109. if (Gamepads.gamepadDOMInfo) {
  45110. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45111. Gamepads.gamepadDOMInfo = null;
  45112. }
  45113. }
  45114. var newGamepad;
  45115. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  45116. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  45117. }
  45118. else {
  45119. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  45120. }
  45121. this.babylonGamepads.push(newGamepad);
  45122. return newGamepad;
  45123. };
  45124. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  45125. // Remove the gamepad from the list of gamepads to monitor.
  45126. for (var i in this.babylonGamepads) {
  45127. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  45128. this.babylonGamepads.splice(+i, 1);
  45129. break;
  45130. }
  45131. }
  45132. // If no gamepads are left, stop the polling loop.
  45133. if (this.babylonGamepads.length == 0) {
  45134. this._stopMonitoringGamepads();
  45135. }
  45136. };
  45137. Gamepads.prototype._startMonitoringGamepads = function () {
  45138. if (!this.isMonitoring) {
  45139. this.isMonitoring = true;
  45140. this._checkGamepadsStatus();
  45141. }
  45142. };
  45143. Gamepads.prototype._stopMonitoringGamepads = function () {
  45144. this.isMonitoring = false;
  45145. };
  45146. Gamepads.prototype._checkGamepadsStatus = function () {
  45147. var _this = this;
  45148. // updating gamepad objects
  45149. this._updateGamepadObjects();
  45150. for (var i in this.babylonGamepads) {
  45151. this.babylonGamepads[i].update();
  45152. }
  45153. if (this.isMonitoring) {
  45154. if (window.requestAnimationFrame) {
  45155. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45156. }
  45157. else if (window.mozRequestAnimationFrame) {
  45158. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45159. }
  45160. else if (window.webkitRequestAnimationFrame) {
  45161. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45162. }
  45163. }
  45164. };
  45165. // This function is called only on Chrome, which does not yet support
  45166. // connection/disconnection events, but requires you to monitor
  45167. // an array for changes.
  45168. Gamepads.prototype._updateGamepadObjects = function () {
  45169. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  45170. for (var i = 0; i < gamepads.length; i++) {
  45171. if (gamepads[i]) {
  45172. if (!(gamepads[i].index in this.babylonGamepads)) {
  45173. var newGamepad = this._addNewGamepad(gamepads[i]);
  45174. if (this._callbackGamepadConnected) {
  45175. this._callbackGamepadConnected(newGamepad);
  45176. }
  45177. }
  45178. else {
  45179. this.babylonGamepads[i].browserGamepad = gamepads[i];
  45180. }
  45181. }
  45182. }
  45183. };
  45184. return Gamepads;
  45185. }());
  45186. BABYLON.Gamepads = Gamepads;
  45187. var StickValues = (function () {
  45188. function StickValues(x, y) {
  45189. this.x = x;
  45190. this.y = y;
  45191. }
  45192. return StickValues;
  45193. }());
  45194. BABYLON.StickValues = StickValues;
  45195. var Gamepad = (function () {
  45196. function Gamepad(id, index, browserGamepad) {
  45197. this.id = id;
  45198. this.index = index;
  45199. this.browserGamepad = browserGamepad;
  45200. if (this.browserGamepad.axes.length >= 2) {
  45201. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  45202. }
  45203. if (this.browserGamepad.axes.length >= 4) {
  45204. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  45205. }
  45206. }
  45207. Gamepad.prototype.onleftstickchanged = function (callback) {
  45208. this._onleftstickchanged = callback;
  45209. };
  45210. Gamepad.prototype.onrightstickchanged = function (callback) {
  45211. this._onrightstickchanged = callback;
  45212. };
  45213. Object.defineProperty(Gamepad.prototype, "leftStick", {
  45214. get: function () {
  45215. return this._leftStick;
  45216. },
  45217. set: function (newValues) {
  45218. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  45219. this._onleftstickchanged(newValues);
  45220. }
  45221. this._leftStick = newValues;
  45222. },
  45223. enumerable: true,
  45224. configurable: true
  45225. });
  45226. Object.defineProperty(Gamepad.prototype, "rightStick", {
  45227. get: function () {
  45228. return this._rightStick;
  45229. },
  45230. set: function (newValues) {
  45231. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  45232. this._onrightstickchanged(newValues);
  45233. }
  45234. this._rightStick = newValues;
  45235. },
  45236. enumerable: true,
  45237. configurable: true
  45238. });
  45239. Gamepad.prototype.update = function () {
  45240. if (this._leftStick) {
  45241. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  45242. }
  45243. if (this._rightStick) {
  45244. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  45245. }
  45246. };
  45247. return Gamepad;
  45248. }());
  45249. BABYLON.Gamepad = Gamepad;
  45250. var GenericPad = (function (_super) {
  45251. __extends(GenericPad, _super);
  45252. function GenericPad(id, index, gamepad) {
  45253. _super.call(this, id, index, gamepad);
  45254. this.id = id;
  45255. this.index = index;
  45256. this.gamepad = gamepad;
  45257. this._buttons = new Array(gamepad.buttons.length);
  45258. }
  45259. GenericPad.prototype.onbuttondown = function (callback) {
  45260. this._onbuttondown = callback;
  45261. };
  45262. GenericPad.prototype.onbuttonup = function (callback) {
  45263. this._onbuttonup = callback;
  45264. };
  45265. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  45266. if (newValue !== currentValue) {
  45267. if (this._onbuttondown && newValue === 1) {
  45268. this._onbuttondown(buttonIndex);
  45269. }
  45270. if (this._onbuttonup && newValue === 0) {
  45271. this._onbuttonup(buttonIndex);
  45272. }
  45273. }
  45274. return newValue;
  45275. };
  45276. GenericPad.prototype.update = function () {
  45277. _super.prototype.update.call(this);
  45278. for (var index = 0; index < this._buttons.length; index++) {
  45279. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  45280. }
  45281. };
  45282. return GenericPad;
  45283. }(Gamepad));
  45284. BABYLON.GenericPad = GenericPad;
  45285. (function (Xbox360Button) {
  45286. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  45287. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  45288. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  45289. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  45290. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  45291. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  45292. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  45293. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  45294. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  45295. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  45296. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  45297. var Xbox360Button = BABYLON.Xbox360Button;
  45298. (function (Xbox360Dpad) {
  45299. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  45300. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  45301. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  45302. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  45303. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  45304. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  45305. var Xbox360Pad = (function (_super) {
  45306. __extends(Xbox360Pad, _super);
  45307. function Xbox360Pad() {
  45308. _super.apply(this, arguments);
  45309. this._leftTrigger = 0;
  45310. this._rightTrigger = 0;
  45311. this._buttonA = 0;
  45312. this._buttonB = 0;
  45313. this._buttonX = 0;
  45314. this._buttonY = 0;
  45315. this._buttonBack = 0;
  45316. this._buttonStart = 0;
  45317. this._buttonLB = 0;
  45318. this._buttonRB = 0;
  45319. this._buttonLeftStick = 0;
  45320. this._buttonRightStick = 0;
  45321. this._dPadUp = 0;
  45322. this._dPadDown = 0;
  45323. this._dPadLeft = 0;
  45324. this._dPadRight = 0;
  45325. }
  45326. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  45327. this._onlefttriggerchanged = callback;
  45328. };
  45329. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  45330. this._onrighttriggerchanged = callback;
  45331. };
  45332. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  45333. get: function () {
  45334. return this._leftTrigger;
  45335. },
  45336. set: function (newValue) {
  45337. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  45338. this._onlefttriggerchanged(newValue);
  45339. }
  45340. this._leftTrigger = newValue;
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  45346. get: function () {
  45347. return this._rightTrigger;
  45348. },
  45349. set: function (newValue) {
  45350. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  45351. this._onrighttriggerchanged(newValue);
  45352. }
  45353. this._rightTrigger = newValue;
  45354. },
  45355. enumerable: true,
  45356. configurable: true
  45357. });
  45358. Xbox360Pad.prototype.onbuttondown = function (callback) {
  45359. this._onbuttondown = callback;
  45360. };
  45361. Xbox360Pad.prototype.onbuttonup = function (callback) {
  45362. this._onbuttonup = callback;
  45363. };
  45364. Xbox360Pad.prototype.ondpaddown = function (callback) {
  45365. this._ondpaddown = callback;
  45366. };
  45367. Xbox360Pad.prototype.ondpadup = function (callback) {
  45368. this._ondpadup = callback;
  45369. };
  45370. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  45371. if (newValue !== currentValue) {
  45372. if (this._onbuttondown && newValue === 1) {
  45373. this._onbuttondown(buttonType);
  45374. }
  45375. if (this._onbuttonup && newValue === 0) {
  45376. this._onbuttonup(buttonType);
  45377. }
  45378. }
  45379. return newValue;
  45380. };
  45381. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  45382. if (newValue !== currentValue) {
  45383. if (this._ondpaddown && newValue === 1) {
  45384. this._ondpaddown(buttonType);
  45385. }
  45386. if (this._ondpadup && newValue === 0) {
  45387. this._ondpadup(buttonType);
  45388. }
  45389. }
  45390. return newValue;
  45391. };
  45392. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  45393. get: function () {
  45394. return this._buttonA;
  45395. },
  45396. set: function (value) {
  45397. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  45398. },
  45399. enumerable: true,
  45400. configurable: true
  45401. });
  45402. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  45403. get: function () {
  45404. return this._buttonB;
  45405. },
  45406. set: function (value) {
  45407. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  45408. },
  45409. enumerable: true,
  45410. configurable: true
  45411. });
  45412. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  45413. get: function () {
  45414. return this._buttonX;
  45415. },
  45416. set: function (value) {
  45417. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  45418. },
  45419. enumerable: true,
  45420. configurable: true
  45421. });
  45422. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  45423. get: function () {
  45424. return this._buttonY;
  45425. },
  45426. set: function (value) {
  45427. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  45428. },
  45429. enumerable: true,
  45430. configurable: true
  45431. });
  45432. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  45433. get: function () {
  45434. return this._buttonStart;
  45435. },
  45436. set: function (value) {
  45437. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  45438. },
  45439. enumerable: true,
  45440. configurable: true
  45441. });
  45442. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  45443. get: function () {
  45444. return this._buttonBack;
  45445. },
  45446. set: function (value) {
  45447. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  45448. },
  45449. enumerable: true,
  45450. configurable: true
  45451. });
  45452. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  45453. get: function () {
  45454. return this._buttonLB;
  45455. },
  45456. set: function (value) {
  45457. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  45458. },
  45459. enumerable: true,
  45460. configurable: true
  45461. });
  45462. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  45463. get: function () {
  45464. return this._buttonRB;
  45465. },
  45466. set: function (value) {
  45467. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  45468. },
  45469. enumerable: true,
  45470. configurable: true
  45471. });
  45472. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  45473. get: function () {
  45474. return this._buttonLeftStick;
  45475. },
  45476. set: function (value) {
  45477. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  45478. },
  45479. enumerable: true,
  45480. configurable: true
  45481. });
  45482. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  45483. get: function () {
  45484. return this._buttonRightStick;
  45485. },
  45486. set: function (value) {
  45487. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  45488. },
  45489. enumerable: true,
  45490. configurable: true
  45491. });
  45492. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  45493. get: function () {
  45494. return this._dPadUp;
  45495. },
  45496. set: function (value) {
  45497. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  45498. },
  45499. enumerable: true,
  45500. configurable: true
  45501. });
  45502. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  45503. get: function () {
  45504. return this._dPadDown;
  45505. },
  45506. set: function (value) {
  45507. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  45508. },
  45509. enumerable: true,
  45510. configurable: true
  45511. });
  45512. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  45513. get: function () {
  45514. return this._dPadLeft;
  45515. },
  45516. set: function (value) {
  45517. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  45518. },
  45519. enumerable: true,
  45520. configurable: true
  45521. });
  45522. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  45523. get: function () {
  45524. return this._dPadRight;
  45525. },
  45526. set: function (value) {
  45527. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  45528. },
  45529. enumerable: true,
  45530. configurable: true
  45531. });
  45532. Xbox360Pad.prototype.update = function () {
  45533. _super.prototype.update.call(this);
  45534. this.buttonA = this.browserGamepad.buttons[0].value;
  45535. this.buttonB = this.browserGamepad.buttons[1].value;
  45536. this.buttonX = this.browserGamepad.buttons[2].value;
  45537. this.buttonY = this.browserGamepad.buttons[3].value;
  45538. this.buttonLB = this.browserGamepad.buttons[4].value;
  45539. this.buttonRB = this.browserGamepad.buttons[5].value;
  45540. this.leftTrigger = this.browserGamepad.buttons[6].value;
  45541. this.rightTrigger = this.browserGamepad.buttons[7].value;
  45542. this.buttonBack = this.browserGamepad.buttons[8].value;
  45543. this.buttonStart = this.browserGamepad.buttons[9].value;
  45544. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  45545. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  45546. this.dPadUp = this.browserGamepad.buttons[12].value;
  45547. this.dPadDown = this.browserGamepad.buttons[13].value;
  45548. this.dPadLeft = this.browserGamepad.buttons[14].value;
  45549. this.dPadRight = this.browserGamepad.buttons[15].value;
  45550. };
  45551. return Xbox360Pad;
  45552. }(Gamepad));
  45553. BABYLON.Xbox360Pad = Xbox360Pad;
  45554. })(BABYLON || (BABYLON = {}));
  45555. var BABYLON;
  45556. (function (BABYLON) {
  45557. // We're mainly based on the logic defined into the FreeCamera code
  45558. var GamepadCamera = (function (_super) {
  45559. __extends(GamepadCamera, _super);
  45560. //-- end properties for backward compatibility for inputs
  45561. function GamepadCamera(name, position, scene) {
  45562. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  45563. _super.call(this, name, position, scene);
  45564. }
  45565. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  45566. //-- Begin properties for backward compatibility for inputs
  45567. get: function () {
  45568. var gamepad = this.inputs.attached["gamepad"];
  45569. if (gamepad)
  45570. return gamepad.gamepadAngularSensibility;
  45571. },
  45572. set: function (value) {
  45573. var gamepad = this.inputs.attached["gamepad"];
  45574. if (gamepad)
  45575. gamepad.gamepadAngularSensibility = value;
  45576. },
  45577. enumerable: true,
  45578. configurable: true
  45579. });
  45580. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  45581. get: function () {
  45582. var gamepad = this.inputs.attached["gamepad"];
  45583. if (gamepad)
  45584. return gamepad.gamepadMoveSensibility;
  45585. },
  45586. set: function (value) {
  45587. var gamepad = this.inputs.attached["gamepad"];
  45588. if (gamepad)
  45589. gamepad.gamepadMoveSensibility = value;
  45590. },
  45591. enumerable: true,
  45592. configurable: true
  45593. });
  45594. GamepadCamera.prototype.getTypeName = function () {
  45595. return "GamepadCamera";
  45596. };
  45597. return GamepadCamera;
  45598. }(BABYLON.UniversalCamera));
  45599. BABYLON.GamepadCamera = GamepadCamera;
  45600. })(BABYLON || (BABYLON = {}));
  45601. var BABYLON;
  45602. (function (BABYLON) {
  45603. var Analyser = (function () {
  45604. function Analyser(scene) {
  45605. this.SMOOTHING = 0.75;
  45606. this.FFT_SIZE = 512;
  45607. this.BARGRAPHAMPLITUDE = 256;
  45608. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45609. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45610. this._scene = scene;
  45611. this._audioEngine = BABYLON.Engine.audioEngine;
  45612. if (this._audioEngine.canUseWebAudio) {
  45613. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45614. this._webAudioAnalyser.minDecibels = -140;
  45615. this._webAudioAnalyser.maxDecibels = 0;
  45616. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45617. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45618. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45619. }
  45620. }
  45621. Analyser.prototype.getFrequencyBinCount = function () {
  45622. if (this._audioEngine.canUseWebAudio) {
  45623. return this._webAudioAnalyser.frequencyBinCount;
  45624. }
  45625. else {
  45626. return 0;
  45627. }
  45628. };
  45629. Analyser.prototype.getByteFrequencyData = function () {
  45630. if (this._audioEngine.canUseWebAudio) {
  45631. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45632. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45633. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45634. }
  45635. return this._byteFreqs;
  45636. };
  45637. Analyser.prototype.getByteTimeDomainData = function () {
  45638. if (this._audioEngine.canUseWebAudio) {
  45639. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45640. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45641. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45642. }
  45643. return this._byteTime;
  45644. };
  45645. Analyser.prototype.getFloatFrequencyData = function () {
  45646. if (this._audioEngine.canUseWebAudio) {
  45647. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45648. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45649. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45650. }
  45651. return this._floatFreqs;
  45652. };
  45653. Analyser.prototype.drawDebugCanvas = function () {
  45654. var _this = this;
  45655. if (this._audioEngine.canUseWebAudio) {
  45656. if (!this._debugCanvas) {
  45657. this._debugCanvas = document.createElement("canvas");
  45658. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45659. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45660. this._debugCanvas.style.position = "absolute";
  45661. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45662. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45663. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45664. document.body.appendChild(this._debugCanvas);
  45665. this._registerFunc = function () {
  45666. _this.drawDebugCanvas();
  45667. };
  45668. this._scene.registerBeforeRender(this._registerFunc);
  45669. }
  45670. if (this._registerFunc) {
  45671. var workingArray = this.getByteFrequencyData();
  45672. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45673. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45674. // Draw the frequency domain chart.
  45675. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45676. var value = workingArray[i];
  45677. var percent = value / this.BARGRAPHAMPLITUDE;
  45678. var height = this.DEBUGCANVASSIZE.height * percent;
  45679. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45680. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45681. var hue = i / this.getFrequencyBinCount() * 360;
  45682. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45683. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45684. }
  45685. }
  45686. }
  45687. };
  45688. Analyser.prototype.stopDebugCanvas = function () {
  45689. if (this._debugCanvas) {
  45690. this._scene.unregisterBeforeRender(this._registerFunc);
  45691. this._registerFunc = null;
  45692. document.body.removeChild(this._debugCanvas);
  45693. this._debugCanvas = null;
  45694. this._debugCanvasContext = null;
  45695. }
  45696. };
  45697. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45698. if (this._audioEngine.canUseWebAudio) {
  45699. inputAudioNode.connect(this._webAudioAnalyser);
  45700. this._webAudioAnalyser.connect(outputAudioNode);
  45701. }
  45702. };
  45703. Analyser.prototype.dispose = function () {
  45704. if (this._audioEngine.canUseWebAudio) {
  45705. this._webAudioAnalyser.disconnect();
  45706. }
  45707. };
  45708. return Analyser;
  45709. }());
  45710. BABYLON.Analyser = Analyser;
  45711. })(BABYLON || (BABYLON = {}));
  45712. var BABYLON;
  45713. (function (BABYLON) {
  45714. var DepthRenderer = (function () {
  45715. function DepthRenderer(scene, type) {
  45716. var _this = this;
  45717. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  45718. this._viewMatrix = BABYLON.Matrix.Zero();
  45719. this._projectionMatrix = BABYLON.Matrix.Zero();
  45720. this._transformMatrix = BABYLON.Matrix.Zero();
  45721. this._worldViewProjection = BABYLON.Matrix.Zero();
  45722. this._scene = scene;
  45723. var engine = scene.getEngine();
  45724. // Render target
  45725. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  45726. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45727. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45728. this._depthMap.refreshRate = 1;
  45729. this._depthMap.renderParticles = false;
  45730. this._depthMap.renderList = null;
  45731. // set default depth value to 1.0 (far away)
  45732. this._depthMap.onClearObservable.add(function (engine) {
  45733. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  45734. });
  45735. // Custom render function
  45736. var renderSubMesh = function (subMesh) {
  45737. var mesh = subMesh.getRenderingMesh();
  45738. var scene = _this._scene;
  45739. var engine = scene.getEngine();
  45740. // Culling
  45741. engine.setState(subMesh.getMaterial().backFaceCulling);
  45742. // Managing instances
  45743. var batch = mesh._getInstancesRenderList(subMesh._id);
  45744. if (batch.mustReturn) {
  45745. return;
  45746. }
  45747. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  45748. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  45749. engine.enableEffect(_this._effect);
  45750. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  45751. var material = subMesh.getMaterial();
  45752. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45753. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  45754. // Alpha test
  45755. if (material && material.needAlphaTesting()) {
  45756. var alphaTexture = material.getAlphaTestTexture();
  45757. _this._effect.setTexture("diffuseSampler", alphaTexture);
  45758. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45759. }
  45760. // Bones
  45761. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45762. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45763. }
  45764. // Draw
  45765. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  45766. }
  45767. };
  45768. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  45769. var index;
  45770. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45771. renderSubMesh(opaqueSubMeshes.data[index]);
  45772. }
  45773. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45774. renderSubMesh(alphaTestSubMeshes.data[index]);
  45775. }
  45776. };
  45777. }
  45778. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  45779. var material = subMesh.getMaterial();
  45780. if (material.disableDepthWrite) {
  45781. return false;
  45782. }
  45783. var defines = [];
  45784. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45785. var mesh = subMesh.getMesh();
  45786. var scene = mesh.getScene();
  45787. // Alpha test
  45788. if (material && material.needAlphaTesting()) {
  45789. defines.push("#define ALPHATEST");
  45790. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45791. attribs.push(BABYLON.VertexBuffer.UVKind);
  45792. defines.push("#define UV1");
  45793. }
  45794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45795. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45796. defines.push("#define UV2");
  45797. }
  45798. }
  45799. // Bones
  45800. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45801. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45802. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45803. if (mesh.numBoneInfluencers > 4) {
  45804. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45805. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45806. }
  45807. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45808. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45809. }
  45810. else {
  45811. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45812. }
  45813. // Instances
  45814. if (useInstances) {
  45815. defines.push("#define INSTANCES");
  45816. attribs.push("world0");
  45817. attribs.push("world1");
  45818. attribs.push("world2");
  45819. attribs.push("world3");
  45820. }
  45821. // Get correct effect
  45822. var join = defines.join("\n");
  45823. if (this._cachedDefines !== join) {
  45824. this._cachedDefines = join;
  45825. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  45826. }
  45827. return this._effect.isReady();
  45828. };
  45829. DepthRenderer.prototype.getDepthMap = function () {
  45830. return this._depthMap;
  45831. };
  45832. // Methods
  45833. DepthRenderer.prototype.dispose = function () {
  45834. this._depthMap.dispose();
  45835. };
  45836. return DepthRenderer;
  45837. }());
  45838. BABYLON.DepthRenderer = DepthRenderer;
  45839. })(BABYLON || (BABYLON = {}));
  45840. var BABYLON;
  45841. (function (BABYLON) {
  45842. var SSAORenderingPipeline = (function (_super) {
  45843. __extends(SSAORenderingPipeline, _super);
  45844. /**
  45845. * @constructor
  45846. * @param {string} name - The rendering pipeline name
  45847. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  45848. * @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 }
  45849. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  45850. */
  45851. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  45852. var _this = this;
  45853. _super.call(this, scene.getEngine(), name);
  45854. // Members
  45855. /**
  45856. * The PassPostProcess id in the pipeline that contains the original scene color
  45857. * @type {string}
  45858. */
  45859. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  45860. /**
  45861. * The SSAO PostProcess id in the pipeline
  45862. * @type {string}
  45863. */
  45864. this.SSAORenderEffect = "SSAORenderEffect";
  45865. /**
  45866. * The horizontal blur PostProcess id in the pipeline
  45867. * @type {string}
  45868. */
  45869. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  45870. /**
  45871. * The vertical blur PostProcess id in the pipeline
  45872. * @type {string}
  45873. */
  45874. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  45875. /**
  45876. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  45877. * @type {string}
  45878. */
  45879. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  45880. /**
  45881. * The output strength of the SSAO post-process. Default value is 1.0.
  45882. * @type {number}
  45883. */
  45884. this.totalStrength = 1.0;
  45885. /**
  45886. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  45887. * @type {number}
  45888. */
  45889. this.radius = 0.0001;
  45890. /**
  45891. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  45892. * Must not be equal to fallOff and superior to fallOff.
  45893. * Default value is 0.975
  45894. * @type {number}
  45895. */
  45896. this.area = 0.0075;
  45897. /**
  45898. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  45899. * Must not be equal to area and inferior to area.
  45900. * Default value is 0.0
  45901. * @type {number}
  45902. */
  45903. this.fallOff = 0.000001;
  45904. /**
  45905. * The base color of the SSAO post-process
  45906. * The final result is "base + ssao" between [0, 1]
  45907. * @type {number}
  45908. */
  45909. this.base = 0.5;
  45910. this._firstUpdate = true;
  45911. this._scene = scene;
  45912. // Set up assets
  45913. this._createRandomTexture();
  45914. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  45915. var ssaoRatio = ratio.ssaoRatio || ratio;
  45916. var combineRatio = ratio.combineRatio || ratio;
  45917. this._ratio = {
  45918. ssaoRatio: ssaoRatio,
  45919. combineRatio: combineRatio
  45920. };
  45921. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45922. this._createSSAOPostProcess(ssaoRatio);
  45923. this._createBlurPostProcess(ssaoRatio);
  45924. this._createSSAOCombinePostProcess(combineRatio);
  45925. // Set up pipeline
  45926. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  45927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  45928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  45929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  45930. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  45931. // Finish
  45932. scene.postProcessRenderPipelineManager.addPipeline(this);
  45933. if (cameras)
  45934. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  45935. }
  45936. // Public Methods
  45937. /**
  45938. * Returns the horizontal blur PostProcess
  45939. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  45940. */
  45941. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  45942. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  45943. return null;
  45944. };
  45945. /**
  45946. * Returns the vertical blur PostProcess
  45947. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  45948. */
  45949. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  45950. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  45951. return null;
  45952. };
  45953. /**
  45954. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  45955. */
  45956. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  45957. if (disableDepthRender === void 0) { disableDepthRender = false; }
  45958. for (var i = 0; i < this._scene.cameras.length; i++) {
  45959. var camera = this._scene.cameras[i];
  45960. this._originalColorPostProcess.dispose(camera);
  45961. this._ssaoPostProcess.dispose(camera);
  45962. this._blurHPostProcess.dispose(camera);
  45963. this._blurVPostProcess.dispose(camera);
  45964. this._ssaoCombinePostProcess.dispose(camera);
  45965. }
  45966. this._randomTexture.dispose();
  45967. if (disableDepthRender)
  45968. this._scene.disableDepthRenderer();
  45969. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  45970. };
  45971. // Private Methods
  45972. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  45973. var _this = this;
  45974. /*
  45975. var samplerOffsets = [
  45976. -8.0, -6.0, -4.0, -2.0,
  45977. 0.0,
  45978. 2.0, 4.0, 6.0, 8.0
  45979. ];
  45980. */
  45981. var samples = 16;
  45982. var samplerOffsets = [];
  45983. for (var i = -8; i < 8; i++) {
  45984. samplerOffsets.push(i * 2);
  45985. }
  45986. 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");
  45987. this._blurHPostProcess.onApply = function (effect) {
  45988. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  45989. effect.setTexture("depthSampler", _this._depthTexture);
  45990. if (_this._firstUpdate) {
  45991. effect.setArray("samplerOffsets", samplerOffsets);
  45992. }
  45993. };
  45994. 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");
  45995. this._blurVPostProcess.onApply = function (effect) {
  45996. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  45997. effect.setTexture("depthSampler", _this._depthTexture);
  45998. if (_this._firstUpdate) {
  45999. effect.setArray("samplerOffsets", samplerOffsets);
  46000. _this._firstUpdate = false;
  46001. }
  46002. };
  46003. };
  46004. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  46005. var _this = this;
  46006. var numSamples = 16;
  46007. var sampleSphere = [
  46008. 0.5381, 0.1856, -0.4319,
  46009. 0.1379, 0.2486, 0.4430,
  46010. 0.3371, 0.5679, -0.0057,
  46011. -0.6999, -0.0451, -0.0019,
  46012. 0.0689, -0.1598, -0.8547,
  46013. 0.0560, 0.0069, -0.1843,
  46014. -0.0146, 0.1402, 0.0762,
  46015. 0.0100, -0.1924, -0.0344,
  46016. -0.3577, -0.5301, -0.4358,
  46017. -0.3169, 0.1063, 0.0158,
  46018. 0.0103, -0.5869, 0.0046,
  46019. -0.0897, -0.4940, 0.3287,
  46020. 0.7119, -0.0154, -0.0918,
  46021. -0.0533, 0.0596, -0.5411,
  46022. 0.0352, -0.0631, 0.5460,
  46023. -0.4776, 0.2847, -0.0271
  46024. ];
  46025. var samplesFactor = 1.0 / numSamples;
  46026. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  46027. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  46028. "area", "fallOff", "base", "range", "viewport"
  46029. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  46030. var viewport = new BABYLON.Vector2(0, 0);
  46031. this._ssaoPostProcess.onApply = function (effect) {
  46032. if (_this._firstUpdate) {
  46033. effect.setArray3("sampleSphere", sampleSphere);
  46034. effect.setFloat("samplesFactor", samplesFactor);
  46035. effect.setFloat("randTextureTiles", 4.0);
  46036. }
  46037. effect.setFloat("totalStrength", _this.totalStrength);
  46038. effect.setFloat("radius", _this.radius);
  46039. effect.setFloat("area", _this.area);
  46040. effect.setFloat("fallOff", _this.fallOff);
  46041. effect.setFloat("base", _this.base);
  46042. effect.setTexture("textureSampler", _this._depthTexture);
  46043. effect.setTexture("randomSampler", _this._randomTexture);
  46044. };
  46045. };
  46046. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  46047. var _this = this;
  46048. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46049. this._ssaoCombinePostProcess.onApply = function (effect) {
  46050. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  46051. };
  46052. };
  46053. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  46054. var size = 512;
  46055. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46056. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46057. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46058. var context = this._randomTexture.getContext();
  46059. var rand = function (min, max) {
  46060. return Math.random() * (max - min) + min;
  46061. };
  46062. var randVector = BABYLON.Vector3.Zero();
  46063. for (var x = 0; x < size; x++) {
  46064. for (var y = 0; y < size; y++) {
  46065. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  46066. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  46067. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  46068. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  46069. context.fillRect(x, y, 1, 1);
  46070. }
  46071. }
  46072. this._randomTexture.update(false);
  46073. };
  46074. __decorate([
  46075. BABYLON.serialize()
  46076. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  46077. __decorate([
  46078. BABYLON.serialize()
  46079. ], SSAORenderingPipeline.prototype, "radius", void 0);
  46080. __decorate([
  46081. BABYLON.serialize()
  46082. ], SSAORenderingPipeline.prototype, "area", void 0);
  46083. __decorate([
  46084. BABYLON.serialize()
  46085. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  46086. __decorate([
  46087. BABYLON.serialize()
  46088. ], SSAORenderingPipeline.prototype, "base", void 0);
  46089. __decorate([
  46090. BABYLON.serialize()
  46091. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  46092. return SSAORenderingPipeline;
  46093. }(BABYLON.PostProcessRenderPipeline));
  46094. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  46095. })(BABYLON || (BABYLON = {}));
  46096. var BABYLON;
  46097. (function (BABYLON) {
  46098. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  46099. var VolumetricLightScatteringPostProcess = (function (_super) {
  46100. __extends(VolumetricLightScatteringPostProcess, _super);
  46101. /**
  46102. * @constructor
  46103. * @param {string} name - The post-process name
  46104. * @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)
  46105. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  46106. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  46107. * @param {number} samples - The post-process quality, default 100
  46108. * @param {number} samplingMode - The post-process filtering mode
  46109. * @param {BABYLON.Engine} engine - The babylon engine
  46110. * @param {boolean} reusable - If the post-process is reusable
  46111. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  46112. */
  46113. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  46114. var _this = this;
  46115. if (samples === void 0) { samples = 100; }
  46116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46117. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  46118. this._screenCoordinates = BABYLON.Vector2.Zero();
  46119. /**
  46120. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  46121. * @type {Vector3}
  46122. */
  46123. this.customMeshPosition = BABYLON.Vector3.Zero();
  46124. /**
  46125. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  46126. * @type {boolean}
  46127. */
  46128. this.useCustomMeshPosition = false;
  46129. /**
  46130. * If the post-process should inverse the light scattering direction
  46131. * @type {boolean}
  46132. */
  46133. this.invert = true;
  46134. /**
  46135. * Array containing the excluded meshes not rendered in the internal pass
  46136. */
  46137. this.excludedMeshes = new Array();
  46138. /**
  46139. * Controls the overall intensity of the post-process
  46140. * @type {number}
  46141. */
  46142. this.exposure = 0.3;
  46143. /**
  46144. * Dissipates each sample's contribution in range [0, 1]
  46145. * @type {number}
  46146. */
  46147. this.decay = 0.96815;
  46148. /**
  46149. * Controls the overall intensity of each sample
  46150. * @type {number}
  46151. */
  46152. this.weight = 0.58767;
  46153. /**
  46154. * Controls the density of each sample
  46155. * @type {number}
  46156. */
  46157. this.density = 0.926;
  46158. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  46159. var engine = scene.getEngine();
  46160. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  46161. // Configure mesh
  46162. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  46163. // Configure
  46164. this._createPass(scene, ratio.passRatio || ratio);
  46165. this.onActivate = function (camera) {
  46166. if (!_this.isSupported) {
  46167. _this.dispose(camera);
  46168. }
  46169. _this.onActivate = null;
  46170. };
  46171. this.onApplyObservable.add(function (effect) {
  46172. _this._updateMeshScreenCoordinates(scene);
  46173. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  46174. effect.setFloat("exposure", _this.exposure);
  46175. effect.setFloat("decay", _this.decay);
  46176. effect.setFloat("weight", _this.weight);
  46177. effect.setFloat("density", _this.density);
  46178. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  46179. });
  46180. }
  46181. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  46182. get: function () {
  46183. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46184. return false;
  46185. },
  46186. set: function (useDiffuseColor) {
  46187. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46188. },
  46189. enumerable: true,
  46190. configurable: true
  46191. });
  46192. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  46193. var mesh = subMesh.getMesh();
  46194. // Render this.mesh as default
  46195. if (mesh === this.mesh) {
  46196. return mesh.material.isReady(mesh);
  46197. }
  46198. var defines = [];
  46199. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46200. var material = subMesh.getMaterial();
  46201. var needUV = false;
  46202. // Alpha test
  46203. if (material) {
  46204. if (material.needAlphaTesting()) {
  46205. defines.push("#define ALPHATEST");
  46206. }
  46207. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46208. attribs.push(BABYLON.VertexBuffer.UVKind);
  46209. defines.push("#define UV1");
  46210. }
  46211. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46212. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46213. defines.push("#define UV2");
  46214. }
  46215. }
  46216. // Bones
  46217. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46218. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46219. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46220. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46221. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46222. }
  46223. else {
  46224. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46225. }
  46226. // Instances
  46227. if (useInstances) {
  46228. defines.push("#define INSTANCES");
  46229. attribs.push("world0");
  46230. attribs.push("world1");
  46231. attribs.push("world2");
  46232. attribs.push("world3");
  46233. }
  46234. // Get correct effect
  46235. var join = defines.join("\n");
  46236. if (this._cachedDefines !== join) {
  46237. this._cachedDefines = join;
  46238. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  46239. }
  46240. return this._volumetricLightScatteringPass.isReady();
  46241. };
  46242. /**
  46243. * Sets the new light position for light scattering effect
  46244. * @param {BABYLON.Vector3} The new custom light position
  46245. */
  46246. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  46247. this.customMeshPosition = position;
  46248. };
  46249. /**
  46250. * Returns the light position for light scattering effect
  46251. * @return {BABYLON.Vector3} The custom light position
  46252. */
  46253. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  46254. return this.customMeshPosition;
  46255. };
  46256. /**
  46257. * Disposes the internal assets and detaches the post-process from the camera
  46258. */
  46259. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  46260. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  46261. if (rttIndex !== -1) {
  46262. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  46263. }
  46264. this._volumetricLightScatteringRTT.dispose();
  46265. _super.prototype.dispose.call(this, camera);
  46266. };
  46267. /**
  46268. * Returns the render target texture used by the post-process
  46269. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  46270. */
  46271. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  46272. return this._volumetricLightScatteringRTT;
  46273. };
  46274. // Private methods
  46275. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  46276. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  46277. return true;
  46278. }
  46279. return false;
  46280. };
  46281. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  46282. var _this = this;
  46283. var engine = scene.getEngine();
  46284. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  46285. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46286. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46287. this._volumetricLightScatteringRTT.renderList = null;
  46288. this._volumetricLightScatteringRTT.renderParticles = false;
  46289. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  46290. // Custom render function for submeshes
  46291. var renderSubMesh = function (subMesh) {
  46292. var mesh = subMesh.getRenderingMesh();
  46293. if (_this._meshExcluded(mesh)) {
  46294. return;
  46295. }
  46296. var scene = mesh.getScene();
  46297. var engine = scene.getEngine();
  46298. // Culling
  46299. engine.setState(subMesh.getMaterial().backFaceCulling);
  46300. // Managing instances
  46301. var batch = mesh._getInstancesRenderList(subMesh._id);
  46302. if (batch.mustReturn) {
  46303. return;
  46304. }
  46305. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46306. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46307. var effect = _this._volumetricLightScatteringPass;
  46308. if (mesh === _this.mesh) {
  46309. effect = subMesh.getMaterial().getEffect();
  46310. }
  46311. engine.enableEffect(effect);
  46312. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  46313. if (mesh === _this.mesh) {
  46314. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  46315. }
  46316. else {
  46317. var material = subMesh.getMaterial();
  46318. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  46319. // Alpha test
  46320. if (material && material.needAlphaTesting()) {
  46321. var alphaTexture = material.getAlphaTestTexture();
  46322. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  46323. if (alphaTexture) {
  46324. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46325. }
  46326. }
  46327. // Bones
  46328. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46329. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46330. }
  46331. }
  46332. // Draw
  46333. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  46334. }
  46335. };
  46336. // Render target texture callbacks
  46337. var savedSceneClearColor;
  46338. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  46339. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  46340. savedSceneClearColor = scene.clearColor;
  46341. scene.clearColor = sceneClearColor;
  46342. });
  46343. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  46344. scene.clearColor = savedSceneClearColor;
  46345. });
  46346. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  46347. var engine = scene.getEngine();
  46348. var index;
  46349. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46350. renderSubMesh(opaqueSubMeshes.data[index]);
  46351. }
  46352. engine.setAlphaTesting(true);
  46353. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46354. renderSubMesh(alphaTestSubMeshes.data[index]);
  46355. }
  46356. engine.setAlphaTesting(false);
  46357. if (transparentSubMeshes.length) {
  46358. // Sort sub meshes
  46359. for (index = 0; index < transparentSubMeshes.length; index++) {
  46360. var submesh = transparentSubMeshes.data[index];
  46361. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  46362. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  46363. }
  46364. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  46365. sortedArray.sort(function (a, b) {
  46366. // Alpha index first
  46367. if (a._alphaIndex > b._alphaIndex) {
  46368. return 1;
  46369. }
  46370. if (a._alphaIndex < b._alphaIndex) {
  46371. return -1;
  46372. }
  46373. // Then distance to camera
  46374. if (a._distanceToCamera < b._distanceToCamera) {
  46375. return 1;
  46376. }
  46377. if (a._distanceToCamera > b._distanceToCamera) {
  46378. return -1;
  46379. }
  46380. return 0;
  46381. });
  46382. // Render sub meshes
  46383. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46384. for (index = 0; index < sortedArray.length; index++) {
  46385. renderSubMesh(sortedArray[index]);
  46386. }
  46387. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46388. }
  46389. };
  46390. };
  46391. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  46392. var transform = scene.getTransformMatrix();
  46393. var meshPosition;
  46394. if (this.useCustomMeshPosition) {
  46395. meshPosition = this.customMeshPosition;
  46396. }
  46397. else if (this.attachedNode) {
  46398. meshPosition = this.attachedNode.position;
  46399. }
  46400. else {
  46401. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  46402. }
  46403. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  46404. this._screenCoordinates.x = pos.x / this._viewPort.width;
  46405. this._screenCoordinates.y = pos.y / this._viewPort.height;
  46406. if (this.invert)
  46407. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  46408. };
  46409. // Static methods
  46410. /**
  46411. * Creates a default mesh for the Volumeric Light Scattering post-process
  46412. * @param {string} The mesh name
  46413. * @param {BABYLON.Scene} The scene where to create the mesh
  46414. * @return {BABYLON.Mesh} the default mesh
  46415. */
  46416. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  46417. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  46418. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  46419. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  46420. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  46421. mesh.material = material;
  46422. return mesh;
  46423. };
  46424. __decorate([
  46425. BABYLON.serializeAsVector3()
  46426. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  46427. __decorate([
  46428. BABYLON.serialize()
  46429. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  46430. __decorate([
  46431. BABYLON.serialize()
  46432. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  46433. __decorate([
  46434. BABYLON.serializeAsMeshReference()
  46435. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  46436. __decorate([
  46437. BABYLON.serialize()
  46438. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  46439. __decorate([
  46440. BABYLON.serialize()
  46441. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  46442. __decorate([
  46443. BABYLON.serialize()
  46444. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  46445. __decorate([
  46446. BABYLON.serialize()
  46447. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  46448. __decorate([
  46449. BABYLON.serialize()
  46450. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  46451. return VolumetricLightScatteringPostProcess;
  46452. }(BABYLON.PostProcess));
  46453. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  46454. })(BABYLON || (BABYLON = {}));
  46455. // BABYLON.JS Chromatic Aberration GLSL Shader
  46456. // Author: Olivier Guyot
  46457. // Separates very slightly R, G and B colors on the edges of the screen
  46458. // Inspired by Francois Tarlier & Martins Upitis
  46459. var BABYLON;
  46460. (function (BABYLON) {
  46461. var LensRenderingPipeline = (function (_super) {
  46462. __extends(LensRenderingPipeline, _super);
  46463. /**
  46464. * @constructor
  46465. *
  46466. * Effect parameters are as follow:
  46467. * {
  46468. * chromatic_aberration: number; // from 0 to x (1 for realism)
  46469. * edge_blur: number; // from 0 to x (1 for realism)
  46470. * distortion: number; // from 0 to x (1 for realism)
  46471. * grain_amount: number; // from 0 to 1
  46472. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  46473. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  46474. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  46475. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  46476. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  46477. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  46478. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  46479. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  46480. * }
  46481. * Note: if an effect parameter is unset, effect is disabled
  46482. *
  46483. * @param {string} name - The rendering pipeline name
  46484. * @param {object} parameters - An object containing all parameters (see above)
  46485. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46486. * @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)
  46487. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46488. */
  46489. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  46490. var _this = this;
  46491. if (ratio === void 0) { ratio = 1.0; }
  46492. _super.call(this, scene.getEngine(), name);
  46493. // Lens effects can be of the following:
  46494. // - chromatic aberration (slight shift of RGB colors)
  46495. // - blur on the edge of the lens
  46496. // - lens distortion
  46497. // - depth-of-field blur & highlights enhancing
  46498. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  46499. // - grain effect (noise or custom texture)
  46500. // Two additional texture samplers are needed:
  46501. // - depth map (for depth-of-field)
  46502. // - grain texture
  46503. /**
  46504. * The chromatic aberration PostProcess id in the pipeline
  46505. * @type {string}
  46506. */
  46507. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  46508. /**
  46509. * The highlights enhancing PostProcess id in the pipeline
  46510. * @type {string}
  46511. */
  46512. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  46513. /**
  46514. * The depth-of-field PostProcess id in the pipeline
  46515. * @type {string}
  46516. */
  46517. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  46518. this._scene = scene;
  46519. // Fetch texture samplers
  46520. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46521. if (parameters.grain_texture) {
  46522. this._grainTexture = parameters.grain_texture;
  46523. }
  46524. else {
  46525. this._createGrainTexture();
  46526. }
  46527. // save parameters
  46528. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  46529. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  46530. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  46531. this._distortion = parameters.distortion ? parameters.distortion : 0;
  46532. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  46533. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  46534. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  46535. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  46536. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  46537. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  46538. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  46539. // Create effects
  46540. this._createChromaticAberrationPostProcess(ratio);
  46541. this._createHighlightsPostProcess(ratio);
  46542. this._createDepthOfFieldPostProcess(ratio / 4);
  46543. // Set up pipeline
  46544. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  46545. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  46546. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  46547. if (this._highlightsGain === -1) {
  46548. this._disableEffect(this.HighlightsEnhancingEffect, null);
  46549. }
  46550. // Finish
  46551. scene.postProcessRenderPipelineManager.addPipeline(this);
  46552. if (cameras) {
  46553. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46554. }
  46555. }
  46556. // public methods (self explanatory)
  46557. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  46558. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  46559. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  46560. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  46561. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  46562. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  46563. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  46564. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  46565. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  46566. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  46567. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  46568. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  46569. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  46570. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  46571. };
  46572. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  46573. this._highlightsPostProcess.updateEffect();
  46574. };
  46575. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  46576. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  46577. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  46578. this._highlightsGain = amount;
  46579. };
  46580. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  46581. if (this._highlightsGain === -1) {
  46582. this._highlightsGain = 1.0;
  46583. }
  46584. this._highlightsThreshold = amount;
  46585. };
  46586. LensRenderingPipeline.prototype.disableHighlights = function () {
  46587. this._highlightsGain = -1;
  46588. };
  46589. /**
  46590. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  46591. */
  46592. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46593. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46594. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46595. this._chromaticAberrationPostProcess = undefined;
  46596. this._highlightsPostProcess = undefined;
  46597. this._depthOfFieldPostProcess = undefined;
  46598. this._grainTexture.dispose();
  46599. if (disableDepthRender)
  46600. this._scene.disableDepthRenderer();
  46601. };
  46602. // colors shifting and distortion
  46603. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  46604. var _this = this;
  46605. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  46606. [], // samplers
  46607. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46608. this._chromaticAberrationPostProcess.onApply = function (effect) {
  46609. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  46610. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46611. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46612. };
  46613. };
  46614. // highlights enhancing
  46615. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  46616. var _this = this;
  46617. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  46618. [], // samplers
  46619. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  46620. this._highlightsPostProcess.onApply = function (effect) {
  46621. effect.setFloat('gain', _this._highlightsGain);
  46622. effect.setFloat('threshold', _this._highlightsThreshold);
  46623. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  46624. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46625. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46626. };
  46627. };
  46628. // colors shifting and distortion
  46629. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  46630. var _this = this;
  46631. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  46632. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  46633. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  46634. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46635. this._depthOfFieldPostProcess.onApply = function (effect) {
  46636. effect.setTexture("depthSampler", _this._depthTexture);
  46637. effect.setTexture("grainSampler", _this._grainTexture);
  46638. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  46639. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  46640. effect.setFloat('grain_amount', _this._grainAmount);
  46641. effect.setBool('blur_noise', _this._blurNoise);
  46642. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46643. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46644. effect.setFloat('distortion', _this._distortion);
  46645. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  46646. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  46647. effect.setFloat('aperture', _this._dofAperture);
  46648. effect.setFloat('darken', _this._dofDarken);
  46649. effect.setFloat('edge_blur', _this._edgeBlur);
  46650. effect.setBool('highlights', (_this._highlightsGain !== -1));
  46651. effect.setFloat('near', _this._scene.activeCamera.minZ);
  46652. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  46653. };
  46654. };
  46655. // creates a black and white random noise texture, 512x512
  46656. LensRenderingPipeline.prototype._createGrainTexture = function () {
  46657. var size = 512;
  46658. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46659. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46660. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46661. var context = this._grainTexture.getContext();
  46662. var rand = function (min, max) {
  46663. return Math.random() * (max - min) + min;
  46664. };
  46665. var value;
  46666. for (var x = 0; x < size; x++) {
  46667. for (var y = 0; y < size; y++) {
  46668. value = Math.floor(rand(0.42, 0.58) * 255);
  46669. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  46670. context.fillRect(x, y, 1, 1);
  46671. }
  46672. }
  46673. this._grainTexture.update(false);
  46674. };
  46675. return LensRenderingPipeline;
  46676. }(BABYLON.PostProcessRenderPipeline));
  46677. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  46678. })(BABYLON || (BABYLON = {}));
  46679. //
  46680. // This post-process allows the modification of rendered colors by using
  46681. // a 'look-up table' (LUT). This effect is also called Color Grading.
  46682. //
  46683. // The object needs to be provided an url to a texture containing the color
  46684. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  46685. // Use an image editing software to tweak the LUT to match your needs.
  46686. //
  46687. // For an example of a color LUT, see here:
  46688. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  46689. // For explanations on color grading, see here:
  46690. // http://udn.epicgames.com/Three/ColorGrading.html
  46691. //
  46692. var BABYLON;
  46693. (function (BABYLON) {
  46694. var ColorCorrectionPostProcess = (function (_super) {
  46695. __extends(ColorCorrectionPostProcess, _super);
  46696. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  46697. var _this = this;
  46698. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  46699. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46700. this._colorTableTexture.anisotropicFilteringLevel = 1;
  46701. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46702. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46703. this.onApply = function (effect) {
  46704. effect.setTexture("colorTable", _this._colorTableTexture);
  46705. };
  46706. }
  46707. return ColorCorrectionPostProcess;
  46708. }(BABYLON.PostProcess));
  46709. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  46710. })(BABYLON || (BABYLON = {}));
  46711. var BABYLON;
  46712. (function (BABYLON) {
  46713. var AnaglyphFreeCamera = (function (_super) {
  46714. __extends(AnaglyphFreeCamera, _super);
  46715. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  46716. _super.call(this, name, position, scene);
  46717. this.interaxialDistance = interaxialDistance;
  46718. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46719. }
  46720. AnaglyphFreeCamera.prototype.getTypeName = function () {
  46721. return "AnaglyphFreeCamera";
  46722. };
  46723. return AnaglyphFreeCamera;
  46724. }(BABYLON.FreeCamera));
  46725. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  46726. var AnaglyphArcRotateCamera = (function (_super) {
  46727. __extends(AnaglyphArcRotateCamera, _super);
  46728. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  46729. _super.call(this, name, alpha, beta, radius, target, scene);
  46730. this.interaxialDistance = interaxialDistance;
  46731. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46732. }
  46733. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  46734. return "AnaglyphArcRotateCamera";
  46735. };
  46736. return AnaglyphArcRotateCamera;
  46737. }(BABYLON.ArcRotateCamera));
  46738. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  46739. var AnaglyphGamepadCamera = (function (_super) {
  46740. __extends(AnaglyphGamepadCamera, _super);
  46741. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  46742. _super.call(this, name, position, scene);
  46743. this.interaxialDistance = interaxialDistance;
  46744. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46745. }
  46746. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  46747. return "AnaglyphGamepadCamera";
  46748. };
  46749. return AnaglyphGamepadCamera;
  46750. }(BABYLON.GamepadCamera));
  46751. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  46752. var AnaglyphUniversalCamera = (function (_super) {
  46753. __extends(AnaglyphUniversalCamera, _super);
  46754. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  46755. _super.call(this, name, position, scene);
  46756. this.interaxialDistance = interaxialDistance;
  46757. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46758. }
  46759. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  46760. return "AnaglyphUniversalCamera";
  46761. };
  46762. return AnaglyphUniversalCamera;
  46763. }(BABYLON.UniversalCamera));
  46764. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  46765. var StereoscopicFreeCamera = (function (_super) {
  46766. __extends(StereoscopicFreeCamera, _super);
  46767. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46768. _super.call(this, name, position, scene);
  46769. this.interaxialDistance = interaxialDistance;
  46770. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46771. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46772. }
  46773. StereoscopicFreeCamera.prototype.getTypeName = function () {
  46774. return "StereoscopicFreeCamera";
  46775. };
  46776. return StereoscopicFreeCamera;
  46777. }(BABYLON.FreeCamera));
  46778. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  46779. var StereoscopicArcRotateCamera = (function (_super) {
  46780. __extends(StereoscopicArcRotateCamera, _super);
  46781. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  46782. _super.call(this, name, alpha, beta, radius, target, scene);
  46783. this.interaxialDistance = interaxialDistance;
  46784. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46785. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46786. }
  46787. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  46788. return "StereoscopicArcRotateCamera";
  46789. };
  46790. return StereoscopicArcRotateCamera;
  46791. }(BABYLON.ArcRotateCamera));
  46792. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  46793. var StereoscopicGamepadCamera = (function (_super) {
  46794. __extends(StereoscopicGamepadCamera, _super);
  46795. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46796. _super.call(this, name, position, scene);
  46797. this.interaxialDistance = interaxialDistance;
  46798. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46799. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46800. }
  46801. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  46802. return "StereoscopicGamepadCamera";
  46803. };
  46804. return StereoscopicGamepadCamera;
  46805. }(BABYLON.GamepadCamera));
  46806. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  46807. var StereoscopicUniversalCamera = (function (_super) {
  46808. __extends(StereoscopicUniversalCamera, _super);
  46809. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46810. _super.call(this, name, position, scene);
  46811. this.interaxialDistance = interaxialDistance;
  46812. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46813. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46814. }
  46815. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  46816. return "StereoscopicUniversalCamera";
  46817. };
  46818. return StereoscopicUniversalCamera;
  46819. }(BABYLON.UniversalCamera));
  46820. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  46821. })(BABYLON || (BABYLON = {}));
  46822. var BABYLON;
  46823. (function (BABYLON) {
  46824. var HDRRenderingPipeline = (function (_super) {
  46825. __extends(HDRRenderingPipeline, _super);
  46826. /**
  46827. * @constructor
  46828. * @param {string} name - The rendering pipeline name
  46829. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46830. * @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)
  46831. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  46832. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46833. */
  46834. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  46835. var _this = this;
  46836. if (originalPostProcess === void 0) { originalPostProcess = null; }
  46837. _super.call(this, scene.getEngine(), name);
  46838. /**
  46839. * Public members
  46840. */
  46841. // Gaussian Blur
  46842. /**
  46843. * Gaussian blur coefficient
  46844. * @type {number}
  46845. */
  46846. this.gaussCoeff = 0.3;
  46847. /**
  46848. * Gaussian blur mean
  46849. * @type {number}
  46850. */
  46851. this.gaussMean = 1.0;
  46852. /**
  46853. * Gaussian blur standard deviation
  46854. * @type {number}
  46855. */
  46856. this.gaussStandDev = 0.8;
  46857. /**
  46858. * Gaussian blur multiplier. Multiplies the blur effect
  46859. * @type {number}
  46860. */
  46861. this.gaussMultiplier = 4.0;
  46862. // HDR
  46863. /**
  46864. * Exposure, controls the overall intensity of the pipeline
  46865. * @type {number}
  46866. */
  46867. this.exposure = 1.0;
  46868. /**
  46869. * Minimum luminance that the post-process can output. Luminance is >= 0
  46870. * @type {number}
  46871. */
  46872. this.minimumLuminance = 1.0;
  46873. /**
  46874. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  46875. * @type {number}
  46876. */
  46877. this.maximumLuminance = 1e20;
  46878. /**
  46879. * Increase rate for luminance: eye adaptation speed to dark
  46880. * @type {number}
  46881. */
  46882. this.luminanceIncreaserate = 0.5;
  46883. /**
  46884. * Decrease rate for luminance: eye adaptation speed to bright
  46885. * @type {number}
  46886. */
  46887. this.luminanceDecreaseRate = 0.5;
  46888. // Bright pass
  46889. /**
  46890. * Minimum luminance needed to compute HDR
  46891. * @type {number}
  46892. */
  46893. this.brightThreshold = 0.8;
  46894. this._needUpdate = true;
  46895. this._scene = scene;
  46896. // Bright pass
  46897. this._createBrightPassPostProcess(scene, ratio);
  46898. // Down sample X4
  46899. this._createDownSampleX4PostProcess(scene, ratio);
  46900. // Create gaussian blur post-processes
  46901. this._createGaussianBlurPostProcess(scene, ratio);
  46902. // Texture adder
  46903. this._createTextureAdderPostProcess(scene, ratio);
  46904. // Luminance generator
  46905. this._createLuminanceGeneratorPostProcess(scene);
  46906. // HDR
  46907. this._createHDRPostProcess(scene, ratio);
  46908. // Pass postprocess
  46909. if (originalPostProcess === null) {
  46910. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46911. }
  46912. else {
  46913. this._originalPostProcess = originalPostProcess;
  46914. }
  46915. // Configure pipeline
  46916. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  46917. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  46918. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  46919. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  46920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  46921. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  46922. var addDownSamplerPostProcess = function (id) {
  46923. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  46924. };
  46925. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46926. addDownSamplerPostProcess(i);
  46927. }
  46928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  46929. // Finish
  46930. scene.postProcessRenderPipelineManager.addPipeline(this);
  46931. if (cameras !== null) {
  46932. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46933. }
  46934. this.update();
  46935. }
  46936. /**
  46937. * Tells the pipeline to update its post-processes
  46938. */
  46939. HDRRenderingPipeline.prototype.update = function () {
  46940. this._needUpdate = true;
  46941. };
  46942. /**
  46943. * Returns the current calculated luminance
  46944. */
  46945. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  46946. return this._hdrCurrentLuminance;
  46947. };
  46948. /**
  46949. * Returns the currently drawn luminance
  46950. */
  46951. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  46952. return this._hdrOutputLuminance;
  46953. };
  46954. /**
  46955. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  46956. */
  46957. HDRRenderingPipeline.prototype.dispose = function () {
  46958. this._originalPostProcess = undefined;
  46959. this._brightPassPostProcess = undefined;
  46960. this._downSampleX4PostProcess = undefined;
  46961. this._guassianBlurHPostProcess = undefined;
  46962. this._guassianBlurVPostProcess = undefined;
  46963. this._textureAdderPostProcess = undefined;
  46964. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46965. this._downSamplePostProcesses[i] = undefined;
  46966. }
  46967. this._hdrPostProcess = undefined;
  46968. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46969. };
  46970. /**
  46971. * Creates the HDR post-process and computes the luminance adaptation
  46972. */
  46973. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  46974. var _this = this;
  46975. var hdrLastLuminance = 0.0;
  46976. this._hdrOutputLuminance = -1.0;
  46977. this._hdrCurrentLuminance = 1.0;
  46978. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  46979. this._hdrPostProcess.onApply = function (effect) {
  46980. if (_this._hdrOutputLuminance < 0.0) {
  46981. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46982. }
  46983. else {
  46984. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  46985. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  46986. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  46987. }
  46988. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  46989. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  46990. }
  46991. else {
  46992. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46993. }
  46994. }
  46995. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  46996. hdrLastLuminance += scene.getEngine().getDeltaTime();
  46997. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46998. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46999. effect.setFloat("exposure", _this.exposure);
  47000. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  47001. _this._needUpdate = false;
  47002. };
  47003. };
  47004. /**
  47005. * Texture Adder post-process
  47006. */
  47007. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  47008. var _this = this;
  47009. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  47010. this._textureAdderPostProcess.onApply = function (effect) {
  47011. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47012. };
  47013. };
  47014. /**
  47015. * Down sample X4 post-process
  47016. */
  47017. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  47018. var _this = this;
  47019. var downSampleX4Offsets = new Array(32);
  47020. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  47021. this._downSampleX4PostProcess.onApply = function (effect) {
  47022. if (_this._needUpdate) {
  47023. var id = 0;
  47024. for (var i = -2; i < 2; i++) {
  47025. for (var j = -2; j < 2; j++) {
  47026. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  47027. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  47028. id += 2;
  47029. }
  47030. }
  47031. }
  47032. effect.setArray2("dsOffsets", downSampleX4Offsets);
  47033. };
  47034. };
  47035. /**
  47036. * Bright pass post-process
  47037. */
  47038. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  47039. var _this = this;
  47040. var brightOffsets = new Array(8);
  47041. var brightPassCallback = function (effect) {
  47042. if (_this._needUpdate) {
  47043. var sU = (1.0 / _this._brightPassPostProcess.width);
  47044. var sV = (1.0 / _this._brightPassPostProcess.height);
  47045. brightOffsets[0] = -0.5 * sU;
  47046. brightOffsets[1] = 0.5 * sV;
  47047. brightOffsets[2] = 0.5 * sU;
  47048. brightOffsets[3] = 0.5 * sV;
  47049. brightOffsets[4] = -0.5 * sU;
  47050. brightOffsets[5] = -0.5 * sV;
  47051. brightOffsets[6] = 0.5 * sU;
  47052. brightOffsets[7] = -0.5 * sV;
  47053. }
  47054. effect.setArray2("dsOffsets", brightOffsets);
  47055. effect.setFloat("brightThreshold", _this.brightThreshold);
  47056. };
  47057. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  47058. this._brightPassPostProcess.onApply = brightPassCallback;
  47059. };
  47060. /**
  47061. * Luminance generator. Creates the luminance post-process and down sample post-processes
  47062. */
  47063. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  47064. var _this = this;
  47065. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  47066. var luminanceOffsets = new Array(8);
  47067. var downSampleOffsets = new Array(18);
  47068. var halfDestPixelSize;
  47069. this._downSamplePostProcesses = new Array(lumSteps);
  47070. // Utils for luminance
  47071. var luminanceUpdateSourceOffsets = function (width, height) {
  47072. var sU = (1.0 / width);
  47073. var sV = (1.0 / height);
  47074. luminanceOffsets[0] = -0.5 * sU;
  47075. luminanceOffsets[1] = 0.5 * sV;
  47076. luminanceOffsets[2] = 0.5 * sU;
  47077. luminanceOffsets[3] = 0.5 * sV;
  47078. luminanceOffsets[4] = -0.5 * sU;
  47079. luminanceOffsets[5] = -0.5 * sV;
  47080. luminanceOffsets[6] = 0.5 * sU;
  47081. luminanceOffsets[7] = -0.5 * sV;
  47082. };
  47083. var luminanceUpdateDestOffsets = function (width, height) {
  47084. var id = 0;
  47085. for (var x = -1; x < 2; x++) {
  47086. for (var y = -1; y < 2; y++) {
  47087. downSampleOffsets[id] = (x) / width;
  47088. downSampleOffsets[id + 1] = (y) / height;
  47089. id += 2;
  47090. }
  47091. }
  47092. };
  47093. // Luminance callback
  47094. var luminanceCallback = function (effect) {
  47095. if (_this._needUpdate) {
  47096. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  47097. }
  47098. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47099. effect.setArray2("lumOffsets", luminanceOffsets);
  47100. };
  47101. // Down sample callbacks
  47102. var downSampleCallback = function (indice) {
  47103. var i = indice;
  47104. return function (effect) {
  47105. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47106. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47107. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  47108. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  47109. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  47110. effect.setArray2("dsOffsets", downSampleOffsets);
  47111. };
  47112. };
  47113. var downSampleAfterRenderCallback = function (effect) {
  47114. // Unpack result
  47115. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  47116. 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);
  47117. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  47118. };
  47119. // Create luminance post-process
  47120. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  47121. 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);
  47122. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  47123. // Create down sample post-processes
  47124. for (var i = lumSteps - 2; i >= 0; i--) {
  47125. var length = Math.pow(3, i);
  47126. ratio = { width: length, height: length };
  47127. var defines = "#define DOWN_SAMPLE\n";
  47128. if (i === 0) {
  47129. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  47130. }
  47131. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  47132. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  47133. if (i === 0) {
  47134. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  47135. }
  47136. }
  47137. };
  47138. /**
  47139. * Gaussian blur post-processes. Horizontal and Vertical
  47140. */
  47141. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  47142. var _this = this;
  47143. var blurOffsetsW = new Array(9);
  47144. var blurOffsetsH = new Array(9);
  47145. var blurWeights = new Array(9);
  47146. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  47147. // Utils for gaussian blur
  47148. var calculateBlurOffsets = function (height) {
  47149. var lastOutputDimensions = {
  47150. width: scene.getEngine().getRenderWidth(),
  47151. height: scene.getEngine().getRenderHeight()
  47152. };
  47153. for (var i = 0; i < 9; i++) {
  47154. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47155. if (height) {
  47156. blurOffsetsH[i] = value;
  47157. }
  47158. else {
  47159. blurOffsetsW[i] = value;
  47160. }
  47161. }
  47162. };
  47163. var calculateWeights = function () {
  47164. var x = 0.0;
  47165. for (var i = 0; i < 9; i++) {
  47166. x = (i - 4.0) / 4.0;
  47167. 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));
  47168. }
  47169. };
  47170. // Callback
  47171. var gaussianBlurCallback = function (height) {
  47172. return function (effect) {
  47173. if (_this._needUpdate) {
  47174. calculateWeights();
  47175. calculateBlurOffsets(height);
  47176. }
  47177. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  47178. effect.setArray("blurWeights", blurWeights);
  47179. effect.setFloat("multiplier", _this.gaussMultiplier);
  47180. };
  47181. };
  47182. // Create horizontal gaussian blur post-processes
  47183. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  47184. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  47185. // Create vertical gaussian blur post-process
  47186. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  47187. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  47188. };
  47189. // Luminance generator
  47190. HDRRenderingPipeline.LUM_STEPS = 6;
  47191. return HDRRenderingPipeline;
  47192. }(BABYLON.PostProcessRenderPipeline));
  47193. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  47194. })(BABYLON || (BABYLON = {}));
  47195. var BABYLON;
  47196. (function (BABYLON) {
  47197. var FaceAdjacencies = (function () {
  47198. function FaceAdjacencies() {
  47199. this.edges = new Array();
  47200. this.edgesConnectedCount = 0;
  47201. }
  47202. return FaceAdjacencies;
  47203. }());
  47204. var EdgesRenderer = (function () {
  47205. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  47206. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  47207. if (epsilon === void 0) { epsilon = 0.95; }
  47208. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  47209. this.edgesWidthScalerForOrthographic = 1000.0;
  47210. this.edgesWidthScalerForPerspective = 50.0;
  47211. this._linesPositions = new Array();
  47212. this._linesNormals = new Array();
  47213. this._linesIndices = new Array();
  47214. this._buffers = {};
  47215. this._checkVerticesInsteadOfIndices = false;
  47216. this._source = source;
  47217. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  47218. this._epsilon = epsilon;
  47219. this._prepareRessources();
  47220. this._generateEdgesLines();
  47221. }
  47222. EdgesRenderer.prototype._prepareRessources = function () {
  47223. if (this._lineShader) {
  47224. return;
  47225. }
  47226. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  47227. attributes: ["position", "normal"],
  47228. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  47229. });
  47230. this._lineShader.disableDepthWrite = true;
  47231. this._lineShader.backFaceCulling = false;
  47232. };
  47233. EdgesRenderer.prototype.dispose = function () {
  47234. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  47235. if (buffer) {
  47236. buffer.dispose();
  47237. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  47238. }
  47239. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  47240. if (buffer) {
  47241. buffer.dispose();
  47242. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  47243. }
  47244. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  47245. this._lineShader.dispose();
  47246. };
  47247. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  47248. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  47249. return 0;
  47250. }
  47251. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  47252. return 1;
  47253. }
  47254. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  47255. return 2;
  47256. }
  47257. return -1;
  47258. };
  47259. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  47260. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  47261. return 0;
  47262. }
  47263. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  47264. return 1;
  47265. }
  47266. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  47267. return 2;
  47268. }
  47269. return -1;
  47270. };
  47271. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  47272. var needToCreateLine;
  47273. if (edge === undefined) {
  47274. needToCreateLine = true;
  47275. }
  47276. else {
  47277. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  47278. needToCreateLine = dotProduct < this._epsilon;
  47279. }
  47280. if (needToCreateLine) {
  47281. var offset = this._linesPositions.length / 3;
  47282. var normal = p0.subtract(p1);
  47283. normal.normalize();
  47284. // Positions
  47285. this._linesPositions.push(p0.x);
  47286. this._linesPositions.push(p0.y);
  47287. this._linesPositions.push(p0.z);
  47288. this._linesPositions.push(p0.x);
  47289. this._linesPositions.push(p0.y);
  47290. this._linesPositions.push(p0.z);
  47291. this._linesPositions.push(p1.x);
  47292. this._linesPositions.push(p1.y);
  47293. this._linesPositions.push(p1.z);
  47294. this._linesPositions.push(p1.x);
  47295. this._linesPositions.push(p1.y);
  47296. this._linesPositions.push(p1.z);
  47297. // Normals
  47298. this._linesNormals.push(p1.x);
  47299. this._linesNormals.push(p1.y);
  47300. this._linesNormals.push(p1.z);
  47301. this._linesNormals.push(-1);
  47302. this._linesNormals.push(p1.x);
  47303. this._linesNormals.push(p1.y);
  47304. this._linesNormals.push(p1.z);
  47305. this._linesNormals.push(1);
  47306. this._linesNormals.push(p0.x);
  47307. this._linesNormals.push(p0.y);
  47308. this._linesNormals.push(p0.z);
  47309. this._linesNormals.push(-1);
  47310. this._linesNormals.push(p0.x);
  47311. this._linesNormals.push(p0.y);
  47312. this._linesNormals.push(p0.z);
  47313. this._linesNormals.push(1);
  47314. // Indices
  47315. this._linesIndices.push(offset);
  47316. this._linesIndices.push(offset + 1);
  47317. this._linesIndices.push(offset + 2);
  47318. this._linesIndices.push(offset);
  47319. this._linesIndices.push(offset + 2);
  47320. this._linesIndices.push(offset + 3);
  47321. }
  47322. };
  47323. EdgesRenderer.prototype._generateEdgesLines = function () {
  47324. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47325. var indices = this._source.getIndices();
  47326. // First let's find adjacencies
  47327. var adjacencies = new Array();
  47328. var faceNormals = new Array();
  47329. var index;
  47330. var faceAdjacencies;
  47331. // Prepare faces
  47332. for (index = 0; index < indices.length; index += 3) {
  47333. faceAdjacencies = new FaceAdjacencies();
  47334. var p0Index = indices[index];
  47335. var p1Index = indices[index + 1];
  47336. var p2Index = indices[index + 2];
  47337. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  47338. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  47339. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  47340. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  47341. faceNormal.normalize();
  47342. faceNormals.push(faceNormal);
  47343. adjacencies.push(faceAdjacencies);
  47344. }
  47345. // Scan
  47346. for (index = 0; index < adjacencies.length; index++) {
  47347. faceAdjacencies = adjacencies[index];
  47348. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  47349. var otherFaceAdjacencies = adjacencies[otherIndex];
  47350. if (faceAdjacencies.edgesConnectedCount === 3) {
  47351. break;
  47352. }
  47353. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  47354. continue;
  47355. }
  47356. var otherP0 = indices[otherIndex * 3];
  47357. var otherP1 = indices[otherIndex * 3 + 1];
  47358. var otherP2 = indices[otherIndex * 3 + 2];
  47359. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  47360. var otherEdgeIndex;
  47361. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  47362. continue;
  47363. }
  47364. switch (edgeIndex) {
  47365. case 0:
  47366. if (this._checkVerticesInsteadOfIndices) {
  47367. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47368. }
  47369. else {
  47370. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  47371. }
  47372. break;
  47373. case 1:
  47374. if (this._checkVerticesInsteadOfIndices) {
  47375. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47376. }
  47377. else {
  47378. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  47379. }
  47380. break;
  47381. case 2:
  47382. if (this._checkVerticesInsteadOfIndices) {
  47383. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47384. }
  47385. else {
  47386. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  47387. }
  47388. break;
  47389. }
  47390. if (otherEdgeIndex === -1) {
  47391. continue;
  47392. }
  47393. faceAdjacencies.edges[edgeIndex] = otherIndex;
  47394. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  47395. faceAdjacencies.edgesConnectedCount++;
  47396. otherFaceAdjacencies.edgesConnectedCount++;
  47397. if (faceAdjacencies.edgesConnectedCount === 3) {
  47398. break;
  47399. }
  47400. }
  47401. }
  47402. }
  47403. // Create lines
  47404. for (index = 0; index < adjacencies.length; index++) {
  47405. // 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
  47406. var current = adjacencies[index];
  47407. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  47408. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  47409. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  47410. }
  47411. // Merge into a single mesh
  47412. var engine = this._source.getScene().getEngine();
  47413. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  47414. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  47415. this._ib = engine.createIndexBuffer(this._linesIndices);
  47416. this._indicesCount = this._linesIndices.length;
  47417. };
  47418. EdgesRenderer.prototype.render = function () {
  47419. if (!this._lineShader.isReady()) {
  47420. return;
  47421. }
  47422. var scene = this._source.getScene();
  47423. var engine = scene.getEngine();
  47424. this._lineShader._preBind();
  47425. // VBOs
  47426. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  47427. scene.resetCachedMaterial();
  47428. this._lineShader.setColor4("color", this._source.edgesColor);
  47429. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  47430. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  47431. }
  47432. else {
  47433. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  47434. }
  47435. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  47436. this._lineShader.bind(this._source.getWorldMatrix());
  47437. // Draw order
  47438. engine.draw(true, 0, this._indicesCount);
  47439. this._lineShader.unbind();
  47440. engine.setDepthWrite(true);
  47441. };
  47442. return EdgesRenderer;
  47443. }());
  47444. BABYLON.EdgesRenderer = EdgesRenderer;
  47445. })(BABYLON || (BABYLON = {}));
  47446. var BABYLON;
  47447. (function (BABYLON) {
  47448. (function (TonemappingOperator) {
  47449. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  47450. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  47451. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  47452. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  47453. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  47454. var TonemappingOperator = BABYLON.TonemappingOperator;
  47455. ;
  47456. var TonemapPostProcess = (function (_super) {
  47457. __extends(TonemapPostProcess, _super);
  47458. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  47459. var _this = this;
  47460. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47461. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47462. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  47463. this._operator = _operator;
  47464. this.exposureAdjustment = exposureAdjustment;
  47465. var defines = "#define ";
  47466. if (this._operator === TonemappingOperator.Hable)
  47467. defines += "HABLE_TONEMAPPING";
  47468. else if (this._operator === TonemappingOperator.Reinhard)
  47469. defines += "REINHARD_TONEMAPPING";
  47470. else if (this._operator === TonemappingOperator.HejiDawson)
  47471. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  47472. else if (this._operator === TonemappingOperator.Photographic)
  47473. defines += "PHOTOGRAPHIC_TONEMAPPING";
  47474. //sadly a second call to create the effect.
  47475. this.updateEffect(defines);
  47476. this.onApply = function (effect) {
  47477. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  47478. };
  47479. }
  47480. return TonemapPostProcess;
  47481. }(BABYLON.PostProcess));
  47482. BABYLON.TonemapPostProcess = TonemapPostProcess;
  47483. })(BABYLON || (BABYLON = {}));
  47484. var BABYLON;
  47485. (function (BABYLON) {
  47486. var ReflectionProbe = (function () {
  47487. function ReflectionProbe(name, size, scene, generateMipMaps) {
  47488. var _this = this;
  47489. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47490. this.name = name;
  47491. this._viewMatrix = BABYLON.Matrix.Identity();
  47492. this._target = BABYLON.Vector3.Zero();
  47493. this._add = BABYLON.Vector3.Zero();
  47494. this.invertYAxis = false;
  47495. this.position = BABYLON.Vector3.Zero();
  47496. this._scene = scene;
  47497. this._scene.reflectionProbes.push(this);
  47498. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  47499. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  47500. switch (faceIndex) {
  47501. case 0:
  47502. _this._add.copyFromFloats(1, 0, 0);
  47503. break;
  47504. case 1:
  47505. _this._add.copyFromFloats(-1, 0, 0);
  47506. break;
  47507. case 2:
  47508. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  47509. break;
  47510. case 3:
  47511. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  47512. break;
  47513. case 4:
  47514. _this._add.copyFromFloats(0, 0, 1);
  47515. break;
  47516. case 5:
  47517. _this._add.copyFromFloats(0, 0, -1);
  47518. break;
  47519. }
  47520. if (_this._attachedMesh) {
  47521. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  47522. }
  47523. _this.position.addToRef(_this._add, _this._target);
  47524. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  47525. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  47526. });
  47527. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  47528. scene.updateTransformMatrix(true);
  47529. });
  47530. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  47531. }
  47532. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  47533. get: function () {
  47534. return this._renderTargetTexture.refreshRate;
  47535. },
  47536. set: function (value) {
  47537. this._renderTargetTexture.refreshRate = value;
  47538. },
  47539. enumerable: true,
  47540. configurable: true
  47541. });
  47542. ReflectionProbe.prototype.getScene = function () {
  47543. return this._scene;
  47544. };
  47545. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  47546. get: function () {
  47547. return this._renderTargetTexture;
  47548. },
  47549. enumerable: true,
  47550. configurable: true
  47551. });
  47552. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  47553. get: function () {
  47554. return this._renderTargetTexture.renderList;
  47555. },
  47556. enumerable: true,
  47557. configurable: true
  47558. });
  47559. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  47560. this._attachedMesh = mesh;
  47561. };
  47562. ReflectionProbe.prototype.dispose = function () {
  47563. var index = this._scene.reflectionProbes.indexOf(this);
  47564. if (index !== -1) {
  47565. // Remove from the scene if found
  47566. this._scene.reflectionProbes.splice(index, 1);
  47567. }
  47568. if (this._renderTargetTexture) {
  47569. this._renderTargetTexture.dispose();
  47570. this._renderTargetTexture = null;
  47571. }
  47572. };
  47573. return ReflectionProbe;
  47574. }());
  47575. BABYLON.ReflectionProbe = ReflectionProbe;
  47576. })(BABYLON || (BABYLON = {}));
  47577. var BABYLON;
  47578. (function (BABYLON) {
  47579. var SolidParticle = (function () {
  47580. /**
  47581. * Creates a Solid Particle object.
  47582. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  47583. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  47584. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  47585. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  47586. * `shapeId` (integer) is the model shape identifier in the SPS.
  47587. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  47588. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  47589. */
  47590. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  47591. this.idx = 0; // particle global index
  47592. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  47593. this.position = BABYLON.Vector3.Zero(); // position
  47594. this.rotation = BABYLON.Vector3.Zero(); // rotation
  47595. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  47596. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  47597. this.velocity = BABYLON.Vector3.Zero(); // velocity
  47598. this.alive = true; // alive
  47599. this.isVisible = true; // visibility
  47600. this._pos = 0; // index of this particle in the global "positions" array
  47601. this.shapeId = 0; // model shape id
  47602. this.idxInShape = 0; // index of the particle in its shape id
  47603. this.idx = particleIndex;
  47604. this._pos = positionIndex;
  47605. this._model = model;
  47606. this.shapeId = shapeId;
  47607. this.idxInShape = idxInShape;
  47608. this._sps = sps;
  47609. if (modelBoundingInfo) {
  47610. this._modelBoundingInfo = modelBoundingInfo;
  47611. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  47612. }
  47613. }
  47614. Object.defineProperty(SolidParticle.prototype, "scale", {
  47615. /**
  47616. * legacy support, changed scale to scaling
  47617. */
  47618. get: function () {
  47619. return this.scaling;
  47620. },
  47621. set: function (scale) {
  47622. this.scaling = scale;
  47623. },
  47624. enumerable: true,
  47625. configurable: true
  47626. });
  47627. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  47628. /**
  47629. * legacy support, changed quaternion to rotationQuaternion
  47630. */
  47631. get: function () {
  47632. return this.rotationQuaternion;
  47633. },
  47634. set: function (q) {
  47635. this.rotationQuaternion = q;
  47636. },
  47637. enumerable: true,
  47638. configurable: true
  47639. });
  47640. /**
  47641. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  47642. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  47643. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  47644. */
  47645. SolidParticle.prototype.intersectsMesh = function (target) {
  47646. if (!this._boundingInfo || !target._boundingInfo) {
  47647. return false;
  47648. }
  47649. if (this._sps._bSphereOnly) {
  47650. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  47651. }
  47652. return this._boundingInfo.intersects(target._boundingInfo, false);
  47653. };
  47654. return SolidParticle;
  47655. }());
  47656. BABYLON.SolidParticle = SolidParticle;
  47657. var ModelShape = (function () {
  47658. /**
  47659. * 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.
  47660. * SPS internal tool, don't use it manually.
  47661. */
  47662. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  47663. this.shapeID = id;
  47664. this._shape = shape;
  47665. this._shapeUV = shapeUV;
  47666. this._positionFunction = posFunction;
  47667. this._vertexFunction = vtxFunction;
  47668. }
  47669. return ModelShape;
  47670. }());
  47671. BABYLON.ModelShape = ModelShape;
  47672. })(BABYLON || (BABYLON = {}));
  47673. var BABYLON;
  47674. (function (BABYLON) {
  47675. /**
  47676. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  47677. */
  47678. var SolidParticleSystem = (function () {
  47679. /**
  47680. * Creates a SPS (Solid Particle System) object.
  47681. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47682. * `scene` (Scene) is the scene in which the SPS is added.
  47683. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  47684. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  47685. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  47686. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  47687. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  47688. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  47689. */
  47690. function SolidParticleSystem(name, scene, options) {
  47691. // public members
  47692. /**
  47693. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47694. * Example : var p = SPS.particles[i];
  47695. */
  47696. this.particles = new Array();
  47697. /**
  47698. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47699. */
  47700. this.nbParticles = 0;
  47701. /**
  47702. * If the particles must ever face the camera (default false). Useful for planar particles.
  47703. */
  47704. this.billboard = false;
  47705. /**
  47706. * Recompute normals when adding a shape
  47707. */
  47708. this.recomputeNormals = true;
  47709. /**
  47710. * This a counter ofr your own usage. It's not set by any SPS functions.
  47711. */
  47712. this.counter = 0;
  47713. /**
  47714. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47715. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47716. */
  47717. this.vars = {};
  47718. this._positions = new Array();
  47719. this._indices = new Array();
  47720. this._normals = new Array();
  47721. this._colors = new Array();
  47722. this._uvs = new Array();
  47723. this._index = 0; // indices index
  47724. this._updatable = true;
  47725. this._pickable = false;
  47726. this._isVisibilityBoxLocked = false;
  47727. this._alwaysVisible = false;
  47728. this._shapeCounter = 0;
  47729. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  47730. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47731. this._computeParticleColor = true;
  47732. this._computeParticleTexture = true;
  47733. this._computeParticleRotation = true;
  47734. this._computeParticleVertex = false;
  47735. this._computeBoundingBox = false;
  47736. this._cam_axisZ = BABYLON.Vector3.Zero();
  47737. this._cam_axisY = BABYLON.Vector3.Zero();
  47738. this._cam_axisX = BABYLON.Vector3.Zero();
  47739. this._axisX = BABYLON.Axis.X;
  47740. this._axisY = BABYLON.Axis.Y;
  47741. this._axisZ = BABYLON.Axis.Z;
  47742. this._camDir = BABYLON.Vector3.Zero();
  47743. this._rotMatrix = new BABYLON.Matrix();
  47744. this._invertMatrix = new BABYLON.Matrix();
  47745. this._rotated = BABYLON.Vector3.Zero();
  47746. this._quaternion = new BABYLON.Quaternion();
  47747. this._vertex = BABYLON.Vector3.Zero();
  47748. this._normal = BABYLON.Vector3.Zero();
  47749. this._yaw = 0.0;
  47750. this._pitch = 0.0;
  47751. this._roll = 0.0;
  47752. this._halfroll = 0.0;
  47753. this._halfpitch = 0.0;
  47754. this._halfyaw = 0.0;
  47755. this._sinRoll = 0.0;
  47756. this._cosRoll = 0.0;
  47757. this._sinPitch = 0.0;
  47758. this._cosPitch = 0.0;
  47759. this._sinYaw = 0.0;
  47760. this._cosYaw = 0.0;
  47761. this._w = 0.0;
  47762. this._minimum = BABYLON.Tmp.Vector3[0];
  47763. this._maximum = BABYLON.Tmp.Vector3[1];
  47764. this._scale = BABYLON.Tmp.Vector3[2];
  47765. this._translation = BABYLON.Tmp.Vector3[3];
  47766. this._minBbox = BABYLON.Tmp.Vector3[4];
  47767. this._maxBbox = BABYLON.Tmp.Vector3[5];
  47768. this._particlesIntersect = false;
  47769. this._bSphereOnly = false;
  47770. this._bSphereRadiusFactor = 1.0;
  47771. this.name = name;
  47772. this._scene = scene;
  47773. this._camera = scene.activeCamera;
  47774. this._pickable = options ? options.isPickable : false;
  47775. this._particlesIntersect = options ? options.particleIntersection : false;
  47776. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  47777. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  47778. if (options && options.updatable) {
  47779. this._updatable = options.updatable;
  47780. }
  47781. else {
  47782. this._updatable = true;
  47783. }
  47784. if (this._pickable) {
  47785. this.pickedParticles = [];
  47786. }
  47787. }
  47788. /**
  47789. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47790. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47791. */
  47792. SolidParticleSystem.prototype.buildMesh = function () {
  47793. if (this.nbParticles === 0) {
  47794. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47795. this.addShape(triangle, 1);
  47796. triangle.dispose();
  47797. }
  47798. this._positions32 = new Float32Array(this._positions);
  47799. this._uvs32 = new Float32Array(this._uvs);
  47800. this._colors32 = new Float32Array(this._colors);
  47801. if (this.recomputeNormals) {
  47802. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  47803. }
  47804. this._normals32 = new Float32Array(this._normals);
  47805. this._fixedNormal32 = new Float32Array(this._normals);
  47806. var vertexData = new BABYLON.VertexData();
  47807. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47808. vertexData.indices = this._indices;
  47809. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47810. if (this._uvs32) {
  47811. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47812. ;
  47813. }
  47814. if (this._colors32) {
  47815. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47816. }
  47817. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47818. vertexData.applyToMesh(mesh, this._updatable);
  47819. this.mesh = mesh;
  47820. this.mesh.isPickable = this._pickable;
  47821. // free memory
  47822. this._positions = null;
  47823. this._normals = null;
  47824. this._uvs = null;
  47825. this._colors = null;
  47826. if (!this._updatable) {
  47827. this.particles.length = 0;
  47828. }
  47829. return mesh;
  47830. };
  47831. /**
  47832. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47833. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47834. * Thus the particles generated from `digest()` have their property `position` set yet.
  47835. * `mesh` ( Mesh ) is the mesh to be digested
  47836. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47837. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47838. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47839. */
  47840. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47841. var size = (options && options.facetNb) || 1;
  47842. var number = (options && options.number);
  47843. var delta = (options && options.delta) || 0;
  47844. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47845. var meshInd = mesh.getIndices();
  47846. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47847. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47848. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47849. var f = 0; // facet counter
  47850. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47851. // compute size from number
  47852. if (number) {
  47853. number = (number > totalFacets) ? totalFacets : number;
  47854. size = Math.round(totalFacets / number);
  47855. delta = 0;
  47856. }
  47857. else {
  47858. size = (size > totalFacets) ? totalFacets : size;
  47859. }
  47860. var facetPos = []; // submesh positions
  47861. var facetInd = []; // submesh indices
  47862. var facetUV = []; // submesh UV
  47863. var facetCol = []; // submesh colors
  47864. var barycenter = BABYLON.Tmp.Vector3[0];
  47865. var rand;
  47866. var sizeO = size;
  47867. while (f < totalFacets) {
  47868. size = sizeO + Math.floor((1 + delta) * Math.random());
  47869. if (f > totalFacets - size) {
  47870. size = totalFacets - f;
  47871. }
  47872. // reset temp arrays
  47873. facetPos.length = 0;
  47874. facetInd.length = 0;
  47875. facetUV.length = 0;
  47876. facetCol.length = 0;
  47877. // iterate over "size" facets
  47878. var fi = 0;
  47879. for (var j = f * 3; j < (f + size) * 3; j++) {
  47880. facetInd.push(fi);
  47881. var i = meshInd[j];
  47882. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47883. if (meshUV) {
  47884. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47885. }
  47886. if (meshCol) {
  47887. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47888. }
  47889. fi++;
  47890. }
  47891. // create a model shape for each single particle
  47892. var idx = this.nbParticles;
  47893. var shape = this._posToShape(facetPos);
  47894. var shapeUV = this._uvsToShapeUV(facetUV);
  47895. // compute the barycenter of the shape
  47896. var v;
  47897. for (v = 0; v < shape.length; v++) {
  47898. barycenter.addInPlace(shape[v]);
  47899. }
  47900. barycenter.scaleInPlace(1 / shape.length);
  47901. // shift the shape from its barycenter to the origin
  47902. for (v = 0; v < shape.length; v++) {
  47903. shape[v].subtractInPlace(barycenter);
  47904. }
  47905. var bInfo;
  47906. if (this._particlesIntersect) {
  47907. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47908. }
  47909. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  47910. // add the particle in the SPS
  47911. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47912. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  47913. // initialize the particle position
  47914. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47915. this._index += shape.length;
  47916. idx++;
  47917. this.nbParticles++;
  47918. this._shapeCounter++;
  47919. f += size;
  47920. }
  47921. return this;
  47922. };
  47923. //reset copy
  47924. SolidParticleSystem.prototype._resetCopy = function () {
  47925. this._copy.position.x = 0;
  47926. this._copy.position.y = 0;
  47927. this._copy.position.z = 0;
  47928. this._copy.rotation.x = 0;
  47929. this._copy.rotation.y = 0;
  47930. this._copy.rotation.z = 0;
  47931. this._copy.rotationQuaternion = null;
  47932. this._copy.scaling.x = 1;
  47933. this._copy.scaling.y = 1;
  47934. this._copy.scaling.z = 1;
  47935. this._copy.uvs.x = 0;
  47936. this._copy.uvs.y = 0;
  47937. this._copy.uvs.z = 1;
  47938. this._copy.uvs.w = 1;
  47939. this._copy.color = null;
  47940. };
  47941. // _meshBuilder : inserts the shape model in the global SPS mesh
  47942. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47943. var i;
  47944. var u = 0;
  47945. var c = 0;
  47946. var n = 0;
  47947. this._resetCopy();
  47948. if (options && options.positionFunction) {
  47949. options.positionFunction(this._copy, idx, idxInShape);
  47950. }
  47951. if (this._copy.rotationQuaternion) {
  47952. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47953. }
  47954. else {
  47955. this._yaw = this._copy.rotation.y;
  47956. this._pitch = this._copy.rotation.x;
  47957. this._roll = this._copy.rotation.z;
  47958. this._quaternionRotationYPR();
  47959. }
  47960. this._quaternionToRotationMatrix();
  47961. for (i = 0; i < shape.length; i++) {
  47962. this._vertex.x = shape[i].x;
  47963. this._vertex.y = shape[i].y;
  47964. this._vertex.z = shape[i].z;
  47965. if (options && options.vertexFunction) {
  47966. options.vertexFunction(this._copy, this._vertex, i);
  47967. }
  47968. this._vertex.x *= this._copy.scaling.x;
  47969. this._vertex.y *= this._copy.scaling.y;
  47970. this._vertex.z *= this._copy.scaling.z;
  47971. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47972. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47973. if (meshUV) {
  47974. 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);
  47975. u += 2;
  47976. }
  47977. if (this._copy.color) {
  47978. this._color = this._copy.color;
  47979. }
  47980. else if (meshCol && meshCol[c] !== undefined) {
  47981. this._color.r = meshCol[c];
  47982. this._color.g = meshCol[c + 1];
  47983. this._color.b = meshCol[c + 2];
  47984. this._color.a = meshCol[c + 3];
  47985. }
  47986. else {
  47987. this._color.r = 1;
  47988. this._color.g = 1;
  47989. this._color.b = 1;
  47990. this._color.a = 1;
  47991. }
  47992. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47993. c += 4;
  47994. if (!this.recomputeNormals && meshNor) {
  47995. this._normal.x = meshNor[n];
  47996. this._normal.y = meshNor[n + 1];
  47997. this._normal.z = meshNor[n + 2];
  47998. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  47999. normals.push(this._normal.x, this._normal.y, this._normal.z);
  48000. n += 3;
  48001. }
  48002. }
  48003. for (i = 0; i < meshInd.length; i++) {
  48004. indices.push(p + meshInd[i]);
  48005. }
  48006. if (this._pickable) {
  48007. var nbfaces = meshInd.length / 3;
  48008. for (i = 0; i < nbfaces; i++) {
  48009. this.pickedParticles.push({ idx: idx, faceId: i });
  48010. }
  48011. }
  48012. };
  48013. // returns a shape array from positions array
  48014. SolidParticleSystem.prototype._posToShape = function (positions) {
  48015. var shape = [];
  48016. for (var i = 0; i < positions.length; i += 3) {
  48017. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  48018. }
  48019. return shape;
  48020. };
  48021. // returns a shapeUV array from a Vector4 uvs
  48022. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  48023. var shapeUV = [];
  48024. if (uvs) {
  48025. for (var i = 0; i < uvs.length; i++)
  48026. shapeUV.push(uvs[i]);
  48027. }
  48028. return shapeUV;
  48029. };
  48030. // adds a new particle object in the particles array
  48031. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  48032. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  48033. };
  48034. /**
  48035. * Adds some particles to the SPS from the model shape. Returns the shape id.
  48036. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  48037. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  48038. * `nb` (positive integer) the number of particles to be created from this model
  48039. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  48040. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  48041. */
  48042. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  48043. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48044. var meshInd = mesh.getIndices();
  48045. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48046. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48047. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48048. var bbInfo;
  48049. if (this._particlesIntersect) {
  48050. bbInfo = mesh.getBoundingInfo();
  48051. }
  48052. var shape = this._posToShape(meshPos);
  48053. var shapeUV = this._uvsToShapeUV(meshUV);
  48054. var posfunc = options ? options.positionFunction : null;
  48055. var vtxfunc = options ? options.vertexFunction : null;
  48056. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  48057. // particles
  48058. var idx = this.nbParticles;
  48059. for (var i = 0; i < nb; i++) {
  48060. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  48061. if (this._updatable) {
  48062. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  48063. }
  48064. this._index += shape.length;
  48065. idx++;
  48066. }
  48067. this.nbParticles += nb;
  48068. this._shapeCounter++;
  48069. return this._shapeCounter - 1;
  48070. };
  48071. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  48072. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  48073. this._resetCopy();
  48074. if (particle._model._positionFunction) {
  48075. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  48076. }
  48077. if (this._copy.rotationQuaternion) {
  48078. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  48079. }
  48080. else {
  48081. this._yaw = this._copy.rotation.y;
  48082. this._pitch = this._copy.rotation.x;
  48083. this._roll = this._copy.rotation.z;
  48084. this._quaternionRotationYPR();
  48085. }
  48086. this._quaternionToRotationMatrix();
  48087. this._shape = particle._model._shape;
  48088. for (var pt = 0; pt < this._shape.length; pt++) {
  48089. this._vertex.x = this._shape[pt].x;
  48090. this._vertex.y = this._shape[pt].y;
  48091. this._vertex.z = this._shape[pt].z;
  48092. if (particle._model._vertexFunction) {
  48093. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  48094. }
  48095. this._vertex.x *= this._copy.scaling.x;
  48096. this._vertex.y *= this._copy.scaling.y;
  48097. this._vertex.z *= this._copy.scaling.z;
  48098. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  48099. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  48100. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  48101. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  48102. }
  48103. particle.position.x = 0.0;
  48104. particle.position.y = 0.0;
  48105. particle.position.z = 0.0;
  48106. particle.rotation.x = 0.0;
  48107. particle.rotation.y = 0.0;
  48108. particle.rotation.z = 0.0;
  48109. particle.rotationQuaternion = null;
  48110. particle.scaling.x = 1.0;
  48111. particle.scaling.y = 1.0;
  48112. particle.scaling.z = 1.0;
  48113. };
  48114. /**
  48115. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  48116. */
  48117. SolidParticleSystem.prototype.rebuildMesh = function () {
  48118. for (var p = 0; p < this.particles.length; p++) {
  48119. this._rebuildParticle(this.particles[p]);
  48120. }
  48121. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  48122. };
  48123. /**
  48124. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  48125. * This method calls `updateParticle()` for each particle of the SPS.
  48126. * For an animated SPS, it is usually called within the render loop.
  48127. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  48128. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  48129. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  48130. */
  48131. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  48132. if (start === void 0) { start = 0; }
  48133. if (end === void 0) { end = this.nbParticles - 1; }
  48134. if (update === void 0) { update = true; }
  48135. if (!this._updatable) {
  48136. return;
  48137. }
  48138. // custom beforeUpdate
  48139. this.beforeUpdateParticles(start, end, update);
  48140. this._cam_axisX.x = 1.0;
  48141. this._cam_axisX.y = 0.0;
  48142. this._cam_axisX.z = 0.0;
  48143. this._cam_axisY.x = 0.0;
  48144. this._cam_axisY.y = 1.0;
  48145. this._cam_axisY.z = 0.0;
  48146. this._cam_axisZ.x = 0.0;
  48147. this._cam_axisZ.y = 0.0;
  48148. this._cam_axisZ.z = 1.0;
  48149. // if the particles will always face the camera
  48150. if (this.billboard) {
  48151. // compute the camera position and un-rotate it by the current mesh rotation
  48152. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  48153. this._quaternionToRotationMatrix();
  48154. this._rotMatrix.invertToRef(this._invertMatrix);
  48155. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  48156. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  48157. this._cam_axisZ.normalize();
  48158. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  48159. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  48160. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  48161. this._cam_axisY.normalize();
  48162. this._cam_axisX.normalize();
  48163. }
  48164. }
  48165. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  48166. var idx = 0;
  48167. var index = 0;
  48168. var colidx = 0;
  48169. var colorIndex = 0;
  48170. var uvidx = 0;
  48171. var uvIndex = 0;
  48172. var pt = 0;
  48173. if (this._computeBoundingBox) {
  48174. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  48175. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  48176. }
  48177. // particle loop
  48178. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  48179. for (var p = start; p <= end; p++) {
  48180. this._particle = this.particles[p];
  48181. this._shape = this._particle._model._shape;
  48182. this._shapeUV = this._particle._model._shapeUV;
  48183. // call to custom user function to update the particle properties
  48184. this.updateParticle(this._particle);
  48185. if (this._particle.isVisible) {
  48186. // particle rotation matrix
  48187. if (this.billboard) {
  48188. this._particle.rotation.x = 0.0;
  48189. this._particle.rotation.y = 0.0;
  48190. }
  48191. if (this._computeParticleRotation || this.billboard) {
  48192. if (this._particle.rotationQuaternion) {
  48193. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  48194. }
  48195. else {
  48196. this._yaw = this._particle.rotation.y;
  48197. this._pitch = this._particle.rotation.x;
  48198. this._roll = this._particle.rotation.z;
  48199. this._quaternionRotationYPR();
  48200. }
  48201. this._quaternionToRotationMatrix();
  48202. }
  48203. // particle vertex loop
  48204. for (pt = 0; pt < this._shape.length; pt++) {
  48205. idx = index + pt * 3;
  48206. colidx = colorIndex + pt * 4;
  48207. uvidx = uvIndex + pt * 2;
  48208. this._vertex.x = this._shape[pt].x;
  48209. this._vertex.y = this._shape[pt].y;
  48210. this._vertex.z = this._shape[pt].z;
  48211. if (this._computeParticleVertex) {
  48212. this.updateParticleVertex(this._particle, this._vertex, pt);
  48213. }
  48214. // positions
  48215. this._vertex.x *= this._particle.scaling.x;
  48216. this._vertex.y *= this._particle.scaling.y;
  48217. this._vertex.z *= this._particle.scaling.z;
  48218. 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];
  48219. 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;
  48220. 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;
  48221. 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;
  48222. 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;
  48223. 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;
  48224. 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;
  48225. if (this._computeBoundingBox) {
  48226. if (this._positions32[idx] < this._minimum.x) {
  48227. this._minimum.x = this._positions32[idx];
  48228. }
  48229. if (this._positions32[idx] > this._maximum.x) {
  48230. this._maximum.x = this._positions32[idx];
  48231. }
  48232. if (this._positions32[idx + 1] < this._minimum.y) {
  48233. this._minimum.y = this._positions32[idx + 1];
  48234. }
  48235. if (this._positions32[idx + 1] > this._maximum.y) {
  48236. this._maximum.y = this._positions32[idx + 1];
  48237. }
  48238. if (this._positions32[idx + 2] < this._minimum.z) {
  48239. this._minimum.z = this._positions32[idx + 2];
  48240. }
  48241. if (this._positions32[idx + 2] > this._maximum.z) {
  48242. this._maximum.z = this._positions32[idx + 2];
  48243. }
  48244. }
  48245. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  48246. if (!this._computeParticleVertex) {
  48247. this._normal.x = this._fixedNormal32[idx];
  48248. this._normal.y = this._fixedNormal32[idx + 1];
  48249. this._normal.z = this._fixedNormal32[idx + 2];
  48250. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  48251. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  48252. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  48253. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  48254. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  48255. 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;
  48256. 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;
  48257. }
  48258. if (this._computeParticleColor) {
  48259. this._colors32[colidx] = this._particle.color.r;
  48260. this._colors32[colidx + 1] = this._particle.color.g;
  48261. this._colors32[colidx + 2] = this._particle.color.b;
  48262. this._colors32[colidx + 3] = this._particle.color.a;
  48263. }
  48264. if (this._computeParticleTexture) {
  48265. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  48266. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  48267. }
  48268. }
  48269. }
  48270. else {
  48271. for (pt = 0; pt < this._shape.length; pt++) {
  48272. idx = index + pt * 3;
  48273. colidx = colorIndex + pt * 4;
  48274. uvidx = uvIndex + pt * 2;
  48275. this._positions32[idx] = this._camera.position.x;
  48276. this._positions32[idx + 1] = this._camera.position.y;
  48277. this._positions32[idx + 2] = this._camera.position.z;
  48278. this._normals32[idx] = 0.0;
  48279. this._normals32[idx + 1] = 0.0;
  48280. this._normals32[idx + 2] = 0.0;
  48281. if (this._computeParticleColor) {
  48282. this._colors32[colidx] = this._particle.color.r;
  48283. this._colors32[colidx + 1] = this._particle.color.g;
  48284. this._colors32[colidx + 2] = this._particle.color.b;
  48285. this._colors32[colidx + 3] = this._particle.color.a;
  48286. }
  48287. if (this._computeParticleTexture) {
  48288. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  48289. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  48290. }
  48291. }
  48292. }
  48293. // if the particle intersections must be computed : update the bbInfo
  48294. if (this._particlesIntersect) {
  48295. var bInfo = this._particle._boundingInfo;
  48296. var bBox = bInfo.boundingBox;
  48297. var bSphere = bInfo.boundingSphere;
  48298. if (!this._bSphereOnly) {
  48299. // place, scale and rotate the particle bbox within the SPS local system, then update it
  48300. for (var b = 0; b < bBox.vectors.length; b++) {
  48301. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  48302. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  48303. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  48304. 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];
  48305. 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;
  48306. 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;
  48307. 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;
  48308. 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;
  48309. 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;
  48310. 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;
  48311. }
  48312. bBox._update(this.mesh._worldMatrix);
  48313. }
  48314. // place and scale the particle bouding sphere in the SPS local system, then update it
  48315. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  48316. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  48317. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  48318. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  48319. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  48320. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  48321. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  48322. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  48323. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  48324. 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));
  48325. bSphere._update(this.mesh._worldMatrix);
  48326. }
  48327. // increment indexes for the next particle
  48328. index = idx + 3;
  48329. colorIndex = colidx + 4;
  48330. uvIndex = uvidx + 2;
  48331. }
  48332. // if the VBO must be updated
  48333. if (update) {
  48334. if (this._computeParticleColor) {
  48335. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  48336. }
  48337. if (this._computeParticleTexture) {
  48338. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  48339. }
  48340. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  48341. if (!this.mesh.areNormalsFrozen) {
  48342. if (this._computeParticleVertex) {
  48343. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  48344. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  48345. for (var i = 0; i < this._normals32.length; i++) {
  48346. this._fixedNormal32[i] = this._normals32[i];
  48347. }
  48348. }
  48349. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  48350. }
  48351. }
  48352. if (this._computeBoundingBox) {
  48353. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  48354. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  48355. }
  48356. this.afterUpdateParticles(start, end, update);
  48357. };
  48358. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  48359. this._halfroll = this._roll * 0.5;
  48360. this._halfpitch = this._pitch * 0.5;
  48361. this._halfyaw = this._yaw * 0.5;
  48362. this._sinRoll = Math.sin(this._halfroll);
  48363. this._cosRoll = Math.cos(this._halfroll);
  48364. this._sinPitch = Math.sin(this._halfpitch);
  48365. this._cosPitch = Math.cos(this._halfpitch);
  48366. this._sinYaw = Math.sin(this._halfyaw);
  48367. this._cosYaw = Math.cos(this._halfyaw);
  48368. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  48369. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  48370. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  48371. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  48372. };
  48373. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  48374. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  48375. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  48376. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  48377. this._rotMatrix.m[3] = 0;
  48378. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  48379. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  48380. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  48381. this._rotMatrix.m[7] = 0;
  48382. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  48383. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  48384. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  48385. this._rotMatrix.m[11] = 0;
  48386. this._rotMatrix.m[12] = 0;
  48387. this._rotMatrix.m[13] = 0;
  48388. this._rotMatrix.m[14] = 0;
  48389. this._rotMatrix.m[15] = 1.0;
  48390. };
  48391. /**
  48392. * Disposes the SPS
  48393. */
  48394. SolidParticleSystem.prototype.dispose = function () {
  48395. this.mesh.dispose();
  48396. this.vars = null;
  48397. // drop references to internal big arrays for the GC
  48398. this._positions = null;
  48399. this._indices = null;
  48400. this._normals = null;
  48401. this._uvs = null;
  48402. this._colors = null;
  48403. this._positions32 = null;
  48404. this._normals32 = null;
  48405. this._fixedNormal32 = null;
  48406. this._uvs32 = null;
  48407. this._colors32 = null;
  48408. this.pickedParticles = null;
  48409. };
  48410. /**
  48411. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  48412. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48413. */
  48414. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  48415. if (!this._isVisibilityBoxLocked) {
  48416. this.mesh.refreshBoundingInfo();
  48417. }
  48418. };
  48419. /**
  48420. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  48421. * @param size the size (float) of the visibility box
  48422. * note : this doesn't lock the SPS mesh bounding box.
  48423. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48424. */
  48425. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  48426. var vis = size / 2;
  48427. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  48428. };
  48429. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  48430. // getter and setter
  48431. get: function () {
  48432. return this._alwaysVisible;
  48433. },
  48434. /**
  48435. * Sets the SPS as always visible or not
  48436. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48437. */
  48438. set: function (val) {
  48439. this._alwaysVisible = val;
  48440. this.mesh.alwaysSelectAsActiveMesh = val;
  48441. },
  48442. enumerable: true,
  48443. configurable: true
  48444. });
  48445. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  48446. get: function () {
  48447. return this._isVisibilityBoxLocked;
  48448. },
  48449. /**
  48450. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  48451. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48452. */
  48453. set: function (val) {
  48454. this._isVisibilityBoxLocked = val;
  48455. this.mesh.getBoundingInfo().isLocked = val;
  48456. },
  48457. enumerable: true,
  48458. configurable: true
  48459. });
  48460. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  48461. // getters
  48462. get: function () {
  48463. return this._computeParticleRotation;
  48464. },
  48465. // Optimizer setters
  48466. /**
  48467. * Tells to `setParticles()` to compute the particle rotations or not.
  48468. * Default value : true. The SPS is faster when it's set to false.
  48469. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  48470. */
  48471. set: function (val) {
  48472. this._computeParticleRotation = val;
  48473. },
  48474. enumerable: true,
  48475. configurable: true
  48476. });
  48477. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  48478. get: function () {
  48479. return this._computeParticleColor;
  48480. },
  48481. /**
  48482. * Tells to `setParticles()` to compute the particle colors or not.
  48483. * Default value : true. The SPS is faster when it's set to false.
  48484. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  48485. */
  48486. set: function (val) {
  48487. this._computeParticleColor = val;
  48488. },
  48489. enumerable: true,
  48490. configurable: true
  48491. });
  48492. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  48493. get: function () {
  48494. return this._computeParticleTexture;
  48495. },
  48496. /**
  48497. * Tells to `setParticles()` to compute the particle textures or not.
  48498. * Default value : true. The SPS is faster when it's set to false.
  48499. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  48500. */
  48501. set: function (val) {
  48502. this._computeParticleTexture = val;
  48503. },
  48504. enumerable: true,
  48505. configurable: true
  48506. });
  48507. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  48508. get: function () {
  48509. return this._computeParticleVertex;
  48510. },
  48511. /**
  48512. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  48513. * Default value : false. The SPS is faster when it's set to false.
  48514. * Note : the particle custom vertex positions aren't stored values.
  48515. */
  48516. set: function (val) {
  48517. this._computeParticleVertex = val;
  48518. },
  48519. enumerable: true,
  48520. configurable: true
  48521. });
  48522. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  48523. get: function () {
  48524. return this._computeBoundingBox;
  48525. },
  48526. /**
  48527. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  48528. */
  48529. set: function (val) {
  48530. this._computeBoundingBox = val;
  48531. },
  48532. enumerable: true,
  48533. configurable: true
  48534. });
  48535. // =======================================================================
  48536. // Particle behavior logic
  48537. // these following methods may be overwritten by the user to fit his needs
  48538. /**
  48539. * This function does nothing. It may be overwritten to set all the particle first values.
  48540. * The SPS doesn't call this function, you may have to call it by your own.
  48541. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48542. */
  48543. SolidParticleSystem.prototype.initParticles = function () {
  48544. };
  48545. /**
  48546. * This function does nothing. It may be overwritten to recycle a particle.
  48547. * The SPS doesn't call this function, you may have to call it by your own.
  48548. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48549. */
  48550. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48551. return particle;
  48552. };
  48553. /**
  48554. * Updates a particle : this function should be overwritten by the user.
  48555. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48556. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48557. * ex : just set a particle position or velocity and recycle conditions
  48558. */
  48559. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48560. return particle;
  48561. };
  48562. /**
  48563. * Updates a vertex of a particle : it can be overwritten by the user.
  48564. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48565. * @param particle the current particle
  48566. * @param vertex the current index of the current particle
  48567. * @param pt the index of the current vertex in the particle shape
  48568. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48569. * ex : just set a vertex particle position
  48570. */
  48571. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48572. return vertex;
  48573. };
  48574. /**
  48575. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48576. * This does nothing and may be overwritten by the user.
  48577. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48578. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48579. * @param update the boolean update value actually passed to setParticles()
  48580. */
  48581. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48582. };
  48583. /**
  48584. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48585. * This will be passed three parameters.
  48586. * This does nothing and may be overwritten by the user.
  48587. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48588. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48589. * @param update the boolean update value actually passed to setParticles()
  48590. */
  48591. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48592. };
  48593. return SolidParticleSystem;
  48594. }());
  48595. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48596. })(BABYLON || (BABYLON = {}));
  48597. var BABYLON;
  48598. (function (BABYLON) {
  48599. var Internals;
  48600. (function (Internals) {
  48601. var FileFaceOrientation = (function () {
  48602. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  48603. this.name = name;
  48604. this.worldAxisForNormal = worldAxisForNormal;
  48605. this.worldAxisForFileX = worldAxisForFileX;
  48606. this.worldAxisForFileY = worldAxisForFileY;
  48607. }
  48608. return FileFaceOrientation;
  48609. }());
  48610. ;
  48611. /**
  48612. * Helper class dealing with the extraction of spherical polynomial dataArray
  48613. * from a cube map.
  48614. */
  48615. var CubeMapToSphericalPolynomialTools = (function () {
  48616. function CubeMapToSphericalPolynomialTools() {
  48617. }
  48618. /**
  48619. * Converts a cubemap to the according Spherical Polynomial data.
  48620. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48621. *
  48622. * @param cubeInfo The Cube map to extract the information from.
  48623. * @return The Spherical Polynomial data.
  48624. */
  48625. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  48626. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  48627. var totalSolidAngle = 0.0;
  48628. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  48629. var du = 2.0 / cubeInfo.size;
  48630. var dv = du;
  48631. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  48632. var minUV = du * 0.5 - 1.0;
  48633. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48634. var fileFace = this.FileFaces[faceIndex];
  48635. var dataArray = cubeInfo[fileFace.name];
  48636. var v = minUV;
  48637. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  48638. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  48639. // Because SP is still linear, so summation is fine in that basis.
  48640. for (var y = 0; y < cubeInfo.size; y++) {
  48641. var u = minUV;
  48642. for (var x = 0; x < cubeInfo.size; x++) {
  48643. // World direction (not normalised)
  48644. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  48645. worldDirection.normalize();
  48646. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  48647. if (1) {
  48648. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  48649. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  48650. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  48651. var color = new BABYLON.Color3(r, g, b);
  48652. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48653. }
  48654. else {
  48655. if (faceIndex == 0) {
  48656. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48657. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48658. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48659. }
  48660. else if (faceIndex == 1) {
  48661. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48662. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48663. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48664. }
  48665. else if (faceIndex == 2) {
  48666. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48667. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48668. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48669. }
  48670. else if (faceIndex == 3) {
  48671. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48672. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48673. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48674. }
  48675. else if (faceIndex == 4) {
  48676. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48677. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48678. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48679. }
  48680. else if (faceIndex == 5) {
  48681. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48682. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48683. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48684. }
  48685. 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]);
  48686. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48687. }
  48688. totalSolidAngle += deltaSolidAngle;
  48689. u += du;
  48690. }
  48691. v += dv;
  48692. }
  48693. }
  48694. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  48695. var correction = correctSolidAngle / totalSolidAngle;
  48696. sphericalHarmonics.scale(correction);
  48697. // Additionally scale by pi -- audit needed
  48698. sphericalHarmonics.scale(1.0 / Math.PI);
  48699. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48700. };
  48701. CubeMapToSphericalPolynomialTools.FileFaces = [
  48702. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48703. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48704. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48705. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48706. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48707. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48708. ];
  48709. return CubeMapToSphericalPolynomialTools;
  48710. }());
  48711. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48712. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48713. })(BABYLON || (BABYLON = {}));
  48714. var BABYLON;
  48715. (function (BABYLON) {
  48716. var Internals;
  48717. (function (Internals) {
  48718. /**
  48719. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48720. */
  48721. var PanoramaToCubeMapTools = (function () {
  48722. function PanoramaToCubeMapTools() {
  48723. }
  48724. /**
  48725. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48726. *
  48727. * @param float32Array The source data.
  48728. * @param inputWidth The width of the input panorama.
  48729. * @param inputhHeight The height of the input panorama.
  48730. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48731. * @return The cubemap data
  48732. */
  48733. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48734. if (!float32Array) {
  48735. throw "ConvertPanoramaToCubemap: input cannot be null";
  48736. }
  48737. if (float32Array.length != inputWidth * inputHeight * 3) {
  48738. throw "ConvertPanoramaToCubemap: input size is wrong";
  48739. }
  48740. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48741. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48742. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48743. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48744. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48745. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48746. return {
  48747. front: textureFront,
  48748. back: textureBack,
  48749. left: textureLeft,
  48750. right: textureRight,
  48751. up: textureUp,
  48752. down: textureDown,
  48753. size: size
  48754. };
  48755. };
  48756. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  48757. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  48758. var textureArray = new Float32Array(buffer);
  48759. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  48760. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  48761. var dy = 1 / texSize;
  48762. var fy = 0;
  48763. for (var y = 0; y < texSize; y++) {
  48764. var xv1 = faceData[0];
  48765. var xv2 = faceData[2];
  48766. for (var x = 0; x < texSize; x++) {
  48767. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  48768. v.normalize();
  48769. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  48770. // 3 channels per pixels
  48771. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  48772. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  48773. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  48774. xv1 = xv1.add(rotDX1);
  48775. xv2 = xv2.add(rotDX2);
  48776. }
  48777. fy += dy;
  48778. }
  48779. return textureArray;
  48780. };
  48781. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  48782. var theta = Math.atan2(vDir.z, vDir.x);
  48783. var phi = Math.acos(vDir.y);
  48784. while (theta < -Math.PI)
  48785. theta += 2 * Math.PI;
  48786. while (theta > Math.PI)
  48787. theta -= 2 * Math.PI;
  48788. var dx = theta / Math.PI;
  48789. var dy = phi / Math.PI;
  48790. // recenter.
  48791. dx = dx * 0.5 + 0.5;
  48792. var px = Math.round(dx * inputWidth);
  48793. if (px < 0)
  48794. px = 0;
  48795. else if (px >= inputWidth)
  48796. px = inputWidth - 1;
  48797. var py = Math.round(dy * inputHeight);
  48798. if (py < 0)
  48799. py = 0;
  48800. else if (py >= inputHeight)
  48801. py = inputHeight - 1;
  48802. var inputY = (inputHeight - py - 1);
  48803. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  48804. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  48805. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  48806. return {
  48807. r: r,
  48808. g: g,
  48809. b: b
  48810. };
  48811. };
  48812. PanoramaToCubeMapTools.FACE_FRONT = [
  48813. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48814. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48815. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48816. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48817. ];
  48818. PanoramaToCubeMapTools.FACE_BACK = [
  48819. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48820. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48821. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48822. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48823. ];
  48824. PanoramaToCubeMapTools.FACE_RIGHT = [
  48825. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48826. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48827. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48828. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48829. ];
  48830. PanoramaToCubeMapTools.FACE_LEFT = [
  48831. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48832. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48833. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48834. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48835. ];
  48836. PanoramaToCubeMapTools.FACE_DOWN = [
  48837. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48838. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48839. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48840. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48841. ];
  48842. PanoramaToCubeMapTools.FACE_UP = [
  48843. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48844. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48845. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48846. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48847. ];
  48848. return PanoramaToCubeMapTools;
  48849. }());
  48850. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48851. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48852. })(BABYLON || (BABYLON = {}));
  48853. var BABYLON;
  48854. (function (BABYLON) {
  48855. var Internals;
  48856. (function (Internals) {
  48857. ;
  48858. /**
  48859. * This groups tools to convert HDR texture to native colors array.
  48860. */
  48861. var HDRTools = (function () {
  48862. function HDRTools() {
  48863. }
  48864. HDRTools.Ldexp = function (mantissa, exponent) {
  48865. if (exponent > 1023) {
  48866. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48867. }
  48868. if (exponent < -1074) {
  48869. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48870. }
  48871. return mantissa * Math.pow(2, exponent);
  48872. };
  48873. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48874. if (exponent > 0) {
  48875. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48876. float32array[index + 0] = red * exponent;
  48877. float32array[index + 1] = green * exponent;
  48878. float32array[index + 2] = blue * exponent;
  48879. }
  48880. else {
  48881. float32array[index + 0] = 0;
  48882. float32array[index + 1] = 0;
  48883. float32array[index + 2] = 0;
  48884. }
  48885. };
  48886. HDRTools.readStringLine = function (uint8array, startIndex) {
  48887. var line = "";
  48888. var character = "";
  48889. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48890. character = String.fromCharCode(uint8array[i]);
  48891. if (character == "\n") {
  48892. break;
  48893. }
  48894. line += character;
  48895. }
  48896. return line;
  48897. };
  48898. /**
  48899. * Reads header information from an RGBE texture stored in a native array.
  48900. * More information on this format are available here:
  48901. * https://en.wikipedia.org/wiki/RGBE_image_format
  48902. *
  48903. * @param uint8array The binary file stored in native array.
  48904. * @return The header information.
  48905. */
  48906. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48907. var height = 0;
  48908. var width = 0;
  48909. var line = this.readStringLine(uint8array, 0);
  48910. if (line[0] != '#' || line[1] != '?') {
  48911. throw "Bad HDR Format.";
  48912. }
  48913. var endOfHeader = false;
  48914. var findFormat = false;
  48915. var lineIndex = 0;
  48916. do {
  48917. lineIndex += (line.length + 1);
  48918. line = this.readStringLine(uint8array, lineIndex);
  48919. if (line == "FORMAT=32-bit_rle_rgbe") {
  48920. findFormat = true;
  48921. }
  48922. else if (line.length == 0) {
  48923. endOfHeader = true;
  48924. }
  48925. } while (!endOfHeader);
  48926. if (!findFormat) {
  48927. throw "HDR Bad header format, unsupported FORMAT";
  48928. }
  48929. lineIndex += (line.length + 1);
  48930. line = this.readStringLine(uint8array, lineIndex);
  48931. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48932. var match = sizeRegexp.exec(line);
  48933. // TODO. Support +Y and -X if needed.
  48934. if (match.length < 3) {
  48935. throw "HDR Bad header format, no size";
  48936. }
  48937. width = parseInt(match[2]);
  48938. height = parseInt(match[1]);
  48939. if (width < 8 || width > 0x7fff) {
  48940. throw "HDR Bad header format, unsupported size";
  48941. }
  48942. lineIndex += (line.length + 1);
  48943. return {
  48944. height: height,
  48945. width: width,
  48946. dataPosition: lineIndex
  48947. };
  48948. };
  48949. /**
  48950. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48951. * This RGBE texture needs to store the information as a panorama.
  48952. *
  48953. * More information on this format are available here:
  48954. * https://en.wikipedia.org/wiki/RGBE_image_format
  48955. *
  48956. * @param buffer The binary file stored in an array buffer.
  48957. * @param size The expected size of the extracted cubemap.
  48958. * @return The Cube Map information.
  48959. */
  48960. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48961. var uint8array = new Uint8Array(buffer);
  48962. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48963. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48964. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48965. return cubeMapData;
  48966. };
  48967. /**
  48968. * Returns the pixels data extracted from an RGBE texture.
  48969. * This pixels will be stored left to right up to down in the R G B order in one array.
  48970. *
  48971. * More information on this format are available here:
  48972. * https://en.wikipedia.org/wiki/RGBE_image_format
  48973. *
  48974. * @param uint8array The binary file stored in an array buffer.
  48975. * @param hdrInfo The header information of the file.
  48976. * @return The pixels data in RGB right to left up to down order.
  48977. */
  48978. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48979. // Keep for multi format supports.
  48980. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48981. };
  48982. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48983. var num_scanlines = hdrInfo.height;
  48984. var scanline_width = hdrInfo.width;
  48985. var a, b, c, d, count;
  48986. var dataIndex = hdrInfo.dataPosition;
  48987. var index = 0, endIndex = 0, i = 0;
  48988. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48989. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48990. // 3 channels of 4 bytes per pixel in float.
  48991. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48992. var resultArray = new Float32Array(resultBuffer);
  48993. // read in each successive scanline
  48994. while (num_scanlines > 0) {
  48995. a = uint8array[dataIndex++];
  48996. b = uint8array[dataIndex++];
  48997. c = uint8array[dataIndex++];
  48998. d = uint8array[dataIndex++];
  48999. if (a != 2 || b != 2 || (c & 0x80)) {
  49000. // this file is not run length encoded
  49001. throw "HDR Bad header format, not RLE";
  49002. }
  49003. if (((c << 8) | d) != scanline_width) {
  49004. throw "HDR Bad header format, wrong scan line width";
  49005. }
  49006. index = 0;
  49007. // read each of the four channels for the scanline into the buffer
  49008. for (i = 0; i < 4; i++) {
  49009. endIndex = (i + 1) * scanline_width;
  49010. while (index < endIndex) {
  49011. a = uint8array[dataIndex++];
  49012. b = uint8array[dataIndex++];
  49013. if (a > 128) {
  49014. // a run of the same value
  49015. count = a - 128;
  49016. if ((count == 0) || (count > endIndex - index)) {
  49017. throw "HDR Bad Format, bad scanline data (run)";
  49018. }
  49019. while (count-- > 0) {
  49020. scanLineArray[index++] = b;
  49021. }
  49022. }
  49023. else {
  49024. // a non-run
  49025. count = a;
  49026. if ((count == 0) || (count > endIndex - index)) {
  49027. throw "HDR Bad Format, bad scanline data (non-run)";
  49028. }
  49029. scanLineArray[index++] = b;
  49030. if (--count > 0) {
  49031. for (var j = 0; j < count; j++) {
  49032. scanLineArray[index++] = uint8array[dataIndex++];
  49033. }
  49034. }
  49035. }
  49036. }
  49037. }
  49038. // now convert data from buffer into floats
  49039. for (i = 0; i < scanline_width; i++) {
  49040. a = scanLineArray[i];
  49041. b = scanLineArray[i + scanline_width];
  49042. c = scanLineArray[i + 2 * scanline_width];
  49043. d = scanLineArray[i + 3 * scanline_width];
  49044. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  49045. }
  49046. num_scanlines--;
  49047. }
  49048. return resultArray;
  49049. };
  49050. return HDRTools;
  49051. }());
  49052. Internals.HDRTools = HDRTools;
  49053. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49054. })(BABYLON || (BABYLON = {}));
  49055. //_______________________________________________________________
  49056. // Extracted from CubeMapGen:
  49057. // https://code.google.com/archive/p/cubemapgen/
  49058. //
  49059. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  49060. //_______________________________________________________________
  49061. var BABYLON;
  49062. (function (BABYLON) {
  49063. var Internals;
  49064. (function (Internals) {
  49065. /**
  49066. * The bounding box information used during the conversion process.
  49067. */
  49068. var CMGBoundinBox = (function () {
  49069. function CMGBoundinBox() {
  49070. this.min = new BABYLON.Vector3(0, 0, 0);
  49071. this.max = new BABYLON.Vector3(0, 0, 0);
  49072. this.clear();
  49073. }
  49074. CMGBoundinBox.prototype.clear = function () {
  49075. this.min.x = CMGBoundinBox.MAX;
  49076. this.min.y = CMGBoundinBox.MAX;
  49077. this.min.z = CMGBoundinBox.MAX;
  49078. this.max.x = CMGBoundinBox.MIN;
  49079. this.max.y = CMGBoundinBox.MIN;
  49080. this.max.z = CMGBoundinBox.MIN;
  49081. };
  49082. CMGBoundinBox.prototype.augment = function (x, y, z) {
  49083. this.min.x = Math.min(this.min.x, x);
  49084. this.min.y = Math.min(this.min.y, y);
  49085. this.min.z = Math.min(this.min.z, z);
  49086. this.max.x = Math.max(this.max.x, x);
  49087. this.max.y = Math.max(this.max.y, y);
  49088. this.max.z = Math.max(this.max.z, z);
  49089. };
  49090. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  49091. this.min.x = Math.max(this.min.x, x);
  49092. this.min.y = Math.max(this.min.y, y);
  49093. this.min.z = Math.max(this.min.z, z);
  49094. };
  49095. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  49096. this.max.x = Math.min(this.max.x, x);
  49097. this.max.y = Math.min(this.max.y, y);
  49098. this.max.z = Math.min(this.max.z, z);
  49099. };
  49100. CMGBoundinBox.prototype.empty = function () {
  49101. if ((this.min.x > this.max.y) ||
  49102. (this.min.y > this.max.y) ||
  49103. (this.min.z > this.max.y)) {
  49104. return true;
  49105. }
  49106. else {
  49107. return false;
  49108. }
  49109. };
  49110. CMGBoundinBox.MAX = Number.MAX_VALUE;
  49111. CMGBoundinBox.MIN = Number.MIN_VALUE;
  49112. return CMGBoundinBox;
  49113. }());
  49114. /**
  49115. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  49116. * required by the glossinees of a material.
  49117. *
  49118. * This only supports the cosine drop power as well as Warp fixup generation method.
  49119. *
  49120. * This is using the process from CubeMapGen described here:
  49121. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  49122. */
  49123. var PMREMGenerator = (function () {
  49124. /**
  49125. * Constructor of the generator.
  49126. *
  49127. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  49128. * @param inputSize The size of the cubemap faces
  49129. * @param outputSize The size of the output cubemap faces
  49130. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  49131. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  49132. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  49133. * @param specularPower The max specular level of the desired cubemap
  49134. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  49135. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  49136. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  49137. */
  49138. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  49139. this.input = input;
  49140. this.inputSize = inputSize;
  49141. this.outputSize = outputSize;
  49142. this.maxNumMipLevels = maxNumMipLevels;
  49143. this.numChannels = numChannels;
  49144. this.isFloat = isFloat;
  49145. this.specularPower = specularPower;
  49146. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  49147. this.excludeBase = excludeBase;
  49148. this.fixup = fixup;
  49149. this._outputSurface = [];
  49150. this._numMipLevels = 0;
  49151. }
  49152. /**
  49153. * Launches the filter process and return the result.
  49154. *
  49155. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  49156. */
  49157. PMREMGenerator.prototype.filterCubeMap = function () {
  49158. // Init cubemap processor
  49159. this.init();
  49160. // Filters the cubemap
  49161. this.filterCubeMapMipChain();
  49162. // Returns the filtered mips.
  49163. return this._outputSurface;
  49164. };
  49165. PMREMGenerator.prototype.init = function () {
  49166. var i;
  49167. var j;
  49168. var mipLevelSize;
  49169. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  49170. if (this.maxNumMipLevels == 0) {
  49171. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  49172. }
  49173. //first miplevel size
  49174. mipLevelSize = this.outputSize;
  49175. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  49176. for (j = 0; j < this.maxNumMipLevels; j++) {
  49177. this._outputSurface.length++;
  49178. this._outputSurface[j] = [];
  49179. //Iterate over faces for output images
  49180. for (i = 0; i < 6; i++) {
  49181. this._outputSurface[j].length++;
  49182. // Initializes a new array for the output.
  49183. if (this.isFloat) {
  49184. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  49185. }
  49186. else {
  49187. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  49188. }
  49189. }
  49190. //next mip level is half size
  49191. mipLevelSize >>= 1;
  49192. this._numMipLevels++;
  49193. //terminate if mip chain becomes too small
  49194. if (mipLevelSize == 0) {
  49195. this.maxNumMipLevels = j;
  49196. return;
  49197. }
  49198. }
  49199. };
  49200. //--------------------------------------------------------------------------------------
  49201. //Cube map filtering and mip chain generation.
  49202. // the cube map filtereing is specified using a number of parameters:
  49203. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  49204. // indicates the region of the hemisphere to filter over for each tap.
  49205. //
  49206. // Note that the top mip level is also a filtered version of the original input images
  49207. // as well in order to create mip chains for diffuse environment illumination.
  49208. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  49209. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  49210. //
  49211. // Then the mip angle used to genreate the next level of the mip chain from the first level
  49212. // is a_InitialMipAngle
  49213. //
  49214. // The angle for the subsequent levels of the mip chain are specified by their parents
  49215. // filtering angle and a per-level scale and bias
  49216. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  49217. //
  49218. //--------------------------------------------------------------------------------------
  49219. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  49220. // First, take count of the lighting model to modify SpecularPower
  49221. // 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;
  49222. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  49223. //Cone angle start (for generating subsequent mip levels)
  49224. var currentSpecularPower = this.specularPower;
  49225. //Build filter lookup tables based on the source miplevel size
  49226. this.precomputeFilterLookupTables(this.inputSize);
  49227. // Note that we need to filter the first level before generating mipmap
  49228. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  49229. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  49230. // TODO : Write a function to copy and scale the base mipmap in output
  49231. // I am just lazy here and just put a high specular power value, and do some if.
  49232. if (this.excludeBase && (levelIndex == 0)) {
  49233. // 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).
  49234. currentSpecularPower = 100000.0;
  49235. }
  49236. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  49237. var srcCubeImage = this.input;
  49238. var dstCubeImage = this._outputSurface[levelIndex];
  49239. var dstSize = this.outputSize >> levelIndex;
  49240. // Compute required angle.
  49241. var angle = this.getBaseFilterAngle(currentSpecularPower);
  49242. // filter cube surfaces
  49243. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  49244. // fix seams
  49245. if (this.fixup) {
  49246. this.fixupCubeEdges(dstCubeImage, dstSize);
  49247. }
  49248. // Decrease the specular power to generate the mipmap chain
  49249. // TODO : Use another method for Exclude (see first comment at start of the function
  49250. if (this.excludeBase && (levelIndex == 0)) {
  49251. currentSpecularPower = this.specularPower;
  49252. }
  49253. currentSpecularPower *= this.cosinePowerDropPerMip;
  49254. }
  49255. };
  49256. //--------------------------------------------------------------------------------------
  49257. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  49258. // It allow to optimize the texel to access base on the specular power.
  49259. //--------------------------------------------------------------------------------------
  49260. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  49261. // We want to find the alpha such that:
  49262. // cos(alpha)^cosinePower = epsilon
  49263. // That's: acos(epsilon^(1/cosinePower))
  49264. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  49265. var angle = 180.0;
  49266. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  49267. angle *= 180.0 / Math.PI; // Convert to degree
  49268. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  49269. return angle;
  49270. };
  49271. //--------------------------------------------------------------------------------------
  49272. //Builds the following lookup tables prior to filtering:
  49273. // -normalizer cube map
  49274. // -tap weight lookup table
  49275. //
  49276. //--------------------------------------------------------------------------------------
  49277. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  49278. var srcTexelAngle;
  49279. var iCubeFace;
  49280. //clear pre-existing normalizer cube map
  49281. this._normCubeMap = [];
  49282. //Normalized vectors per cubeface and per-texel solid angle
  49283. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  49284. };
  49285. //--------------------------------------------------------------------------------------
  49286. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  49287. //
  49288. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  49289. //
  49290. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  49291. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  49292. // below
  49293. //--------------------------------------------------------------------------------------
  49294. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  49295. var iCubeFace;
  49296. var u;
  49297. var v;
  49298. //iterate over cube faces
  49299. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49300. //First three channels for norm cube, and last channel for solid angle
  49301. this._normCubeMap.push(new Float32Array(size * size * 4));
  49302. //fast texture walk, build normalizer cube map
  49303. var facesData = this.input[iCubeFace];
  49304. for (v = 0; v < size; v++) {
  49305. for (u = 0; u < size; u++) {
  49306. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  49307. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  49308. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  49309. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  49310. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  49311. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  49312. }
  49313. }
  49314. }
  49315. };
  49316. //--------------------------------------------------------------------------------------
  49317. // Convert cubemap face texel coordinates and face idx to 3D vector
  49318. // note the U and V coords are integer coords and range from 0 to size-1
  49319. // this routine can be used to generate a normalizer cube map
  49320. //--------------------------------------------------------------------------------------
  49321. // SL BEGIN
  49322. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  49323. var nvcU;
  49324. var nvcV;
  49325. var tempVec;
  49326. // Change from original AMD code
  49327. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  49328. // + 0.5f is for texel center addressing
  49329. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  49330. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  49331. // warp fixup
  49332. if (fixup && size > 1) {
  49333. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  49334. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  49335. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  49336. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  49337. }
  49338. // Get current vector
  49339. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  49340. // U contribution
  49341. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  49342. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  49343. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  49344. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  49345. // V contribution and Sum
  49346. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  49347. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  49348. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  49349. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  49350. //add face axis
  49351. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  49352. PMREMGenerator._vectorTemp.x += faceAxis[0];
  49353. PMREMGenerator._vectorTemp.y += faceAxis[1];
  49354. PMREMGenerator._vectorTemp.z += faceAxis[2];
  49355. //normalize vector
  49356. PMREMGenerator._vectorTemp.normalize();
  49357. return PMREMGenerator._vectorTemp;
  49358. };
  49359. //--------------------------------------------------------------------------------------
  49360. // Convert 3D vector to cubemap face texel coordinates and face idx
  49361. // note the U and V coords are integer coords and range from 0 to size-1
  49362. // this routine can be used to generate a normalizer cube map
  49363. //
  49364. // returns face IDX and texel coords
  49365. //--------------------------------------------------------------------------------------
  49366. // SL BEGIN
  49367. /*
  49368. Mapping Texture Coordinates to Cube Map Faces
  49369. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  49370. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  49371. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  49372. map arrangement in Pixar's RenderMan package.
  49373. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  49374. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  49375. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  49376. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  49377. the major axis direction). The target column in the table below explains how the major axis direction
  49378. maps to the 2D image of a particular cube map target.
  49379. major axis
  49380. direction target sc tc ma
  49381. ---------- --------------------------------- --- --- ---
  49382. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  49383. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  49384. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  49385. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  49386. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  49387. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  49388. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  49389. an updated (s,t) is calculated as follows
  49390. s = ( sc/|ma| + 1 ) / 2
  49391. t = ( tc/|ma| + 1 ) / 2
  49392. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  49393. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  49394. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  49395. */
  49396. // Note this method return U and V in range from 0 to size-1
  49397. // SL END
  49398. // Store the information in vector3 for convenience (faceindex, u, v)
  49399. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  49400. var maxCoord;
  49401. var faceIdx;
  49402. //absolute value 3
  49403. var absX = Math.abs(x);
  49404. var absY = Math.abs(y);
  49405. var absZ = Math.abs(z);
  49406. if (absX >= absY && absX >= absZ) {
  49407. maxCoord = absX;
  49408. if (x >= 0) {
  49409. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  49410. }
  49411. else {
  49412. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  49413. }
  49414. }
  49415. else if (absY >= absX && absY >= absZ) {
  49416. maxCoord = absY;
  49417. if (y >= 0) {
  49418. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  49419. }
  49420. else {
  49421. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  49422. }
  49423. }
  49424. else {
  49425. maxCoord = absZ;
  49426. if (z >= 0) {
  49427. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  49428. }
  49429. else {
  49430. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  49431. }
  49432. }
  49433. //divide through by max coord so face vector lies on cube face
  49434. var scale = 1 / maxCoord;
  49435. x *= scale;
  49436. y *= scale;
  49437. z *= scale;
  49438. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  49439. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  49440. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  49441. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  49442. // Modify original AMD code to return value from 0 to Size - 1
  49443. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  49444. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  49445. PMREMGenerator._vectorTemp.x = faceIdx;
  49446. PMREMGenerator._vectorTemp.y = u;
  49447. PMREMGenerator._vectorTemp.z = v;
  49448. return PMREMGenerator._vectorTemp;
  49449. };
  49450. //--------------------------------------------------------------------------------------
  49451. //Original code from Ignacio CastaÒo
  49452. // This formula is from Manne ÷hrstrˆm's thesis.
  49453. // Take two coordiantes in the range [-1, 1] that define a portion of a
  49454. // cube face and return the area of the projection of that portion on the
  49455. // surface of the sphere.
  49456. //--------------------------------------------------------------------------------------
  49457. PMREMGenerator.prototype.areaElement = function (x, y) {
  49458. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  49459. };
  49460. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  49461. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  49462. // (+ 0.5f is for texel center addressing)
  49463. u = (2.0 * (u + 0.5) / size) - 1.0;
  49464. v = (2.0 * (v + 0.5) / size) - 1.0;
  49465. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  49466. var invResolution = 1.0 / size;
  49467. // U and V are the -1..1 texture coordinate on the current face.
  49468. // Get projected area for this texel
  49469. var x0 = u - invResolution;
  49470. var y0 = v - invResolution;
  49471. var x1 = u + invResolution;
  49472. var y1 = v + invResolution;
  49473. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  49474. return solidAngle;
  49475. };
  49476. //--------------------------------------------------------------------------------------
  49477. //The key to the speed of these filtering routines is to quickly define a per-face
  49478. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  49479. // Later these pixels are selectively processed based on their dot products to see if
  49480. // they reside within the filtering cone.
  49481. //
  49482. //This is done by computing the smallest per-texel angle to get a conservative estimate
  49483. // of the number of texels needed to be covered in width and height order to filter the
  49484. // region. the bounding box for the center taps face is defined first, and if the
  49485. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  49486. // defined next
  49487. //--------------------------------------------------------------------------------------
  49488. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  49489. // note that pixels within these regions may be rejected
  49490. // based on the anlge
  49491. var iCubeFace;
  49492. var u;
  49493. var v;
  49494. // bounding box per face to specify region to process
  49495. var filterExtents = [];
  49496. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49497. filterExtents.push(new CMGBoundinBox());
  49498. }
  49499. // min angle a src texel can cover (in degrees)
  49500. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  49501. // angle about center tap to define filter cone
  49502. // filter angle is 1/2 the cone angle
  49503. var filterAngle = filterConeAngle / 2.0;
  49504. //ensure filter angle is larger than a texel
  49505. if (filterAngle < srcTexelAngle) {
  49506. filterAngle = srcTexelAngle;
  49507. }
  49508. //ensure filter cone is always smaller than the hemisphere
  49509. if (filterAngle > 90.0) {
  49510. filterAngle = 90.0;
  49511. }
  49512. // the maximum number of texels in 1D the filter cone angle will cover
  49513. // used to determine bounding box size for filter extents
  49514. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  49515. // ensure conservative region always covers at least one texel
  49516. if (filterSize < 1) {
  49517. filterSize = 1;
  49518. }
  49519. // dotProdThresh threshold based on cone angle to determine whether or not taps
  49520. // reside within the cone angle
  49521. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  49522. // process required faces
  49523. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49524. //iterate over dst cube map face texel
  49525. for (v = 0; v < dstSize; v++) {
  49526. for (u = 0; u < dstSize; u++) {
  49527. //get center tap direction
  49528. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  49529. //clear old per-face filter extents
  49530. this.clearFilterExtents(filterExtents);
  49531. //define per-face filter extents
  49532. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  49533. //perform filtering of src faces using filter extents
  49534. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  49535. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  49536. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  49537. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  49538. }
  49539. }
  49540. }
  49541. };
  49542. //--------------------------------------------------------------------------------------
  49543. //Clear filter extents for the 6 cube map faces
  49544. //--------------------------------------------------------------------------------------
  49545. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  49546. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  49547. filterExtents[iCubeFaces].clear();
  49548. }
  49549. };
  49550. //--------------------------------------------------------------------------------------
  49551. //Define per-face bounding box filter extents
  49552. //
  49553. // These define conservative texel regions in each of the faces the filter can possibly
  49554. // process. When the pixels in the regions are actually processed, the dot product
  49555. // between the tap vector and the center tap vector is used to determine the weight of
  49556. // the tap and whether or not the tap is within the cone.
  49557. //
  49558. //--------------------------------------------------------------------------------------
  49559. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  49560. //neighboring face and bleed over amount, and width of BBOX for
  49561. // left, right, top, and bottom edges of this face
  49562. var bleedOverAmount = [0, 0, 0, 0];
  49563. var bleedOverBBoxMin = [0, 0, 0, 0];
  49564. var bleedOverBBoxMax = [0, 0, 0, 0];
  49565. var neighborFace;
  49566. var neighborEdge;
  49567. var oppositeFaceIdx;
  49568. //get face idx, and u, v info from center tap dir
  49569. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  49570. var faceIdx = result.x;
  49571. var u = result.y;
  49572. var v = result.z;
  49573. //define bbox size within face
  49574. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  49575. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  49576. filterExtents[faceIdx].clampMin(0, 0, 0);
  49577. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  49578. //u and v extent in face corresponding to center tap
  49579. var minU = filterExtents[faceIdx].min.x;
  49580. var minV = filterExtents[faceIdx].min.y;
  49581. var maxU = filterExtents[faceIdx].max.x;
  49582. var maxV = filterExtents[faceIdx].max.y;
  49583. //bleed over amounts for face across u=0 edge (left)
  49584. bleedOverAmount[0] = (bboxSize - u);
  49585. bleedOverBBoxMin[0] = minV;
  49586. bleedOverBBoxMax[0] = maxV;
  49587. //bleed over amounts for face across u=1 edge (right)
  49588. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  49589. bleedOverBBoxMin[1] = minV;
  49590. bleedOverBBoxMax[1] = maxV;
  49591. //bleed over to face across v=0 edge (up)
  49592. bleedOverAmount[2] = (bboxSize - v);
  49593. bleedOverBBoxMin[2] = minU;
  49594. bleedOverBBoxMax[2] = maxU;
  49595. //bleed over to face across v=1 edge (down)
  49596. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  49597. bleedOverBBoxMin[3] = minU;
  49598. bleedOverBBoxMax[3] = maxU;
  49599. //compute bleed over regions in neighboring faces
  49600. for (var i = 0; i < 4; i++) {
  49601. if (bleedOverAmount[i] > 0) {
  49602. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  49603. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  49604. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  49605. // be flipped: the cases are
  49606. // if a left edge mates with a left or bottom edge on the neighbor
  49607. // if a top edge mates with a top or right edge on the neighbor
  49608. // if a right edge mates with a right or top edge on the neighbor
  49609. // if a bottom edge mates with a bottom or left edge on the neighbor
  49610. //Seeing as the edges are enumerated as follows
  49611. // left =0
  49612. // right =1
  49613. // top =2
  49614. // bottom =3
  49615. //
  49616. // so if the edge enums are the same, or the sum of the enums == 3,
  49617. // the bbox needs to be flipped
  49618. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  49619. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  49620. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  49621. }
  49622. //The way the bounding box is extended onto the neighboring face
  49623. // depends on which edge of neighboring face abuts with this one
  49624. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  49625. case PMREMGenerator.CP_EDGE_LEFT:
  49626. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  49627. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49628. break;
  49629. case PMREMGenerator.CP_EDGE_RIGHT:
  49630. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  49631. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49632. break;
  49633. case PMREMGenerator.CP_EDGE_TOP:
  49634. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  49635. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  49636. break;
  49637. case PMREMGenerator.CP_EDGE_BOTTOM:
  49638. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  49639. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  49640. break;
  49641. }
  49642. //clamp filter extents in non-center tap faces to remain within surface
  49643. filterExtents[neighborFace].clampMin(0, 0, 0);
  49644. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  49645. }
  49646. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  49647. // from the center tap face, then process the opposite face entirely for now.
  49648. //Note that the cases in which this happens, what usually happens is that
  49649. // more than one edge bleeds onto the opposite face, and the bounding box
  49650. // encompasses the entire cube map face.
  49651. if (bleedOverAmount[i] > srcSize) {
  49652. //determine opposite face
  49653. switch (faceIdx) {
  49654. case PMREMGenerator.CP_FACE_X_POS:
  49655. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  49656. break;
  49657. case PMREMGenerator.CP_FACE_X_NEG:
  49658. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  49659. break;
  49660. case PMREMGenerator.CP_FACE_Y_POS:
  49661. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  49662. break;
  49663. case PMREMGenerator.CP_FACE_Y_NEG:
  49664. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  49665. break;
  49666. case PMREMGenerator.CP_FACE_Z_POS:
  49667. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  49668. break;
  49669. case PMREMGenerator.CP_FACE_Z_NEG:
  49670. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  49671. break;
  49672. default:
  49673. break;
  49674. }
  49675. //just encompass entire face for now
  49676. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  49677. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  49678. }
  49679. }
  49680. };
  49681. //--------------------------------------------------------------------------------------
  49682. //ProcessFilterExtents
  49683. // Process bounding box in each cube face
  49684. //
  49685. //--------------------------------------------------------------------------------------
  49686. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  49687. //accumulators are 64-bit floats in order to have the precision needed
  49688. // over a summation of a large number of pixels
  49689. var dstAccum = [0, 0, 0, 0];
  49690. var weightAccum = 0;
  49691. var k = 0;
  49692. var nSrcChannels = this.numChannels;
  49693. // norm cube map and srcCubeMap have same face width
  49694. var faceWidth = srcSize;
  49695. //amount to add to pointer to move to next scanline in images
  49696. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  49697. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  49698. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  49699. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  49700. // iterate over cubefaces
  49701. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  49702. //if bbox is non empty
  49703. if (!filterExtents[iFaceIdx].empty()) {
  49704. var uStart = filterExtents[iFaceIdx].min.x;
  49705. var vStart = filterExtents[iFaceIdx].min.y;
  49706. var uEnd = filterExtents[iFaceIdx].max.x;
  49707. var vEnd = filterExtents[iFaceIdx].max.y;
  49708. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  49709. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  49710. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  49711. for (var v = vStart; v <= vEnd; v++) {
  49712. var normCubeRowWalk = 0;
  49713. var srcCubeRowWalk = 0;
  49714. for (var u = uStart; u <= uEnd; u++) {
  49715. //pointer to direction in cube map associated with texel
  49716. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  49717. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  49718. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  49719. //check dot product to see if texel is within cone
  49720. var tapDotProd = texelVectX * centerTapDir.x +
  49721. texelVectY * centerTapDir.y +
  49722. texelVectZ * centerTapDir.z;
  49723. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  49724. //solid angle stored in 4th channel of normalizer/solid angle cube map
  49725. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  49726. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  49727. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  49728. // so just adding one to specularpower do the trick.
  49729. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  49730. //iterate over channels
  49731. for (k = 0; k < nSrcChannels; k++) {
  49732. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  49733. srcCubeRowWalk++;
  49734. }
  49735. weightAccum += weight; //accumulate weight
  49736. }
  49737. else {
  49738. //step across source pixel
  49739. srcCubeRowWalk += nSrcChannels;
  49740. }
  49741. normCubeRowWalk += 4; // 4 channels per norm cube map.
  49742. }
  49743. startIndexNormCubeMap += normCubePitch;
  49744. startIndexSrcCubeMap += srcCubePitch;
  49745. }
  49746. }
  49747. }
  49748. //divide through by weights if weight is non zero
  49749. if (weightAccum != 0.0) {
  49750. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  49751. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  49752. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  49753. if (this.numChannels > 3) {
  49754. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  49755. }
  49756. }
  49757. else {
  49758. // otherwise sample nearest
  49759. // get face idx and u, v texel coordinate in face
  49760. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  49761. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  49762. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  49763. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  49764. if (this.numChannels > 3) {
  49765. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  49766. }
  49767. }
  49768. return PMREMGenerator._vectorTemp;
  49769. };
  49770. //--------------------------------------------------------------------------------------
  49771. // Fixup cube edges
  49772. //
  49773. // average texels on cube map faces across the edges
  49774. // WARP/BENT Method Only.
  49775. //--------------------------------------------------------------------------------------
  49776. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  49777. var k;
  49778. var j;
  49779. var i;
  49780. var iFace;
  49781. var iCorner = 0;
  49782. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  49783. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  49784. // note that if functionality to filter across the three texels for each corner, then
  49785. //indexed by corner and face idx. the array contains the face the start points belongs to.
  49786. var cornerPtr = [
  49787. [[], [], []],
  49788. [[], [], []],
  49789. [[], [], []],
  49790. [[], [], []],
  49791. [[], [], []],
  49792. [[], [], []],
  49793. [[], [], []],
  49794. [[], [], []]
  49795. ];
  49796. //if there is no fixup, or fixup width = 0, do nothing
  49797. if (cubeMapSize < 1) {
  49798. return;
  49799. }
  49800. //special case 1x1 cubemap, average face colors
  49801. if (cubeMapSize == 1) {
  49802. //iterate over channels
  49803. for (k = 0; k < this.numChannels; k++) {
  49804. var accum = 0.0;
  49805. //iterate over faces to accumulate face colors
  49806. for (iFace = 0; iFace < 6; iFace++) {
  49807. accum += cubeMap[iFace][k];
  49808. }
  49809. //compute average over 6 face colors
  49810. accum /= 6.0;
  49811. //iterate over faces to distribute face colors
  49812. for (iFace = 0; iFace < 6; iFace++) {
  49813. cubeMap[iFace][k] = accum;
  49814. }
  49815. }
  49816. return;
  49817. }
  49818. //iterate over faces to collect list of corner texel pointers
  49819. for (iFace = 0; iFace < 6; iFace++) {
  49820. //the 4 corner pointers for this face
  49821. faceCornerStartIndicies[0] = [iFace, 0];
  49822. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  49823. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  49824. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  49825. //iterate over face corners to collect cube corner pointers
  49826. for (iCorner = 0; iCorner < 4; iCorner++) {
  49827. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  49828. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  49829. cornerNumPtrs[corner]++;
  49830. }
  49831. }
  49832. //iterate over corners to average across corner tap values
  49833. for (iCorner = 0; iCorner < 8; iCorner++) {
  49834. for (k = 0; k < this.numChannels; k++) {
  49835. var cornerTapAccum = 0.0;
  49836. //iterate over corner texels and average results
  49837. for (i = 0; i < 3; i++) {
  49838. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  49839. }
  49840. //divide by 3 to compute average of corner tap values
  49841. cornerTapAccum *= (1.0 / 3.0);
  49842. //iterate over corner texels and average results
  49843. for (i = 0; i < 3; i++) {
  49844. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  49845. }
  49846. }
  49847. }
  49848. //iterate over the twelve edges of the cube to average across edges
  49849. for (i = 0; i < 12; i++) {
  49850. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  49851. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  49852. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  49853. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  49854. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  49855. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  49856. var edgeWalk = 0;
  49857. var neighborEdgeWalk = 0;
  49858. //Determine walking pointers based on edge type
  49859. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  49860. switch (edge) {
  49861. case PMREMGenerator.CP_EDGE_LEFT:
  49862. // no change to faceEdgeStartPtr
  49863. edgeWalk = this.numChannels * cubeMapSize;
  49864. break;
  49865. case PMREMGenerator.CP_EDGE_RIGHT:
  49866. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49867. edgeWalk = this.numChannels * cubeMapSize;
  49868. break;
  49869. case PMREMGenerator.CP_EDGE_TOP:
  49870. // no change to faceEdgeStartPtr
  49871. edgeWalk = this.numChannels;
  49872. break;
  49873. case PMREMGenerator.CP_EDGE_BOTTOM:
  49874. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49875. edgeWalk = this.numChannels;
  49876. break;
  49877. }
  49878. //For certain types of edge abutments, the neighbor edge walk needs to
  49879. // be flipped: the cases are
  49880. // if a left edge mates with a left or bottom edge on the neighbor
  49881. // if a top edge mates with a top or right edge on the neighbor
  49882. // if a right edge mates with a right or top edge on the neighbor
  49883. // if a bottom edge mates with a bottom or left edge on the neighbor
  49884. //Seeing as the edges are enumerated as follows
  49885. // left =0
  49886. // right =1
  49887. // top =2
  49888. // bottom =3
  49889. //
  49890. //If the edge enums are the same, or the sum of the enums == 3,
  49891. // the neighbor edge walk needs to be flipped
  49892. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  49893. switch (neighborEdge) {
  49894. case PMREMGenerator.CP_EDGE_LEFT:
  49895. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  49896. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49897. break;
  49898. case PMREMGenerator.CP_EDGE_RIGHT:
  49899. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49900. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49901. break;
  49902. case PMREMGenerator.CP_EDGE_TOP:
  49903. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49904. neighborEdgeWalk = -this.numChannels;
  49905. break;
  49906. case PMREMGenerator.CP_EDGE_BOTTOM:
  49907. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49908. neighborEdgeWalk = -this.numChannels;
  49909. break;
  49910. }
  49911. }
  49912. else {
  49913. //swapped direction neighbor edge walk
  49914. switch (neighborEdge) {
  49915. case PMREMGenerator.CP_EDGE_LEFT:
  49916. //no change to neighborEdgeStartPtr for this case since it points
  49917. // to the upper left corner already
  49918. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49919. break;
  49920. case PMREMGenerator.CP_EDGE_RIGHT:
  49921. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49922. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49923. break;
  49924. case PMREMGenerator.CP_EDGE_TOP:
  49925. //no change to neighborEdgeStartPtr for this case since it points
  49926. // to the upper left corner already
  49927. neighborEdgeWalk = this.numChannels;
  49928. break;
  49929. case PMREMGenerator.CP_EDGE_BOTTOM:
  49930. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49931. neighborEdgeWalk = this.numChannels;
  49932. break;
  49933. }
  49934. }
  49935. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  49936. //nearby neighborhood
  49937. //step ahead one texel on edge
  49938. edgeStartIndex += edgeWalk;
  49939. neighborEdgeStartIndex += neighborEdgeWalk;
  49940. // note that this loop does not process the corner texels, since they have already been
  49941. // averaged across faces across earlier
  49942. for (j = 1; j < (cubeMapSize - 1); j++) {
  49943. //for each set of taps along edge, average them
  49944. // and rewrite the results into the edges
  49945. for (k = 0; k < this.numChannels; k++) {
  49946. var edgeTap = cubeMap[face][edgeStartIndex + k];
  49947. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  49948. //compute average of tap intensity values
  49949. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  49950. //propagate average of taps to edge taps
  49951. cubeMap[face][edgeStartIndex + k] = avgTap;
  49952. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  49953. }
  49954. edgeStartIndex += edgeWalk;
  49955. neighborEdgeStartIndex += neighborEdgeWalk;
  49956. }
  49957. }
  49958. };
  49959. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  49960. PMREMGenerator.CP_UDIR = 0;
  49961. PMREMGenerator.CP_VDIR = 1;
  49962. PMREMGenerator.CP_FACEAXIS = 2;
  49963. //used to index cube faces
  49964. PMREMGenerator.CP_FACE_X_POS = 0;
  49965. PMREMGenerator.CP_FACE_X_NEG = 1;
  49966. PMREMGenerator.CP_FACE_Y_POS = 2;
  49967. PMREMGenerator.CP_FACE_Y_NEG = 3;
  49968. PMREMGenerator.CP_FACE_Z_POS = 4;
  49969. PMREMGenerator.CP_FACE_Z_NEG = 5;
  49970. //used to index image edges
  49971. // NOTE.. the actual number corresponding to the edge is important
  49972. // do not change these, or the code will break
  49973. //
  49974. // CP_EDGE_LEFT is u = 0
  49975. // CP_EDGE_RIGHT is u = width-1
  49976. // CP_EDGE_TOP is v = 0
  49977. // CP_EDGE_BOTTOM is v = height-1
  49978. PMREMGenerator.CP_EDGE_LEFT = 0;
  49979. PMREMGenerator.CP_EDGE_RIGHT = 1;
  49980. PMREMGenerator.CP_EDGE_TOP = 2;
  49981. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  49982. //corners of CUBE map (P or N specifys if it corresponds to the
  49983. // positive or negative direction each of X, Y, and Z
  49984. PMREMGenerator.CP_CORNER_NNN = 0;
  49985. PMREMGenerator.CP_CORNER_NNP = 1;
  49986. PMREMGenerator.CP_CORNER_NPN = 2;
  49987. PMREMGenerator.CP_CORNER_NPP = 3;
  49988. PMREMGenerator.CP_CORNER_PNN = 4;
  49989. PMREMGenerator.CP_CORNER_PNP = 5;
  49990. PMREMGenerator.CP_CORNER_PPN = 6;
  49991. PMREMGenerator.CP_CORNER_PPP = 7;
  49992. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  49993. //3x2 matrices that map cube map indexing vectors in 3d
  49994. // (after face selection and divide through by the
  49995. // _ABSOLUTE VALUE_ of the max coord)
  49996. // into NVC space
  49997. //Note this currently assumes the D3D cube face ordering and orientation
  49998. PMREMGenerator._sgFace2DMapping = [
  49999. //XPOS face
  50000. [[0, 0, -1],
  50001. [0, -1, 0],
  50002. [1, 0, 0]],
  50003. //XNEG face
  50004. [[0, 0, 1],
  50005. [0, -1, 0],
  50006. [-1, 0, 0]],
  50007. //YPOS face
  50008. [[1, 0, 0],
  50009. [0, 0, 1],
  50010. [0, 1, 0]],
  50011. //YNEG face
  50012. [[1, 0, 0],
  50013. [0, 0, -1],
  50014. [0, -1, 0]],
  50015. //ZPOS face
  50016. [[1, 0, 0],
  50017. [0, -1, 0],
  50018. [0, 0, 1]],
  50019. //ZNEG face
  50020. [[-1, 0, 0],
  50021. [0, -1, 0],
  50022. [0, 0, -1]],
  50023. ];
  50024. //------------------------------------------------------------------------------
  50025. // D3D cube map face specification
  50026. // mapping from 3D x,y,z cube map lookup coordinates
  50027. // to 2D within face u,v coordinates
  50028. //
  50029. // --------------------> U direction
  50030. // | (within-face texture space)
  50031. // | _____
  50032. // | | |
  50033. // | | +Y |
  50034. // | _____|_____|_____ _____
  50035. // | | | | | |
  50036. // | | -X | +Z | +X | -Z |
  50037. // | |_____|_____|_____|_____|
  50038. // | | |
  50039. // | | -Y |
  50040. // | |_____|
  50041. // |
  50042. // v V direction
  50043. // (within-face texture space)
  50044. //------------------------------------------------------------------------------
  50045. //Information about neighbors and how texture coorrdinates change across faces
  50046. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  50047. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  50048. //Note this currently assumes the D3D cube face ordering and orientation
  50049. PMREMGenerator._sgCubeNgh = [
  50050. //XPOS face
  50051. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50052. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  50053. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50054. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  50055. //XNEG face
  50056. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  50057. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  50058. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  50059. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  50060. //YPOS face
  50061. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  50062. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  50063. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  50064. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  50065. //YNEG face
  50066. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  50067. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50068. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50069. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  50070. //ZPOS face
  50071. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  50072. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  50073. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50074. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  50075. //ZNEG face
  50076. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50077. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  50078. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  50079. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  50080. ];
  50081. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  50082. // this table is used to average over the edges.
  50083. PMREMGenerator._sgCubeEdgeList = [
  50084. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  50085. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50086. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  50087. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50088. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  50089. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  50090. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  50091. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  50092. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  50093. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50094. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  50095. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  50096. ];
  50097. //Information about which of the 8 cube corners are correspond to the
  50098. // the 4 corners in each cube face
  50099. // the order is upper left, upper right, lower left, lower right
  50100. PMREMGenerator._sgCubeCornerList = [
  50101. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  50102. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  50103. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  50104. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  50105. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  50106. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  50107. ];
  50108. return PMREMGenerator;
  50109. }());
  50110. Internals.PMREMGenerator = PMREMGenerator;
  50111. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50112. })(BABYLON || (BABYLON = {}));
  50113. var BABYLON;
  50114. (function (BABYLON) {
  50115. /**
  50116. * This represents a texture coming from an HDR input.
  50117. *
  50118. * The only supported format is currently panorama picture stored in RGBE format.
  50119. * Example of such files can be found on HDRLib: http://hdrlib.com/
  50120. */
  50121. var HDRCubeTexture = (function (_super) {
  50122. __extends(HDRCubeTexture, _super);
  50123. /**
  50124. * Instantiates an HDRTexture from the following parameters.
  50125. *
  50126. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  50127. * @param scene The scene the texture will be used in
  50128. * @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.
  50129. * @param noMipmap Forces to not generate the mipmap if true
  50130. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  50131. * @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)
  50132. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  50133. */
  50134. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  50135. if (noMipmap === void 0) { noMipmap = false; }
  50136. if (generateHarmonics === void 0) { generateHarmonics = true; }
  50137. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  50138. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  50139. _super.call(this, scene);
  50140. this._useInGammaSpace = false;
  50141. this._generateHarmonics = true;
  50142. this._isBABYLONPreprocessed = false;
  50143. /**
  50144. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  50145. */
  50146. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  50147. /**
  50148. * The spherical polynomial data extracted from the texture.
  50149. */
  50150. this.sphericalPolynomial = null;
  50151. /**
  50152. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  50153. * This is usefull at run time to apply the good shader.
  50154. */
  50155. this.isPMREM = false;
  50156. if (!url) {
  50157. return;
  50158. }
  50159. this.name = url;
  50160. this.url = url;
  50161. this.hasAlpha = false;
  50162. this.isCube = true;
  50163. this._textureMatrix = BABYLON.Matrix.Identity();
  50164. if (size) {
  50165. this._isBABYLONPreprocessed = false;
  50166. this._noMipmap = noMipmap;
  50167. this._size = size;
  50168. this._useInGammaSpace = useInGammaSpace;
  50169. this._usePMREMGenerator = usePMREMGenerator &&
  50170. scene.getEngine().getCaps().textureLOD &&
  50171. this.getScene().getEngine().getCaps().textureFloat &&
  50172. !this._useInGammaSpace;
  50173. }
  50174. else {
  50175. this._isBABYLONPreprocessed = true;
  50176. this._noMipmap = false;
  50177. this._useInGammaSpace = false;
  50178. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  50179. this.getScene().getEngine().getCaps().textureFloat &&
  50180. !this._useInGammaSpace;
  50181. }
  50182. this.isPMREM = this._usePMREMGenerator;
  50183. this._texture = this._getFromCache(url, this._noMipmap);
  50184. if (!this._texture) {
  50185. if (!scene.useDelayedTextureLoading) {
  50186. this.loadTexture();
  50187. }
  50188. else {
  50189. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50190. }
  50191. }
  50192. }
  50193. /**
  50194. * Occurs when the file is a preprocessed .babylon.hdr file.
  50195. */
  50196. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  50197. var _this = this;
  50198. var mipLevels = 0;
  50199. var floatArrayView = null;
  50200. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  50201. var mips = [];
  50202. var startIndex = 30;
  50203. for (var level = 0; level < mipLevels; level++) {
  50204. mips.push([]);
  50205. // Fill each pixel of the mip level.
  50206. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  50207. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50208. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  50209. mips[level].push(faceData);
  50210. startIndex += faceSize;
  50211. }
  50212. }
  50213. return mips;
  50214. } : null;
  50215. var callback = function (buffer) {
  50216. // Create Native Array Views
  50217. var intArrayView = new Int32Array(buffer);
  50218. floatArrayView = new Float32Array(buffer);
  50219. // Fill header.
  50220. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  50221. _this._size = intArrayView[1]; // CubeMap max mip face size.
  50222. // Update Texture Information.
  50223. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  50224. // Fill polynomial information.
  50225. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  50226. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  50227. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  50228. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  50229. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  50230. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  50231. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  50232. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  50233. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  50234. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  50235. // Fill pixel data.
  50236. mipLevels = intArrayView[29]; // Number of mip levels.
  50237. var startIndex = 30;
  50238. var data = [];
  50239. var faceSize = Math.pow(_this._size, 2) * 3;
  50240. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50241. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  50242. startIndex += faceSize;
  50243. }
  50244. var results = [];
  50245. var byteArray = null;
  50246. // Push each faces.
  50247. for (var k = 0; k < 6; k++) {
  50248. var dataFace = null;
  50249. // If special cases.
  50250. if (!mipmapGenerator) {
  50251. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  50252. dataFace = data[j];
  50253. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  50254. // 3 channels of 1 bytes per pixel in bytes.
  50255. var byteBuffer = new ArrayBuffer(faceSize);
  50256. byteArray = new Uint8Array(byteBuffer);
  50257. }
  50258. for (var i = 0; i < _this._size * _this._size; i++) {
  50259. // Put in gamma space if requested.
  50260. if (_this._useInGammaSpace) {
  50261. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  50262. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  50263. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  50264. }
  50265. // Convert to int texture for fallback.
  50266. if (byteArray) {
  50267. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  50268. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  50269. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  50270. // May use luminance instead if the result is not accurate.
  50271. var max = Math.max(Math.max(r, g), b);
  50272. if (max > 255) {
  50273. var scale = 255 / max;
  50274. r *= scale;
  50275. g *= scale;
  50276. b *= scale;
  50277. }
  50278. byteArray[(i * 3) + 0] = r;
  50279. byteArray[(i * 3) + 1] = g;
  50280. byteArray[(i * 3) + 2] = b;
  50281. }
  50282. }
  50283. }
  50284. else {
  50285. dataFace = data[k];
  50286. }
  50287. // Fill the array accordingly.
  50288. if (byteArray) {
  50289. results.push(byteArray);
  50290. }
  50291. else {
  50292. results.push(dataFace);
  50293. }
  50294. }
  50295. return results;
  50296. };
  50297. 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);
  50298. };
  50299. /**
  50300. * Occurs when the file is raw .hdr file.
  50301. */
  50302. HDRCubeTexture.prototype.loadHDRTexture = function () {
  50303. var _this = this;
  50304. var callback = function (buffer) {
  50305. // Extract the raw linear data.
  50306. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  50307. // Generate harmonics if needed.
  50308. if (_this._generateHarmonics) {
  50309. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  50310. }
  50311. var results = [];
  50312. var byteArray = null;
  50313. // Push each faces.
  50314. for (var j = 0; j < 6; j++) {
  50315. // Create uintarray fallback.
  50316. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  50317. // 3 channels of 1 bytes per pixel in bytes.
  50318. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  50319. byteArray = new Uint8Array(byteBuffer);
  50320. }
  50321. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  50322. // If special cases.
  50323. if (_this._useInGammaSpace || byteArray) {
  50324. for (var i = 0; i < _this._size * _this._size; i++) {
  50325. // Put in gamma space if requested.
  50326. if (_this._useInGammaSpace) {
  50327. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  50328. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  50329. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  50330. }
  50331. // Convert to int texture for fallback.
  50332. if (byteArray) {
  50333. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  50334. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  50335. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  50336. // May use luminance instead if the result is not accurate.
  50337. var max = Math.max(Math.max(r, g), b);
  50338. if (max > 255) {
  50339. var scale = 255 / max;
  50340. r *= scale;
  50341. g *= scale;
  50342. b *= scale;
  50343. }
  50344. byteArray[(i * 3) + 0] = r;
  50345. byteArray[(i * 3) + 1] = g;
  50346. byteArray[(i * 3) + 2] = b;
  50347. }
  50348. }
  50349. }
  50350. if (byteArray) {
  50351. results.push(byteArray);
  50352. }
  50353. else {
  50354. results.push(dataFace);
  50355. }
  50356. }
  50357. return results;
  50358. };
  50359. var mipmapGenerator = null;
  50360. if (!this._noMipmap &&
  50361. this._usePMREMGenerator) {
  50362. mipmapGenerator = function (data) {
  50363. // Custom setup of the generator matching with the PBR shader values.
  50364. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  50365. return generator.filterCubeMap();
  50366. };
  50367. }
  50368. 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);
  50369. };
  50370. /**
  50371. * Starts the loading process of the texture.
  50372. */
  50373. HDRCubeTexture.prototype.loadTexture = function () {
  50374. if (this._isBABYLONPreprocessed) {
  50375. this.loadBabylonTexture();
  50376. }
  50377. else {
  50378. this.loadHDRTexture();
  50379. }
  50380. };
  50381. HDRCubeTexture.prototype.clone = function () {
  50382. var size = this._isBABYLONPreprocessed ? null : this._size;
  50383. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  50384. // Base texture
  50385. newTexture.level = this.level;
  50386. newTexture.wrapU = this.wrapU;
  50387. newTexture.wrapV = this.wrapV;
  50388. newTexture.coordinatesIndex = this.coordinatesIndex;
  50389. newTexture.coordinatesMode = this.coordinatesMode;
  50390. return newTexture;
  50391. };
  50392. // Methods
  50393. HDRCubeTexture.prototype.delayLoad = function () {
  50394. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50395. return;
  50396. }
  50397. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50398. this._texture = this._getFromCache(this.url, this._noMipmap);
  50399. if (!this._texture) {
  50400. this.loadTexture();
  50401. }
  50402. };
  50403. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  50404. return this._textureMatrix;
  50405. };
  50406. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50407. var texture = null;
  50408. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  50409. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  50410. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  50411. texture.name = parsedTexture.name;
  50412. texture.hasAlpha = parsedTexture.hasAlpha;
  50413. texture.level = parsedTexture.level;
  50414. texture.coordinatesMode = parsedTexture.coordinatesMode;
  50415. }
  50416. return texture;
  50417. };
  50418. HDRCubeTexture.prototype.serialize = function () {
  50419. if (!this.name) {
  50420. return null;
  50421. }
  50422. var serializationObject = {};
  50423. serializationObject.name = this.name;
  50424. serializationObject.hasAlpha = this.hasAlpha;
  50425. serializationObject.isCube = true;
  50426. serializationObject.level = this.level;
  50427. serializationObject.size = this._size;
  50428. serializationObject.coordinatesMode = this.coordinatesMode;
  50429. serializationObject.useInGammaSpace = this._useInGammaSpace;
  50430. serializationObject.generateHarmonics = this._generateHarmonics;
  50431. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  50432. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  50433. serializationObject.customType = "BABYLON.HDRCubeTexture";
  50434. return serializationObject;
  50435. };
  50436. /**
  50437. * Saves as a file the data contained in the texture in a binary format.
  50438. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  50439. * as the spherical used in the lighting.
  50440. * @param url The HDR file url.
  50441. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  50442. * @param onError Method called if any error happens during download.
  50443. * @return The packed binary data.
  50444. */
  50445. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  50446. if (onError === void 0) { onError = null; }
  50447. var callback = function (buffer) {
  50448. var data = new Blob([buffer], { type: 'application/octet-stream' });
  50449. // Returns a URL you can use as a href.
  50450. var objUrl = window.URL.createObjectURL(data);
  50451. // Simulates a link to it and click to dowload.
  50452. var a = document.createElement("a");
  50453. document.body.appendChild(a);
  50454. a.style.display = "none";
  50455. a.href = objUrl;
  50456. a.download = "envmap.babylon.hdr";
  50457. a.click();
  50458. };
  50459. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  50460. };
  50461. /**
  50462. * Serializes the data contained in the texture in a binary format.
  50463. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  50464. * as the spherical used in the lighting.
  50465. * @param url The HDR file url.
  50466. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  50467. * @param onError Method called if any error happens during download.
  50468. * @return The packed binary data.
  50469. */
  50470. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  50471. if (onError === void 0) { onError = null; }
  50472. // Needs the url tho create the texture.
  50473. if (!url) {
  50474. return null;
  50475. }
  50476. // Check Power of two size.
  50477. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  50478. return null;
  50479. }
  50480. var getDataCallback = function (dataBuffer) {
  50481. // Extract the raw linear data.
  50482. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  50483. // Generate harmonics if needed.
  50484. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  50485. // Generate seamless faces
  50486. var mipGeneratorArray = [];
  50487. // Data are known to be in +X +Y +Z -X -Y -Z
  50488. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  50489. mipGeneratorArray.push(cubeData.right); // +X
  50490. mipGeneratorArray.push(cubeData.left); // -X
  50491. mipGeneratorArray.push(cubeData.up); // +Y
  50492. mipGeneratorArray.push(cubeData.down); // -Y
  50493. mipGeneratorArray.push(cubeData.front); // +Z
  50494. mipGeneratorArray.push(cubeData.back); // -Z
  50495. // Custom setup of the generator matching with the PBR shader values.
  50496. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  50497. var mippedData = generator.filterCubeMap();
  50498. // Compute required byte length.
  50499. var byteLength = 1 * 4; // Raw Data Version int32.
  50500. byteLength += 4; // CubeMap max mip face size int32.
  50501. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  50502. // Add data size.
  50503. byteLength += 4; // Number of mip levels int32.
  50504. for (var level = 0; level < mippedData.length; level++) {
  50505. var mipSize = size >> level;
  50506. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  50507. }
  50508. // Prepare binary structure.
  50509. var buffer = new ArrayBuffer(byteLength);
  50510. var intArrayView = new Int32Array(buffer);
  50511. var floatArrayView = new Float32Array(buffer);
  50512. // Fill header.
  50513. intArrayView[0] = 1; // Version 1.
  50514. intArrayView[1] = size; // CubeMap max mip face size.
  50515. // Fill polynomial information.
  50516. sphericalPolynomial.x.toArray(floatArrayView, 2);
  50517. sphericalPolynomial.y.toArray(floatArrayView, 5);
  50518. sphericalPolynomial.z.toArray(floatArrayView, 8);
  50519. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  50520. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  50521. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  50522. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  50523. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  50524. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  50525. // Fill pixel data.
  50526. intArrayView[29] = mippedData.length; // Number of mip levels.
  50527. var startIndex = 30;
  50528. for (var level = 0; level < mippedData.length; level++) {
  50529. // Fill each pixel of the mip level.
  50530. var faceSize = Math.pow(size >> level, 2) * 3;
  50531. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50532. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  50533. startIndex += faceSize;
  50534. }
  50535. }
  50536. // Callback.
  50537. callback(buffer);
  50538. };
  50539. // Download and process.
  50540. BABYLON.Tools.LoadFile(url, function (data) {
  50541. getDataCallback(data);
  50542. }, null, null, true, onError);
  50543. };
  50544. HDRCubeTexture._facesMapping = [
  50545. "right",
  50546. "up",
  50547. "front",
  50548. "left",
  50549. "down",
  50550. "back"
  50551. ];
  50552. return HDRCubeTexture;
  50553. }(BABYLON.BaseTexture));
  50554. BABYLON.HDRCubeTexture = HDRCubeTexture;
  50555. })(BABYLON || (BABYLON = {}));
  50556. var BABYLON;
  50557. (function (BABYLON) {
  50558. var Debug;
  50559. (function (Debug) {
  50560. /**
  50561. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  50562. */
  50563. var SkeletonViewer = (function () {
  50564. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  50565. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  50566. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  50567. this.skeleton = skeleton;
  50568. this.mesh = mesh;
  50569. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  50570. this.renderingGroupId = renderingGroupId;
  50571. this.color = BABYLON.Color3.White();
  50572. this._debugLines = [];
  50573. this._isEnabled = false;
  50574. this._scene = scene;
  50575. this.update();
  50576. this._renderFunction = this.update.bind(this);
  50577. }
  50578. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  50579. get: function () {
  50580. return this._isEnabled;
  50581. },
  50582. set: function (value) {
  50583. if (this._isEnabled === value) {
  50584. return;
  50585. }
  50586. this._isEnabled = value;
  50587. if (value) {
  50588. this._scene.registerBeforeRender(this._renderFunction);
  50589. }
  50590. else {
  50591. this._scene.unregisterBeforeRender(this._renderFunction);
  50592. }
  50593. },
  50594. enumerable: true,
  50595. configurable: true
  50596. });
  50597. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  50598. if (x === void 0) { x = 0; }
  50599. if (y === void 0) { y = 0; }
  50600. if (z === void 0) { z = 0; }
  50601. var tmat = BABYLON.Tmp.Matrix[0];
  50602. var parentBone = bone.getParent();
  50603. tmat.copyFrom(bone.getLocalMatrix());
  50604. if (x !== 0 || y !== 0 || z !== 0) {
  50605. var tmat2 = BABYLON.Tmp.Matrix[1];
  50606. BABYLON.Matrix.IdentityToRef(tmat2);
  50607. tmat2.m[12] = x;
  50608. tmat2.m[13] = y;
  50609. tmat2.m[14] = z;
  50610. tmat2.multiplyToRef(tmat, tmat);
  50611. }
  50612. if (parentBone) {
  50613. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  50614. }
  50615. tmat.multiplyToRef(meshMat, tmat);
  50616. position.x = tmat.m[12];
  50617. position.y = tmat.m[13];
  50618. position.z = tmat.m[14];
  50619. };
  50620. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  50621. var len = bones.length;
  50622. for (var i = 0; i < len; i++) {
  50623. var bone = bones[i];
  50624. var points = this._debugLines[i];
  50625. if (!points) {
  50626. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50627. this._debugLines[i] = points;
  50628. }
  50629. this._getBonePosition(points[0], bone, meshMat);
  50630. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  50631. }
  50632. };
  50633. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  50634. var len = bones.length;
  50635. var boneNum = 0;
  50636. for (var i = len - 1; i >= 0; i--) {
  50637. var childBone = bones[i];
  50638. var parentBone = childBone.getParent();
  50639. if (!parentBone) {
  50640. continue;
  50641. }
  50642. var points = this._debugLines[boneNum];
  50643. if (!points) {
  50644. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50645. this._debugLines[boneNum] = points;
  50646. }
  50647. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  50648. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  50649. boneNum++;
  50650. }
  50651. };
  50652. SkeletonViewer.prototype.update = function () {
  50653. if (this.autoUpdateBonesMatrices) {
  50654. this.skeleton.computeAbsoluteTransforms();
  50655. }
  50656. if (this.skeleton.bones[0].length === undefined) {
  50657. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50658. }
  50659. else {
  50660. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50661. }
  50662. if (!this._debugMesh) {
  50663. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  50664. this._debugMesh.renderingGroupId = this.renderingGroupId;
  50665. }
  50666. else {
  50667. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  50668. }
  50669. this._debugMesh.color = this.color;
  50670. };
  50671. SkeletonViewer.prototype.dispose = function () {
  50672. if (this._debugMesh) {
  50673. this.isEnabled = false;
  50674. this._debugMesh.dispose();
  50675. this._debugMesh = null;
  50676. }
  50677. };
  50678. return SkeletonViewer;
  50679. }());
  50680. Debug.SkeletonViewer = SkeletonViewer;
  50681. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  50682. })(BABYLON || (BABYLON = {}));
  50683. var BABYLON;
  50684. (function (BABYLON) {
  50685. /**
  50686. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  50687. * It can help converting any input color in a desired output one. This can then be used to create effects
  50688. * from sepia, black and white to sixties or futuristic rendering...
  50689. *
  50690. * The only supported format is currently 3dl.
  50691. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  50692. */
  50693. var ColorGradingTexture = (function (_super) {
  50694. __extends(ColorGradingTexture, _super);
  50695. /**
  50696. * Instantiates a ColorGradingTexture from the following parameters.
  50697. *
  50698. * @param url The location of the color gradind data (currently only supporting 3dl)
  50699. * @param scene The scene the texture will be used in
  50700. */
  50701. function ColorGradingTexture(url, scene) {
  50702. _super.call(this, scene);
  50703. if (!url) {
  50704. return;
  50705. }
  50706. this._textureMatrix = BABYLON.Matrix.Identity();
  50707. this.name = url;
  50708. this.url = url;
  50709. this.hasAlpha = false;
  50710. this.isCube = false;
  50711. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50712. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50713. this.anisotropicFilteringLevel = 1;
  50714. this._texture = this._getFromCache(url, true);
  50715. if (!this._texture) {
  50716. if (!scene.useDelayedTextureLoading) {
  50717. this.loadTexture();
  50718. }
  50719. else {
  50720. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50721. }
  50722. }
  50723. }
  50724. /**
  50725. * Returns the texture matrix used in most of the material.
  50726. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  50727. */
  50728. ColorGradingTexture.prototype.getTextureMatrix = function () {
  50729. return this._textureMatrix;
  50730. };
  50731. /**
  50732. * Occurs when the file being loaded is a .3dl LUT file.
  50733. */
  50734. ColorGradingTexture.prototype.load3dlTexture = function () {
  50735. var _this = this;
  50736. var mipLevels = 0;
  50737. var floatArrayView = null;
  50738. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50739. this._texture = texture;
  50740. var callback = function (text) {
  50741. var data;
  50742. var tempData;
  50743. var line;
  50744. var lines = text.split('\n');
  50745. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  50746. var maxColor = 0;
  50747. for (var i = 0; i < lines.length; i++) {
  50748. line = lines[i];
  50749. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  50750. continue;
  50751. if (line.indexOf('#') === 0)
  50752. continue;
  50753. var words = line.split(" ");
  50754. if (size === 0) {
  50755. // Number of space + one
  50756. size = words.length;
  50757. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  50758. tempData = new Float32Array(size * size * size * 4);
  50759. continue;
  50760. }
  50761. if (size != 0) {
  50762. var r = Math.max(parseInt(words[0]), 0);
  50763. var g = Math.max(parseInt(words[1]), 0);
  50764. var b = Math.max(parseInt(words[2]), 0);
  50765. maxColor = Math.max(r, maxColor);
  50766. maxColor = Math.max(g, maxColor);
  50767. maxColor = Math.max(b, maxColor);
  50768. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  50769. tempData[pixelStorageIndex + 0] = r;
  50770. tempData[pixelStorageIndex + 1] = g;
  50771. tempData[pixelStorageIndex + 2] = b;
  50772. tempData[pixelStorageIndex + 3] = 0;
  50773. pixelIndexSlice++;
  50774. if (pixelIndexSlice % size == 0) {
  50775. pixelIndexH++;
  50776. pixelIndexSlice = 0;
  50777. if (pixelIndexH % size == 0) {
  50778. pixelIndexW++;
  50779. pixelIndexH = 0;
  50780. }
  50781. }
  50782. }
  50783. }
  50784. for (var i = 0; i < tempData.length; i++) {
  50785. var value = tempData[i];
  50786. data[i] = (value / maxColor * 255);
  50787. }
  50788. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  50789. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  50790. };
  50791. BABYLON.Tools.LoadFile(this.url, callback);
  50792. return this._texture;
  50793. };
  50794. /**
  50795. * Starts the loading process of the texture.
  50796. */
  50797. ColorGradingTexture.prototype.loadTexture = function () {
  50798. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  50799. this.load3dlTexture();
  50800. }
  50801. };
  50802. /**
  50803. * Clones the color gradind texture.
  50804. */
  50805. ColorGradingTexture.prototype.clone = function () {
  50806. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  50807. // Base texture
  50808. newTexture.level = this.level;
  50809. return newTexture;
  50810. };
  50811. /**
  50812. * Called during delayed load for textures.
  50813. */
  50814. ColorGradingTexture.prototype.delayLoad = function () {
  50815. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50816. return;
  50817. }
  50818. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50819. this._texture = this._getFromCache(this.url, true);
  50820. if (!this._texture) {
  50821. this.loadTexture();
  50822. }
  50823. };
  50824. /**
  50825. * Binds the color grading to the shader.
  50826. * @param colorGrading The texture to bind
  50827. * @param effect The effect to bind to
  50828. */
  50829. ColorGradingTexture.Bind = function (colorGrading, effect) {
  50830. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  50831. var x = colorGrading.level; // Texture Level
  50832. var y = colorGrading.getSize().height; // Texture Size example with 8
  50833. var z = y - 1.0; // SizeMinusOne 8 - 1
  50834. var w = 1 / y; // Space of 1 slice 1 / 8
  50835. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  50836. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  50837. 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
  50838. 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
  50839. 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
  50840. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  50841. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  50842. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  50843. };
  50844. /**
  50845. * Prepare the list of uniforms associated with the ColorGrading effects.
  50846. * @param uniformsList The list of uniforms used in the effect
  50847. * @param samplersList The list of samplers used in the effect
  50848. */
  50849. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  50850. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  50851. samplersList.push("cameraColorGrading2DSampler");
  50852. };
  50853. /**
  50854. * Parses a color grading texture serialized by Babylon.
  50855. * @param parsedTexture The texture information being parsedTexture
  50856. * @param scene The scene to load the texture in
  50857. * @param rootUrl The root url of the data assets to load
  50858. * @return A color gradind texture
  50859. */
  50860. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50861. var texture = null;
  50862. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  50863. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  50864. texture.name = parsedTexture.name;
  50865. texture.level = parsedTexture.level;
  50866. }
  50867. return texture;
  50868. };
  50869. /**
  50870. * Serializes the LUT texture to json format.
  50871. */
  50872. ColorGradingTexture.prototype.serialize = function () {
  50873. if (!this.name) {
  50874. return null;
  50875. }
  50876. var serializationObject = {};
  50877. serializationObject.name = this.name;
  50878. serializationObject.level = this.level;
  50879. serializationObject.customType = "BABYLON.ColorGradingTexture";
  50880. return serializationObject;
  50881. };
  50882. /**
  50883. * Empty line regex stored for GC.
  50884. */
  50885. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  50886. return ColorGradingTexture;
  50887. }(BABYLON.BaseTexture));
  50888. BABYLON.ColorGradingTexture = ColorGradingTexture;
  50889. })(BABYLON || (BABYLON = {}));
  50890. var BABYLON;
  50891. (function (BABYLON) {
  50892. /**
  50893. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  50894. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  50895. * 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;
  50896. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  50897. */
  50898. var ColorCurves = (function () {
  50899. function ColorCurves() {
  50900. this._dirty = true;
  50901. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  50902. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  50903. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  50904. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  50905. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  50906. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  50907. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  50908. this._globalHue = 30;
  50909. this._globalDensity = 0;
  50910. this._globalSaturation = 0;
  50911. this._globalExposure = 0;
  50912. this._highlightsHue = 30;
  50913. this._highlightsDensity = 0;
  50914. this._highlightsSaturation = 0;
  50915. this._highlightsExposure = 0;
  50916. this._midtonesHue = 30;
  50917. this._midtonesDensity = 0;
  50918. this._midtonesSaturation = 0;
  50919. this._midtonesExposure = 0;
  50920. this._shadowsHue = 30;
  50921. this._shadowsDensity = 0;
  50922. this._shadowsSaturation = 0;
  50923. this._shadowsExposure = 0;
  50924. }
  50925. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  50926. /**
  50927. * Gets the global Hue value.
  50928. * 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).
  50929. */
  50930. get: function () {
  50931. return this._globalHue;
  50932. },
  50933. /**
  50934. * Sets the global Hue value.
  50935. * 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).
  50936. */
  50937. set: function (value) {
  50938. this._globalHue = value;
  50939. this._dirty = true;
  50940. },
  50941. enumerable: true,
  50942. configurable: true
  50943. });
  50944. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  50945. /**
  50946. * Gets the global Density value.
  50947. * 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.
  50948. * Values less than zero provide a filter of opposite hue.
  50949. */
  50950. get: function () {
  50951. return this._globalDensity;
  50952. },
  50953. /**
  50954. * Sets the global Density value.
  50955. * 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.
  50956. * Values less than zero provide a filter of opposite hue.
  50957. */
  50958. set: function (value) {
  50959. this._globalDensity = value;
  50960. this._dirty = true;
  50961. },
  50962. enumerable: true,
  50963. configurable: true
  50964. });
  50965. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  50966. /**
  50967. * Gets the global Saturation value.
  50968. * 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.
  50969. */
  50970. get: function () {
  50971. return this._globalSaturation;
  50972. },
  50973. /**
  50974. * Sets the global Saturation value.
  50975. * 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.
  50976. */
  50977. set: function (value) {
  50978. this._globalSaturation = value;
  50979. this._dirty = true;
  50980. },
  50981. enumerable: true,
  50982. configurable: true
  50983. });
  50984. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  50985. /**
  50986. * Gets the highlights Hue value.
  50987. * 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).
  50988. */
  50989. get: function () {
  50990. return this._highlightsHue;
  50991. },
  50992. /**
  50993. * Sets the highlights Hue value.
  50994. * 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).
  50995. */
  50996. set: function (value) {
  50997. this._highlightsHue = value;
  50998. this._dirty = true;
  50999. },
  51000. enumerable: true,
  51001. configurable: true
  51002. });
  51003. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  51004. /**
  51005. * Gets the highlights Density value.
  51006. * 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.
  51007. * Values less than zero provide a filter of opposite hue.
  51008. */
  51009. get: function () {
  51010. return this._highlightsDensity;
  51011. },
  51012. /**
  51013. * Sets the highlights Density value.
  51014. * 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.
  51015. * Values less than zero provide a filter of opposite hue.
  51016. */
  51017. set: function (value) {
  51018. this._highlightsDensity = value;
  51019. this._dirty = true;
  51020. },
  51021. enumerable: true,
  51022. configurable: true
  51023. });
  51024. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  51025. /**
  51026. * Gets the highlights Saturation value.
  51027. * 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.
  51028. */
  51029. get: function () {
  51030. return this._highlightsSaturation;
  51031. },
  51032. /**
  51033. * Sets the highlights Saturation value.
  51034. * 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.
  51035. */
  51036. set: function (value) {
  51037. this._highlightsSaturation = value;
  51038. this._dirty = true;
  51039. },
  51040. enumerable: true,
  51041. configurable: true
  51042. });
  51043. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  51044. /**
  51045. * Gets the highlights Exposure value.
  51046. * 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.
  51047. */
  51048. get: function () {
  51049. return this._highlightsExposure;
  51050. },
  51051. /**
  51052. * Sets the highlights Exposure value.
  51053. * 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.
  51054. */
  51055. set: function (value) {
  51056. this._highlightsExposure = value;
  51057. this._dirty = true;
  51058. },
  51059. enumerable: true,
  51060. configurable: true
  51061. });
  51062. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  51063. /**
  51064. * Gets the midtones Hue value.
  51065. * 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).
  51066. */
  51067. get: function () {
  51068. return this._midtonesHue;
  51069. },
  51070. /**
  51071. * Sets the midtones Hue value.
  51072. * 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).
  51073. */
  51074. set: function (value) {
  51075. this._midtonesHue = value;
  51076. this._dirty = true;
  51077. },
  51078. enumerable: true,
  51079. configurable: true
  51080. });
  51081. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  51082. /**
  51083. * Gets the midtones Density value.
  51084. * 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.
  51085. * Values less than zero provide a filter of opposite hue.
  51086. */
  51087. get: function () {
  51088. return this._midtonesDensity;
  51089. },
  51090. /**
  51091. * Sets the midtones Density value.
  51092. * 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.
  51093. * Values less than zero provide a filter of opposite hue.
  51094. */
  51095. set: function (value) {
  51096. this._midtonesDensity = value;
  51097. this._dirty = true;
  51098. },
  51099. enumerable: true,
  51100. configurable: true
  51101. });
  51102. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  51103. /**
  51104. * Gets the midtones Saturation value.
  51105. * 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.
  51106. */
  51107. get: function () {
  51108. return this._midtonesSaturation;
  51109. },
  51110. /**
  51111. * Sets the midtones Saturation value.
  51112. * 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.
  51113. */
  51114. set: function (value) {
  51115. this._midtonesSaturation = value;
  51116. this._dirty = true;
  51117. },
  51118. enumerable: true,
  51119. configurable: true
  51120. });
  51121. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  51122. /**
  51123. * Gets the midtones Exposure value.
  51124. * 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.
  51125. */
  51126. get: function () {
  51127. return this._midtonesExposure;
  51128. },
  51129. /**
  51130. * Sets the midtones Exposure value.
  51131. * 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.
  51132. */
  51133. set: function (value) {
  51134. this._midtonesExposure = value;
  51135. this._dirty = true;
  51136. },
  51137. enumerable: true,
  51138. configurable: true
  51139. });
  51140. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  51141. /**
  51142. * Gets the shadows Hue value.
  51143. * 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).
  51144. */
  51145. get: function () {
  51146. return this._shadowsHue;
  51147. },
  51148. /**
  51149. * Sets the shadows Hue value.
  51150. * 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).
  51151. */
  51152. set: function (value) {
  51153. this._shadowsHue = value;
  51154. this._dirty = true;
  51155. },
  51156. enumerable: true,
  51157. configurable: true
  51158. });
  51159. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  51160. /**
  51161. * Gets the shadows Density value.
  51162. * 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.
  51163. * Values less than zero provide a filter of opposite hue.
  51164. */
  51165. get: function () {
  51166. return this._shadowsDensity;
  51167. },
  51168. /**
  51169. * Sets the shadows Density value.
  51170. * 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.
  51171. * Values less than zero provide a filter of opposite hue.
  51172. */
  51173. set: function (value) {
  51174. this._shadowsDensity = value;
  51175. this._dirty = true;
  51176. },
  51177. enumerable: true,
  51178. configurable: true
  51179. });
  51180. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  51181. /**
  51182. * Gets the shadows Saturation value.
  51183. * 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.
  51184. */
  51185. get: function () {
  51186. return this._shadowsSaturation;
  51187. },
  51188. /**
  51189. * Sets the shadows Saturation value.
  51190. * 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.
  51191. */
  51192. set: function (value) {
  51193. this._shadowsSaturation = value;
  51194. this._dirty = true;
  51195. },
  51196. enumerable: true,
  51197. configurable: true
  51198. });
  51199. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  51200. /**
  51201. * Gets the shadows Exposure value.
  51202. * 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.
  51203. */
  51204. get: function () {
  51205. return this._shadowsExposure;
  51206. },
  51207. /**
  51208. * Sets the shadows Exposure value.
  51209. * 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.
  51210. */
  51211. set: function (value) {
  51212. this._shadowsExposure = value;
  51213. this._dirty = true;
  51214. },
  51215. enumerable: true,
  51216. configurable: true
  51217. });
  51218. /**
  51219. * Binds the color curves to the shader.
  51220. * @param colorCurves The color curve to bind
  51221. * @param effect The effect to bind to
  51222. */
  51223. ColorCurves.Bind = function (colorCurves, effect) {
  51224. if (colorCurves._dirty) {
  51225. colorCurves._dirty = false;
  51226. // Fill in global info.
  51227. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  51228. // Compute highlights info.
  51229. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  51230. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  51231. // Compute midtones info.
  51232. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  51233. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  51234. // Compute shadows info.
  51235. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  51236. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  51237. // Compute deltas (neutral is midtones).
  51238. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  51239. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  51240. }
  51241. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  51242. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  51243. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  51244. };
  51245. /**
  51246. * Prepare the list of uniforms associated with the ColorCurves effects.
  51247. * @param uniformsList The list of uniforms used in the effect
  51248. */
  51249. ColorCurves.PrepareUniforms = function (uniformsList) {
  51250. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  51251. };
  51252. /**
  51253. * Returns color grading data based on a hue, density, saturation and exposure value.
  51254. * @param filterHue The hue of the color filter.
  51255. * @param filterDensity The density of the color filter.
  51256. * @param saturation The saturation.
  51257. * @param exposure The exposure.
  51258. * @param result The result data container.
  51259. */
  51260. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  51261. if (hue == null) {
  51262. return;
  51263. }
  51264. hue = ColorCurves.clamp(hue, 0, 360);
  51265. density = ColorCurves.clamp(density, -100, 100);
  51266. saturation = ColorCurves.clamp(saturation, -100, 100);
  51267. exposure = ColorCurves.clamp(exposure, -100, 100);
  51268. // Remap the slider/config filter density with non-linear mapping and also scale by half
  51269. // so that the maximum filter density is only 50% control. This provides fine control
  51270. // for small values and reasonable range.
  51271. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  51272. density *= 0.5;
  51273. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  51274. if (density < 0) {
  51275. density *= -1;
  51276. hue = (hue + 180) % 360;
  51277. }
  51278. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  51279. result.scaleToRef(2, result);
  51280. result.a = 1 + 0.01 * saturation;
  51281. };
  51282. /**
  51283. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  51284. * @param value The input slider value in range [-100,100].
  51285. * @returns Adjusted value.
  51286. */
  51287. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  51288. value /= 100;
  51289. var x = Math.abs(value);
  51290. x = Math.pow(x, 2);
  51291. if (value < 0) {
  51292. x *= -1;
  51293. }
  51294. x *= 100;
  51295. return x;
  51296. };
  51297. /**
  51298. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  51299. * @param hue The hue (H) input.
  51300. * @param saturation The saturation (S) input.
  51301. * @param brightness The brightness (B) input.
  51302. * @result An RGBA color represented as Vector4.
  51303. */
  51304. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  51305. var h = ColorCurves.clamp(hue, 0, 360);
  51306. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  51307. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  51308. if (s === 0) {
  51309. result.r = v;
  51310. result.g = v;
  51311. result.b = v;
  51312. }
  51313. else {
  51314. // sector 0 to 5
  51315. h /= 60;
  51316. var i = Math.floor(h);
  51317. // fractional part of h
  51318. var f = h - i;
  51319. var p = v * (1 - s);
  51320. var q = v * (1 - s * f);
  51321. var t = v * (1 - s * (1 - f));
  51322. switch (i) {
  51323. case 0:
  51324. result.r = v;
  51325. result.g = t;
  51326. result.b = p;
  51327. break;
  51328. case 1:
  51329. result.r = q;
  51330. result.g = v;
  51331. result.b = p;
  51332. break;
  51333. case 2:
  51334. result.r = p;
  51335. result.g = v;
  51336. result.b = t;
  51337. break;
  51338. case 3:
  51339. result.r = p;
  51340. result.g = q;
  51341. result.b = v;
  51342. break;
  51343. case 4:
  51344. result.r = t;
  51345. result.g = p;
  51346. result.b = v;
  51347. break;
  51348. default:
  51349. result.r = v;
  51350. result.g = p;
  51351. result.b = q;
  51352. break;
  51353. }
  51354. }
  51355. result.a = 1;
  51356. };
  51357. /**
  51358. * Returns a value clamped between min and max
  51359. * @param value The value to clamp
  51360. * @param min The minimum of value
  51361. * @param max The maximum of value
  51362. * @returns The clamped value.
  51363. */
  51364. ColorCurves.clamp = function (value, min, max) {
  51365. return Math.min(Math.max(value, min), max);
  51366. };
  51367. /**
  51368. * Clones the current color curve instance.
  51369. * @return The cloned curves
  51370. */
  51371. ColorCurves.prototype.clone = function () {
  51372. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  51373. };
  51374. /**
  51375. * Serializes the current color curve instance to a json representation.
  51376. * @return a JSON representation
  51377. */
  51378. ColorCurves.prototype.serialize = function () {
  51379. return BABYLON.SerializationHelper.Serialize(this);
  51380. };
  51381. /**
  51382. * Parses the color curve from a json representation.
  51383. * @param source the JSON source to parse
  51384. * @return The parsed curves
  51385. */
  51386. ColorCurves.Parse = function (source) {
  51387. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  51388. };
  51389. __decorate([
  51390. BABYLON.serialize()
  51391. ], ColorCurves.prototype, "_globalHue", void 0);
  51392. __decorate([
  51393. BABYLON.serialize()
  51394. ], ColorCurves.prototype, "_globalDensity", void 0);
  51395. __decorate([
  51396. BABYLON.serialize()
  51397. ], ColorCurves.prototype, "_globalSaturation", void 0);
  51398. __decorate([
  51399. BABYLON.serialize()
  51400. ], ColorCurves.prototype, "_globalExposure", void 0);
  51401. __decorate([
  51402. BABYLON.serialize()
  51403. ], ColorCurves.prototype, "_highlightsHue", void 0);
  51404. __decorate([
  51405. BABYLON.serialize()
  51406. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  51407. __decorate([
  51408. BABYLON.serialize()
  51409. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  51410. __decorate([
  51411. BABYLON.serialize()
  51412. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  51413. __decorate([
  51414. BABYLON.serialize()
  51415. ], ColorCurves.prototype, "_midtonesHue", void 0);
  51416. __decorate([
  51417. BABYLON.serialize()
  51418. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  51419. __decorate([
  51420. BABYLON.serialize()
  51421. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  51422. __decorate([
  51423. BABYLON.serialize()
  51424. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  51425. return ColorCurves;
  51426. }());
  51427. BABYLON.ColorCurves = ColorCurves;
  51428. })(BABYLON || (BABYLON = {}));
  51429. var BABYLON;
  51430. (function (BABYLON) {
  51431. var PBRMaterialDefines = (function (_super) {
  51432. __extends(PBRMaterialDefines, _super);
  51433. function PBRMaterialDefines() {
  51434. _super.call(this);
  51435. this.ALBEDO = false;
  51436. this.AMBIENT = false;
  51437. this.OPACITY = false;
  51438. this.OPACITYRGB = false;
  51439. this.REFLECTION = false;
  51440. this.EMISSIVE = false;
  51441. this.REFLECTIVITY = false;
  51442. this.BUMP = false;
  51443. this.PARALLAX = false;
  51444. this.PARALLAXOCCLUSION = false;
  51445. this.SPECULAROVERALPHA = false;
  51446. this.CLIPPLANE = false;
  51447. this.ALPHATEST = false;
  51448. this.ALPHAFROMALBEDO = false;
  51449. this.POINTSIZE = false;
  51450. this.FOG = false;
  51451. this.SPECULARTERM = false;
  51452. this.OPACITYFRESNEL = false;
  51453. this.EMISSIVEFRESNEL = false;
  51454. this.FRESNEL = false;
  51455. this.NORMAL = false;
  51456. this.UV1 = false;
  51457. this.UV2 = false;
  51458. this.VERTEXCOLOR = false;
  51459. this.VERTEXALPHA = false;
  51460. this.NUM_BONE_INFLUENCERS = 0;
  51461. this.BonesPerMesh = 0;
  51462. this.INSTANCES = false;
  51463. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  51464. this.MICROSURFACEAUTOMATIC = false;
  51465. this.EMISSIVEASILLUMINATION = false;
  51466. this.LINKEMISSIVEWITHALBEDO = false;
  51467. this.LIGHTMAP = false;
  51468. this.USELIGHTMAPASSHADOWMAP = false;
  51469. this.REFLECTIONMAP_3D = false;
  51470. this.REFLECTIONMAP_SPHERICAL = false;
  51471. this.REFLECTIONMAP_PLANAR = false;
  51472. this.REFLECTIONMAP_CUBIC = false;
  51473. this.REFLECTIONMAP_PROJECTION = false;
  51474. this.REFLECTIONMAP_SKYBOX = false;
  51475. this.REFLECTIONMAP_EXPLICIT = false;
  51476. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  51477. this.INVERTCUBICMAP = false;
  51478. this.LOGARITHMICDEPTH = false;
  51479. this.CAMERATONEMAP = false;
  51480. this.CAMERACONTRAST = false;
  51481. this.CAMERACOLORGRADING = false;
  51482. this.CAMERACOLORCURVES = false;
  51483. this.OVERLOADEDVALUES = false;
  51484. this.OVERLOADEDSHADOWVALUES = false;
  51485. this.USESPHERICALFROMREFLECTIONMAP = false;
  51486. this.REFRACTION = false;
  51487. this.REFRACTIONMAP_3D = false;
  51488. this.LINKREFRACTIONTOTRANSPARENCY = false;
  51489. this.REFRACTIONMAPINLINEARSPACE = false;
  51490. this.LODBASEDMICROSFURACE = false;
  51491. this.USEPHYSICALLIGHTFALLOFF = false;
  51492. this.RADIANCEOVERALPHA = false;
  51493. this.USEPMREMREFLECTION = false;
  51494. this.USEPMREMREFRACTION = false;
  51495. this.OPENGLNORMALMAP = false;
  51496. this.INVERTNORMALMAPX = false;
  51497. this.INVERTNORMALMAPY = false;
  51498. this.SHADOWFULLFLOAT = false;
  51499. this.rebuild();
  51500. }
  51501. return PBRMaterialDefines;
  51502. }(BABYLON.MaterialDefines));
  51503. /**
  51504. * The Physically based material of BJS.
  51505. *
  51506. * This offers the main features of a standard PBR material.
  51507. * For more information, please refer to the documentation :
  51508. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  51509. */
  51510. var PBRMaterial = (function (_super) {
  51511. __extends(PBRMaterial, _super);
  51512. /**
  51513. * Instantiates a new PBRMaterial instance.
  51514. *
  51515. * @param name The material name
  51516. * @param scene The scene the material will be use in.
  51517. */
  51518. function PBRMaterial(name, scene) {
  51519. var _this = this;
  51520. _super.call(this, name, scene);
  51521. /**
  51522. * Intensity of the direct lights e.g. the four lights available in your scene.
  51523. * This impacts both the direct diffuse and specular highlights.
  51524. */
  51525. this.directIntensity = 1.0;
  51526. /**
  51527. * Intensity of the emissive part of the material.
  51528. * This helps controlling the emissive effect without modifying the emissive color.
  51529. */
  51530. this.emissiveIntensity = 1.0;
  51531. /**
  51532. * Intensity of the environment e.g. how much the environment will light the object
  51533. * either through harmonics for rough material or through the refelction for shiny ones.
  51534. */
  51535. this.environmentIntensity = 1.0;
  51536. /**
  51537. * This is a special control allowing the reduction of the specular highlights coming from the
  51538. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  51539. */
  51540. this.specularIntensity = 1.0;
  51541. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  51542. /**
  51543. * Debug Control allowing disabling the bump map on this material.
  51544. */
  51545. this.disableBumpMap = false;
  51546. /**
  51547. * Debug Control helping enforcing or dropping the darkness of shadows.
  51548. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  51549. */
  51550. this.overloadedShadowIntensity = 1.0;
  51551. /**
  51552. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  51553. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  51554. */
  51555. this.overloadedShadeIntensity = 1.0;
  51556. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  51557. /**
  51558. * The camera exposure used on this material.
  51559. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  51560. * This corresponds to a photographic exposure.
  51561. */
  51562. this.cameraExposure = 1.0;
  51563. /**
  51564. * The camera contrast used on this material.
  51565. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  51566. */
  51567. this.cameraContrast = 1.0;
  51568. /**
  51569. * Color Grading 2D Lookup Texture.
  51570. * This allows special effects like sepia, black and white to sixties rendering style.
  51571. */
  51572. this.cameraColorGradingTexture = null;
  51573. /**
  51574. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  51575. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  51576. * 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;
  51577. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  51578. */
  51579. this.cameraColorCurves = null;
  51580. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  51581. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  51582. /**
  51583. * Debug Control allowing to overload the ambient color.
  51584. * This as to be use with the overloadedAmbientIntensity parameter.
  51585. */
  51586. this.overloadedAmbient = BABYLON.Color3.White();
  51587. /**
  51588. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  51589. */
  51590. this.overloadedAmbientIntensity = 0.0;
  51591. /**
  51592. * Debug Control allowing to overload the albedo color.
  51593. * This as to be use with the overloadedAlbedoIntensity parameter.
  51594. */
  51595. this.overloadedAlbedo = BABYLON.Color3.White();
  51596. /**
  51597. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  51598. */
  51599. this.overloadedAlbedoIntensity = 0.0;
  51600. /**
  51601. * Debug Control allowing to overload the reflectivity color.
  51602. * This as to be use with the overloadedReflectivityIntensity parameter.
  51603. */
  51604. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  51605. /**
  51606. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  51607. */
  51608. this.overloadedReflectivityIntensity = 0.0;
  51609. /**
  51610. * Debug Control allowing to overload the emissive color.
  51611. * This as to be use with the overloadedEmissiveIntensity parameter.
  51612. */
  51613. this.overloadedEmissive = BABYLON.Color3.White();
  51614. /**
  51615. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  51616. */
  51617. this.overloadedEmissiveIntensity = 0.0;
  51618. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  51619. /**
  51620. * Debug Control allowing to overload the reflection color.
  51621. * This as to be use with the overloadedReflectionIntensity parameter.
  51622. */
  51623. this.overloadedReflection = BABYLON.Color3.White();
  51624. /**
  51625. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  51626. */
  51627. this.overloadedReflectionIntensity = 0.0;
  51628. /**
  51629. * Debug Control allowing to overload the microsurface.
  51630. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  51631. */
  51632. this.overloadedMicroSurface = 0.0;
  51633. /**
  51634. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  51635. */
  51636. this.overloadedMicroSurfaceIntensity = 0.0;
  51637. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  51638. /**
  51639. * AKA Occlusion Texture Intensity in other nomenclature.
  51640. */
  51641. this.ambientTextureStrength = 1.0;
  51642. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  51643. /**
  51644. * AKA Diffuse Color in other nomenclature.
  51645. */
  51646. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  51647. /**
  51648. * AKA Specular Color in other nomenclature.
  51649. */
  51650. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  51651. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  51652. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  51653. /**
  51654. * AKA Glossiness in other nomenclature.
  51655. */
  51656. this.microSurface = 0.9;
  51657. /**
  51658. * source material index of refraction (IOR)' / 'destination material IOR.
  51659. */
  51660. this.indexOfRefraction = 0.66;
  51661. /**
  51662. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  51663. */
  51664. this.invertRefractionY = false;
  51665. /**
  51666. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  51667. * Materials half opaque for instance using refraction could benefit from this control.
  51668. */
  51669. this.linkRefractionWithTransparency = false;
  51670. /**
  51671. * The emissive and albedo are linked to never be more than one (Energy conservation).
  51672. */
  51673. this.linkEmissiveWithAlbedo = false;
  51674. this.useLightmapAsShadowmap = false;
  51675. /**
  51676. * In this mode, the emissive informtaion will always be added to the lighting once.
  51677. * A light for instance can be thought as emissive.
  51678. */
  51679. this.useEmissiveAsIllumination = false;
  51680. /**
  51681. * Secifies that the alpha is coming form the albedo channel alpha channel.
  51682. */
  51683. this.useAlphaFromAlbedoTexture = false;
  51684. /**
  51685. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  51686. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  51687. */
  51688. this.useSpecularOverAlpha = true;
  51689. /**
  51690. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  51691. */
  51692. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  51693. /**
  51694. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  51695. * The material will try to infer what glossiness each pixel should be.
  51696. */
  51697. this.useAutoMicroSurfaceFromReflectivityMap = false;
  51698. /**
  51699. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  51700. * the creation of the material.
  51701. */
  51702. this.useScalarInLinearSpace = false;
  51703. /**
  51704. * BJS is using an harcoded light falloff based on a manually sets up range.
  51705. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  51706. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  51707. */
  51708. this.usePhysicalLightFalloff = true;
  51709. /**
  51710. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  51711. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  51712. */
  51713. this.useRadianceOverAlpha = true;
  51714. /**
  51715. * Allows using the bump map in parallax mode.
  51716. */
  51717. this.useParallax = false;
  51718. /**
  51719. * Allows using the bump map in parallax occlusion mode.
  51720. */
  51721. this.useParallaxOcclusion = false;
  51722. /**
  51723. * Controls the scale bias of the parallax mode.
  51724. */
  51725. this.parallaxScaleBias = 0.05;
  51726. /**
  51727. * If sets to true, disables all the lights affecting the material.
  51728. */
  51729. this.disableLighting = false;
  51730. /**
  51731. * Number of Simultaneous lights allowed on the material.
  51732. */
  51733. this.maxSimultaneousLights = 4;
  51734. /**
  51735. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  51736. */
  51737. this.invertNormalMapX = false;
  51738. /**
  51739. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  51740. */
  51741. this.invertNormalMapY = false;
  51742. this._renderTargets = new BABYLON.SmartArray(16);
  51743. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  51744. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  51745. this._tempColor = new BABYLON.Color3();
  51746. this._defines = new PBRMaterialDefines();
  51747. this._cachedDefines = new PBRMaterialDefines();
  51748. this._myScene = null;
  51749. this._myShadowGenerator = null;
  51750. this._cachedDefines.BonesPerMesh = -1;
  51751. this.getRenderTargetTextures = function () {
  51752. _this._renderTargets.reset();
  51753. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  51754. _this._renderTargets.push(_this.reflectionTexture);
  51755. }
  51756. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  51757. _this._renderTargets.push(_this.refractionTexture);
  51758. }
  51759. return _this._renderTargets;
  51760. };
  51761. }
  51762. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  51763. get: function () {
  51764. return this._useLogarithmicDepth;
  51765. },
  51766. set: function (value) {
  51767. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  51768. },
  51769. enumerable: true,
  51770. configurable: true
  51771. });
  51772. PBRMaterial.prototype.needAlphaBlending = function () {
  51773. if (this.linkRefractionWithTransparency) {
  51774. return false;
  51775. }
  51776. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  51777. };
  51778. PBRMaterial.prototype.needAlphaTesting = function () {
  51779. if (this.linkRefractionWithTransparency) {
  51780. return false;
  51781. }
  51782. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  51783. };
  51784. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  51785. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  51786. };
  51787. PBRMaterial.prototype.getAlphaTestTexture = function () {
  51788. return this.albedoTexture;
  51789. };
  51790. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  51791. if (!mesh) {
  51792. return true;
  51793. }
  51794. if (this._defines.INSTANCES !== useInstances) {
  51795. return false;
  51796. }
  51797. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  51798. return true;
  51799. }
  51800. return false;
  51801. };
  51802. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  51803. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  51804. };
  51805. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  51806. if (!useScalarInLinear) {
  51807. color.toLinearSpaceToRef(ref);
  51808. }
  51809. else {
  51810. ref.r = color.r;
  51811. ref.g = color.g;
  51812. ref.b = color.b;
  51813. }
  51814. };
  51815. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  51816. var lightIndex = 0;
  51817. var depthValuesAlreadySet = false;
  51818. for (var index = 0; index < scene.lights.length; index++) {
  51819. var light = scene.lights[index];
  51820. if (!light.isEnabled()) {
  51821. continue;
  51822. }
  51823. if (!light.canAffectMesh(mesh)) {
  51824. continue;
  51825. }
  51826. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  51827. // GAMMA CORRECTION.
  51828. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  51829. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  51830. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  51831. if (defines["SPECULARTERM"]) {
  51832. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  51833. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  51834. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  51835. }
  51836. // Shadows
  51837. if (scene.shadowsEnabled) {
  51838. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  51839. }
  51840. lightIndex++;
  51841. if (lightIndex === maxSimultaneousLights)
  51842. break;
  51843. }
  51844. };
  51845. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  51846. if (this.checkReadyOnlyOnce) {
  51847. if (this._wasPreviouslyReady) {
  51848. return true;
  51849. }
  51850. }
  51851. var scene = this.getScene();
  51852. if (!this.checkReadyOnEveryCall) {
  51853. if (this._renderId === scene.getRenderId()) {
  51854. if (this._checkCache(scene, mesh, useInstances)) {
  51855. return true;
  51856. }
  51857. }
  51858. }
  51859. var engine = scene.getEngine();
  51860. var needNormals = false;
  51861. var needUVs = false;
  51862. this._defines.reset();
  51863. if (scene.texturesEnabled) {
  51864. if (scene.getEngine().getCaps().textureLOD) {
  51865. this._defines.LODBASEDMICROSFURACE = true;
  51866. }
  51867. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  51868. if (!this.albedoTexture.isReady()) {
  51869. return false;
  51870. }
  51871. else {
  51872. needUVs = true;
  51873. this._defines.ALBEDO = true;
  51874. }
  51875. }
  51876. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  51877. if (!this.ambientTexture.isReady()) {
  51878. return false;
  51879. }
  51880. else {
  51881. needUVs = true;
  51882. this._defines.AMBIENT = true;
  51883. }
  51884. }
  51885. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  51886. if (!this.opacityTexture.isReady()) {
  51887. return false;
  51888. }
  51889. else {
  51890. needUVs = true;
  51891. this._defines.OPACITY = true;
  51892. if (this.opacityTexture.getAlphaFromRGB) {
  51893. this._defines.OPACITYRGB = true;
  51894. }
  51895. }
  51896. }
  51897. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  51898. if (!this.reflectionTexture.isReady()) {
  51899. return false;
  51900. }
  51901. else {
  51902. needNormals = true;
  51903. this._defines.REFLECTION = true;
  51904. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  51905. this._defines.INVERTCUBICMAP = true;
  51906. }
  51907. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  51908. switch (this.reflectionTexture.coordinatesMode) {
  51909. case BABYLON.Texture.CUBIC_MODE:
  51910. case BABYLON.Texture.INVCUBIC_MODE:
  51911. this._defines.REFLECTIONMAP_CUBIC = true;
  51912. break;
  51913. case BABYLON.Texture.EXPLICIT_MODE:
  51914. this._defines.REFLECTIONMAP_EXPLICIT = true;
  51915. break;
  51916. case BABYLON.Texture.PLANAR_MODE:
  51917. this._defines.REFLECTIONMAP_PLANAR = true;
  51918. break;
  51919. case BABYLON.Texture.PROJECTION_MODE:
  51920. this._defines.REFLECTIONMAP_PROJECTION = true;
  51921. break;
  51922. case BABYLON.Texture.SKYBOX_MODE:
  51923. this._defines.REFLECTIONMAP_SKYBOX = true;
  51924. break;
  51925. case BABYLON.Texture.SPHERICAL_MODE:
  51926. this._defines.REFLECTIONMAP_SPHERICAL = true;
  51927. break;
  51928. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  51929. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  51930. break;
  51931. }
  51932. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  51933. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  51934. needNormals = true;
  51935. if (this.reflectionTexture.isPMREM) {
  51936. this._defines.USEPMREMREFLECTION = true;
  51937. }
  51938. }
  51939. }
  51940. }
  51941. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  51942. if (!this.lightmapTexture.isReady()) {
  51943. return false;
  51944. }
  51945. else {
  51946. needUVs = true;
  51947. this._defines.LIGHTMAP = true;
  51948. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  51949. }
  51950. }
  51951. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  51952. if (!this.emissiveTexture.isReady()) {
  51953. return false;
  51954. }
  51955. else {
  51956. needUVs = true;
  51957. this._defines.EMISSIVE = true;
  51958. }
  51959. }
  51960. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  51961. if (!this.reflectivityTexture.isReady()) {
  51962. return false;
  51963. }
  51964. else {
  51965. needUVs = true;
  51966. this._defines.REFLECTIVITY = true;
  51967. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  51968. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  51969. }
  51970. }
  51971. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  51972. if (!this.bumpTexture.isReady()) {
  51973. return false;
  51974. }
  51975. else {
  51976. needUVs = true;
  51977. this._defines.BUMP = true;
  51978. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  51979. this._defines.PARALLAX = true;
  51980. if (this.useParallaxOcclusion) {
  51981. this._defines.PARALLAXOCCLUSION = true;
  51982. }
  51983. }
  51984. if (this.invertNormalMapX) {
  51985. this._defines.INVERTNORMALMAPX = true;
  51986. }
  51987. if (this.invertNormalMapY) {
  51988. this._defines.INVERTNORMALMAPY = true;
  51989. }
  51990. }
  51991. }
  51992. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  51993. if (!this.refractionTexture.isReady()) {
  51994. return false;
  51995. }
  51996. else {
  51997. needUVs = true;
  51998. this._defines.REFRACTION = true;
  51999. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  52000. if (this.linkRefractionWithTransparency) {
  52001. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  52002. }
  52003. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  52004. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  52005. if (this.refractionTexture.isPMREM) {
  52006. this._defines.USEPMREMREFRACTION = true;
  52007. }
  52008. }
  52009. }
  52010. }
  52011. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  52012. if (!this.cameraColorGradingTexture.isReady()) {
  52013. return false;
  52014. }
  52015. else {
  52016. this._defines.CAMERACOLORGRADING = true;
  52017. }
  52018. }
  52019. }
  52020. // Effect
  52021. if (scene.clipPlane) {
  52022. this._defines.CLIPPLANE = true;
  52023. }
  52024. if (engine.getAlphaTesting()) {
  52025. this._defines.ALPHATEST = true;
  52026. }
  52027. if (this._shouldUseAlphaFromAlbedoTexture()) {
  52028. this._defines.ALPHAFROMALBEDO = true;
  52029. }
  52030. if (this.useEmissiveAsIllumination) {
  52031. this._defines.EMISSIVEASILLUMINATION = true;
  52032. }
  52033. if (this.linkEmissiveWithAlbedo) {
  52034. this._defines.LINKEMISSIVEWITHALBEDO = true;
  52035. }
  52036. if (this.useLogarithmicDepth) {
  52037. this._defines.LOGARITHMICDEPTH = true;
  52038. }
  52039. if (this.cameraContrast != 1) {
  52040. this._defines.CAMERACONTRAST = true;
  52041. }
  52042. if (this.cameraExposure != 1) {
  52043. this._defines.CAMERATONEMAP = true;
  52044. }
  52045. if (this.cameraColorCurves) {
  52046. this._defines.CAMERACOLORCURVES = true;
  52047. }
  52048. if (this.overloadedShadeIntensity != 1 ||
  52049. this.overloadedShadowIntensity != 1) {
  52050. this._defines.OVERLOADEDSHADOWVALUES = true;
  52051. }
  52052. if (this.overloadedMicroSurfaceIntensity > 0 ||
  52053. this.overloadedEmissiveIntensity > 0 ||
  52054. this.overloadedReflectivityIntensity > 0 ||
  52055. this.overloadedAlbedoIntensity > 0 ||
  52056. this.overloadedAmbientIntensity > 0 ||
  52057. this.overloadedReflectionIntensity > 0) {
  52058. this._defines.OVERLOADEDVALUES = true;
  52059. }
  52060. // Point size
  52061. if (this.pointsCloud || scene.forcePointsCloud) {
  52062. this._defines.POINTSIZE = true;
  52063. }
  52064. // Fog
  52065. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52066. this._defines.FOG = true;
  52067. }
  52068. if (scene.lightsEnabled && !this.disableLighting) {
  52069. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  52070. }
  52071. if (BABYLON.StandardMaterial.FresnelEnabled) {
  52072. // Fresnel
  52073. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  52074. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  52075. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  52076. this._defines.OPACITYFRESNEL = true;
  52077. }
  52078. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  52079. this._defines.EMISSIVEFRESNEL = true;
  52080. }
  52081. needNormals = true;
  52082. this._defines.FRESNEL = true;
  52083. }
  52084. }
  52085. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  52086. this._defines.SPECULAROVERALPHA = true;
  52087. }
  52088. if (this.usePhysicalLightFalloff) {
  52089. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  52090. }
  52091. if (this.useRadianceOverAlpha) {
  52092. this._defines.RADIANCEOVERALPHA = true;
  52093. }
  52094. // Attribs
  52095. if (mesh) {
  52096. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  52097. this._defines.NORMAL = true;
  52098. }
  52099. if (needUVs) {
  52100. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52101. this._defines.UV1 = true;
  52102. }
  52103. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52104. this._defines.UV2 = true;
  52105. }
  52106. }
  52107. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52108. this._defines.VERTEXCOLOR = true;
  52109. if (mesh.hasVertexAlpha) {
  52110. this._defines.VERTEXALPHA = true;
  52111. }
  52112. }
  52113. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52114. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  52115. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  52116. }
  52117. // Instances
  52118. if (useInstances) {
  52119. this._defines.INSTANCES = true;
  52120. }
  52121. }
  52122. // Get correct effect
  52123. if (!this._defines.isEqual(this._cachedDefines)) {
  52124. this._defines.cloneTo(this._cachedDefines);
  52125. scene.resetCachedMaterial();
  52126. // Fallbacks
  52127. var fallbacks = new BABYLON.EffectFallbacks();
  52128. if (this._defines.REFLECTION) {
  52129. fallbacks.addFallback(0, "REFLECTION");
  52130. }
  52131. if (this._defines.REFRACTION) {
  52132. fallbacks.addFallback(0, "REFRACTION");
  52133. }
  52134. if (this._defines.REFLECTIVITY) {
  52135. fallbacks.addFallback(0, "REFLECTIVITY");
  52136. }
  52137. if (this._defines.BUMP) {
  52138. fallbacks.addFallback(0, "BUMP");
  52139. }
  52140. if (this._defines.PARALLAX) {
  52141. fallbacks.addFallback(1, "PARALLAX");
  52142. }
  52143. if (this._defines.PARALLAXOCCLUSION) {
  52144. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  52145. }
  52146. if (this._defines.SPECULAROVERALPHA) {
  52147. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  52148. }
  52149. if (this._defines.FOG) {
  52150. fallbacks.addFallback(1, "FOG");
  52151. }
  52152. if (this._defines.POINTSIZE) {
  52153. fallbacks.addFallback(0, "POINTSIZE");
  52154. }
  52155. if (this._defines.LOGARITHMICDEPTH) {
  52156. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  52157. }
  52158. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  52159. if (this._defines.SPECULARTERM) {
  52160. fallbacks.addFallback(0, "SPECULARTERM");
  52161. }
  52162. if (this._defines.OPACITYFRESNEL) {
  52163. fallbacks.addFallback(1, "OPACITYFRESNEL");
  52164. }
  52165. if (this._defines.EMISSIVEFRESNEL) {
  52166. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  52167. }
  52168. if (this._defines.FRESNEL) {
  52169. fallbacks.addFallback(3, "FRESNEL");
  52170. }
  52171. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  52172. fallbacks.addCPUSkinningFallback(0, mesh);
  52173. }
  52174. //Attributes
  52175. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52176. if (this._defines.NORMAL) {
  52177. attribs.push(BABYLON.VertexBuffer.NormalKind);
  52178. }
  52179. if (this._defines.UV1) {
  52180. attribs.push(BABYLON.VertexBuffer.UVKind);
  52181. }
  52182. if (this._defines.UV2) {
  52183. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52184. }
  52185. if (this._defines.VERTEXCOLOR) {
  52186. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52187. }
  52188. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  52189. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  52190. // Legacy browser patch
  52191. var join = this._defines.toString();
  52192. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  52193. "vFogInfos", "vFogColor", "pointSize",
  52194. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  52195. "mBones",
  52196. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  52197. "depthValues",
  52198. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  52199. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  52200. "logarithmicDepthConstant",
  52201. "vSphericalX", "vSphericalY", "vSphericalZ",
  52202. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  52203. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  52204. "vMicrosurfaceTextureLods",
  52205. "vCameraInfos"
  52206. ];
  52207. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  52208. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  52209. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  52210. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  52211. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  52212. }
  52213. if (!this._effect.isReady()) {
  52214. return false;
  52215. }
  52216. this._renderId = scene.getRenderId();
  52217. this._wasPreviouslyReady = true;
  52218. if (mesh) {
  52219. if (!mesh._materialDefines) {
  52220. mesh._materialDefines = new PBRMaterialDefines();
  52221. }
  52222. this._defines.cloneTo(mesh._materialDefines);
  52223. }
  52224. return true;
  52225. };
  52226. PBRMaterial.prototype.unbind = function () {
  52227. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  52228. this._effect.setTexture("reflection2DSampler", null);
  52229. }
  52230. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  52231. this._effect.setTexture("refraction2DSampler", null);
  52232. }
  52233. _super.prototype.unbind.call(this);
  52234. };
  52235. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52236. this._effect.setMatrix("world", world);
  52237. };
  52238. PBRMaterial.prototype.bind = function (world, mesh) {
  52239. this._myScene = this.getScene();
  52240. // Matrices
  52241. this.bindOnlyWorldMatrix(world);
  52242. // Bones
  52243. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52244. if (this._myScene.getCachedMaterial() !== this) {
  52245. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  52246. if (BABYLON.StandardMaterial.FresnelEnabled) {
  52247. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  52248. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  52249. }
  52250. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  52251. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  52252. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  52253. }
  52254. }
  52255. // Textures
  52256. if (this._myScene.texturesEnabled) {
  52257. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  52258. this._effect.setTexture("albedoSampler", this.albedoTexture);
  52259. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  52260. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  52261. }
  52262. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  52263. this._effect.setTexture("ambientSampler", this.ambientTexture);
  52264. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  52265. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  52266. }
  52267. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  52268. this._effect.setTexture("opacitySampler", this.opacityTexture);
  52269. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  52270. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  52271. }
  52272. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  52273. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  52274. if (this.reflectionTexture.isCube) {
  52275. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  52276. }
  52277. else {
  52278. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  52279. }
  52280. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  52281. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  52282. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  52283. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  52284. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  52285. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  52286. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  52287. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  52288. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  52289. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  52290. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  52291. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  52292. }
  52293. }
  52294. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  52295. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  52296. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  52297. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  52298. }
  52299. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  52300. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  52301. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  52302. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  52303. }
  52304. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  52305. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  52306. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  52307. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  52308. }
  52309. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  52310. this._effect.setTexture("bumpSampler", this.bumpTexture);
  52311. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  52312. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  52313. }
  52314. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  52315. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  52316. var depth = 1.0;
  52317. if (this.refractionTexture.isCube) {
  52318. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  52319. }
  52320. else {
  52321. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  52322. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  52323. if (this.refractionTexture.depth) {
  52324. depth = this.refractionTexture.depth;
  52325. }
  52326. }
  52327. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  52328. }
  52329. if ((this.reflectionTexture || this.refractionTexture)) {
  52330. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  52331. }
  52332. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  52333. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  52334. }
  52335. }
  52336. // Clip plane
  52337. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  52338. // Point size
  52339. if (this.pointsCloud) {
  52340. this._effect.setFloat("pointSize", this.pointSize);
  52341. }
  52342. // Colors
  52343. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  52344. // GAMMA CORRECTION.
  52345. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  52346. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  52347. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  52348. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  52349. // GAMMA CORRECTION.
  52350. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  52351. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  52352. // GAMMA CORRECTION.
  52353. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  52354. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  52355. }
  52356. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  52357. // GAMMA CORRECTION.
  52358. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  52359. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  52360. // Lights
  52361. if (this._myScene.lightsEnabled && !this.disableLighting) {
  52362. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  52363. }
  52364. // View
  52365. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  52366. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  52367. }
  52368. // Fog
  52369. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  52370. this._lightingInfos.x = this.directIntensity;
  52371. this._lightingInfos.y = this.emissiveIntensity;
  52372. this._lightingInfos.z = this.environmentIntensity;
  52373. this._lightingInfos.w = this.specularIntensity;
  52374. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  52375. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  52376. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  52377. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  52378. this._cameraInfos.x = this.cameraExposure;
  52379. this._cameraInfos.y = this.cameraContrast;
  52380. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  52381. if (this.cameraColorCurves) {
  52382. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  52383. }
  52384. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  52385. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  52386. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  52387. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  52388. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  52389. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  52390. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  52391. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  52392. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  52393. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  52394. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  52395. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  52396. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  52397. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  52398. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  52399. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  52400. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  52401. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  52402. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  52403. // Log. depth
  52404. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  52405. }
  52406. _super.prototype.bind.call(this, world, mesh);
  52407. this._myScene = null;
  52408. };
  52409. PBRMaterial.prototype.getAnimatables = function () {
  52410. var results = [];
  52411. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  52412. results.push(this.albedoTexture);
  52413. }
  52414. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  52415. results.push(this.ambientTexture);
  52416. }
  52417. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  52418. results.push(this.opacityTexture);
  52419. }
  52420. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  52421. results.push(this.reflectionTexture);
  52422. }
  52423. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  52424. results.push(this.emissiveTexture);
  52425. }
  52426. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  52427. results.push(this.reflectivityTexture);
  52428. }
  52429. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  52430. results.push(this.bumpTexture);
  52431. }
  52432. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  52433. results.push(this.lightmapTexture);
  52434. }
  52435. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  52436. results.push(this.refractionTexture);
  52437. }
  52438. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  52439. results.push(this.cameraColorGradingTexture);
  52440. }
  52441. return results;
  52442. };
  52443. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52444. if (forceDisposeTextures) {
  52445. if (this.albedoTexture) {
  52446. this.albedoTexture.dispose();
  52447. }
  52448. if (this.ambientTexture) {
  52449. this.ambientTexture.dispose();
  52450. }
  52451. if (this.opacityTexture) {
  52452. this.opacityTexture.dispose();
  52453. }
  52454. if (this.reflectionTexture) {
  52455. this.reflectionTexture.dispose();
  52456. }
  52457. if (this.emissiveTexture) {
  52458. this.emissiveTexture.dispose();
  52459. }
  52460. if (this.reflectivityTexture) {
  52461. this.reflectivityTexture.dispose();
  52462. }
  52463. if (this.bumpTexture) {
  52464. this.bumpTexture.dispose();
  52465. }
  52466. if (this.lightmapTexture) {
  52467. this.lightmapTexture.dispose();
  52468. }
  52469. if (this.refractionTexture) {
  52470. this.refractionTexture.dispose();
  52471. }
  52472. if (this.cameraColorGradingTexture) {
  52473. this.cameraColorGradingTexture.dispose();
  52474. }
  52475. }
  52476. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52477. };
  52478. PBRMaterial.prototype.clone = function (name) {
  52479. var _this = this;
  52480. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  52481. };
  52482. PBRMaterial.prototype.serialize = function () {
  52483. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52484. serializationObject.customType = "BABYLON.PBRMaterial";
  52485. return serializationObject;
  52486. };
  52487. // Statics
  52488. PBRMaterial.Parse = function (source, scene, rootUrl) {
  52489. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  52490. };
  52491. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  52492. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  52493. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  52494. PBRMaterial._scaledReflection = new BABYLON.Color3();
  52495. __decorate([
  52496. BABYLON.serialize()
  52497. ], PBRMaterial.prototype, "directIntensity", void 0);
  52498. __decorate([
  52499. BABYLON.serialize()
  52500. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  52501. __decorate([
  52502. BABYLON.serialize()
  52503. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  52504. __decorate([
  52505. BABYLON.serialize()
  52506. ], PBRMaterial.prototype, "specularIntensity", void 0);
  52507. __decorate([
  52508. BABYLON.serialize()
  52509. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  52510. __decorate([
  52511. BABYLON.serialize()
  52512. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  52513. __decorate([
  52514. BABYLON.serialize()
  52515. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  52516. __decorate([
  52517. BABYLON.serialize()
  52518. ], PBRMaterial.prototype, "cameraExposure", void 0);
  52519. __decorate([
  52520. BABYLON.serialize()
  52521. ], PBRMaterial.prototype, "cameraContrast", void 0);
  52522. __decorate([
  52523. BABYLON.serializeAsTexture()
  52524. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  52525. __decorate([
  52526. BABYLON.serializeAsColorCurves()
  52527. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  52528. __decorate([
  52529. BABYLON.serializeAsColor3()
  52530. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  52531. __decorate([
  52532. BABYLON.serialize()
  52533. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  52534. __decorate([
  52535. BABYLON.serializeAsColor3()
  52536. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  52537. __decorate([
  52538. BABYLON.serialize()
  52539. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  52540. __decorate([
  52541. BABYLON.serializeAsColor3()
  52542. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  52543. __decorate([
  52544. BABYLON.serialize()
  52545. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  52546. __decorate([
  52547. BABYLON.serializeAsColor3()
  52548. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  52549. __decorate([
  52550. BABYLON.serialize()
  52551. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  52552. __decorate([
  52553. BABYLON.serializeAsColor3()
  52554. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  52555. __decorate([
  52556. BABYLON.serialize()
  52557. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  52558. __decorate([
  52559. BABYLON.serialize()
  52560. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  52561. __decorate([
  52562. BABYLON.serialize()
  52563. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  52564. __decorate([
  52565. BABYLON.serializeAsTexture()
  52566. ], PBRMaterial.prototype, "albedoTexture", void 0);
  52567. __decorate([
  52568. BABYLON.serializeAsTexture()
  52569. ], PBRMaterial.prototype, "ambientTexture", void 0);
  52570. __decorate([
  52571. BABYLON.serialize()
  52572. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  52573. __decorate([
  52574. BABYLON.serializeAsTexture()
  52575. ], PBRMaterial.prototype, "opacityTexture", void 0);
  52576. __decorate([
  52577. BABYLON.serializeAsTexture()
  52578. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  52579. __decorate([
  52580. BABYLON.serializeAsTexture()
  52581. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  52582. __decorate([
  52583. BABYLON.serializeAsTexture()
  52584. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  52585. __decorate([
  52586. BABYLON.serializeAsTexture()
  52587. ], PBRMaterial.prototype, "bumpTexture", void 0);
  52588. __decorate([
  52589. BABYLON.serializeAsTexture()
  52590. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  52591. __decorate([
  52592. BABYLON.serializeAsTexture()
  52593. ], PBRMaterial.prototype, "refractionTexture", void 0);
  52594. __decorate([
  52595. BABYLON.serializeAsColor3("ambient")
  52596. ], PBRMaterial.prototype, "ambientColor", void 0);
  52597. __decorate([
  52598. BABYLON.serializeAsColor3("albedo")
  52599. ], PBRMaterial.prototype, "albedoColor", void 0);
  52600. __decorate([
  52601. BABYLON.serializeAsColor3("reflectivity")
  52602. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  52603. __decorate([
  52604. BABYLON.serializeAsColor3("reflection")
  52605. ], PBRMaterial.prototype, "reflectionColor", void 0);
  52606. __decorate([
  52607. BABYLON.serializeAsColor3("emissive")
  52608. ], PBRMaterial.prototype, "emissiveColor", void 0);
  52609. __decorate([
  52610. BABYLON.serialize()
  52611. ], PBRMaterial.prototype, "microSurface", void 0);
  52612. __decorate([
  52613. BABYLON.serialize()
  52614. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  52615. __decorate([
  52616. BABYLON.serialize()
  52617. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  52618. __decorate([
  52619. BABYLON.serializeAsFresnelParameters()
  52620. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  52621. __decorate([
  52622. BABYLON.serializeAsFresnelParameters()
  52623. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  52624. __decorate([
  52625. BABYLON.serialize()
  52626. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  52627. __decorate([
  52628. BABYLON.serialize()
  52629. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  52630. __decorate([
  52631. BABYLON.serialize()
  52632. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  52633. __decorate([
  52634. BABYLON.serialize()
  52635. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  52636. __decorate([
  52637. BABYLON.serialize()
  52638. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  52639. __decorate([
  52640. BABYLON.serialize()
  52641. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  52642. __decorate([
  52643. BABYLON.serialize()
  52644. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  52645. __decorate([
  52646. BABYLON.serialize()
  52647. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  52648. __decorate([
  52649. BABYLON.serialize()
  52650. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  52651. __decorate([
  52652. BABYLON.serialize()
  52653. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  52654. __decorate([
  52655. BABYLON.serialize()
  52656. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  52657. __decorate([
  52658. BABYLON.serialize()
  52659. ], PBRMaterial.prototype, "useParallax", void 0);
  52660. __decorate([
  52661. BABYLON.serialize()
  52662. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  52663. __decorate([
  52664. BABYLON.serialize()
  52665. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  52666. __decorate([
  52667. BABYLON.serialize()
  52668. ], PBRMaterial.prototype, "disableLighting", void 0);
  52669. __decorate([
  52670. BABYLON.serialize()
  52671. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  52672. __decorate([
  52673. BABYLON.serialize()
  52674. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  52675. __decorate([
  52676. BABYLON.serialize()
  52677. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  52678. __decorate([
  52679. BABYLON.serialize()
  52680. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  52681. return PBRMaterial;
  52682. }(BABYLON.Material));
  52683. BABYLON.PBRMaterial = PBRMaterial;
  52684. })(BABYLON || (BABYLON = {}));
  52685. var BABYLON;
  52686. (function (BABYLON) {
  52687. var DebugLayer = (function () {
  52688. function DebugLayer(scene) {
  52689. var _this = this;
  52690. this._transformationMatrix = BABYLON.Matrix.Identity();
  52691. this._enabled = false;
  52692. this._labelsEnabled = false;
  52693. this._displayStatistics = true;
  52694. this._displayTree = false;
  52695. this._displayLogs = false;
  52696. this._skeletonViewers = new Array();
  52697. this._identityMatrix = BABYLON.Matrix.Identity();
  52698. this.axisRatio = 0.02;
  52699. this.accentColor = "orange";
  52700. this._scene = scene;
  52701. this._syncPositions = function () {
  52702. var engine = _this._scene.getEngine();
  52703. var canvasRect = engine.getRenderingCanvasClientRect();
  52704. if (_this._showUI) {
  52705. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  52706. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  52707. _this._statsDiv.style.width = "400px";
  52708. _this._statsDiv.style.height = "auto";
  52709. _this._statsSubsetDiv.style.maxHeight = "240px";
  52710. _this._optionsDiv.style.left = "0px";
  52711. _this._optionsDiv.style.top = "10px";
  52712. _this._optionsDiv.style.width = "200px";
  52713. _this._optionsDiv.style.height = "auto";
  52714. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  52715. _this._logDiv.style.left = "0px";
  52716. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  52717. _this._logDiv.style.width = "600px";
  52718. _this._logDiv.style.height = "160px";
  52719. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  52720. _this._treeDiv.style.top = "10px";
  52721. _this._treeDiv.style.width = "300px";
  52722. _this._treeDiv.style.height = "auto";
  52723. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  52724. }
  52725. _this._globalDiv.style.left = canvasRect.left + "px";
  52726. _this._globalDiv.style.top = canvasRect.top + "px";
  52727. _this._drawingCanvas.style.left = "0px";
  52728. _this._drawingCanvas.style.top = "0px";
  52729. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  52730. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  52731. var devicePixelRatio = window.devicePixelRatio || 1;
  52732. var context = _this._drawingContext;
  52733. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  52734. context.mozBackingStorePixelRatio ||
  52735. context.msBackingStorePixelRatio ||
  52736. context.oBackingStorePixelRatio ||
  52737. context.backingStorePixelRatio || 1;
  52738. _this._ratio = devicePixelRatio / backingStoreRatio;
  52739. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  52740. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  52741. };
  52742. this._onCanvasClick = function (evt) {
  52743. _this._clickPosition = {
  52744. x: evt.clientX * _this._ratio,
  52745. y: evt.clientY * _this._ratio
  52746. };
  52747. };
  52748. this._syncUI = function () {
  52749. if (_this._showUI) {
  52750. if (_this._displayStatistics) {
  52751. _this._displayStats();
  52752. _this._statsDiv.style.display = "";
  52753. }
  52754. else {
  52755. _this._statsDiv.style.display = "none";
  52756. }
  52757. if (_this._displayLogs) {
  52758. _this._logDiv.style.display = "";
  52759. }
  52760. else {
  52761. _this._logDiv.style.display = "none";
  52762. }
  52763. if (_this._displayTree) {
  52764. _this._treeDiv.style.display = "";
  52765. if (_this._needToRefreshMeshesTree) {
  52766. _this._needToRefreshMeshesTree = false;
  52767. _this._refreshMeshesTreeContent();
  52768. }
  52769. }
  52770. else {
  52771. _this._treeDiv.style.display = "none";
  52772. }
  52773. }
  52774. };
  52775. this._syncData = function () {
  52776. if (_this._labelsEnabled || !_this._showUI) {
  52777. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  52778. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  52779. var engine = _this._scene.getEngine();
  52780. var viewport = _this._camera.viewport;
  52781. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  52782. // Meshes
  52783. var meshes = _this._camera.getActiveMeshes();
  52784. var index;
  52785. var projectedPosition;
  52786. for (index = 0; index < meshes.length; index++) {
  52787. var mesh = meshes.data[index];
  52788. var position = mesh.getBoundingInfo().boundingSphere.center;
  52789. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  52790. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  52791. _this._renderAxis(projectedPosition, mesh, globalViewport);
  52792. }
  52793. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  52794. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  52795. }
  52796. }
  52797. // Cameras
  52798. var cameras = _this._scene.cameras;
  52799. for (index = 0; index < cameras.length; index++) {
  52800. var camera = cameras[index];
  52801. if (camera === _this._camera) {
  52802. continue;
  52803. }
  52804. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  52805. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  52806. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  52807. _this._camera.detachControl(engine.getRenderingCanvas());
  52808. _this._camera = camera;
  52809. _this._camera.attachControl(engine.getRenderingCanvas());
  52810. }, function () { return "purple"; });
  52811. }
  52812. }
  52813. // Lights
  52814. var lights = _this._scene.lights;
  52815. for (index = 0; index < lights.length; index++) {
  52816. var light = lights[index];
  52817. if (light.position) {
  52818. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  52819. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  52820. _this._renderLabel(light.name, projectedPosition, -20, function () {
  52821. light.setEnabled(!light.isEnabled());
  52822. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  52823. }
  52824. }
  52825. }
  52826. }
  52827. _this._clickPosition = undefined;
  52828. };
  52829. }
  52830. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  52831. while (this._treeSubsetDiv.hasChildNodes()) {
  52832. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  52833. }
  52834. // Add meshes
  52835. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  52836. sortedArray.sort(function (a, b) {
  52837. if (a.name === b.name) {
  52838. return 0;
  52839. }
  52840. return (a.name > b.name) ? 1 : -1;
  52841. });
  52842. for (var index = 0; index < sortedArray.length; index++) {
  52843. var mesh = sortedArray[index];
  52844. if (!mesh.isEnabled()) {
  52845. continue;
  52846. }
  52847. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  52848. m.isVisible = element.checked;
  52849. }, mesh);
  52850. }
  52851. };
  52852. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  52853. this._drawingContext.beginPath();
  52854. this._drawingContext.moveTo(zero.x, zero.y);
  52855. this._drawingContext.lineTo(unit.x, unit.y);
  52856. this._drawingContext.strokeStyle = color;
  52857. this._drawingContext.lineWidth = 4;
  52858. this._drawingContext.stroke();
  52859. this._drawingContext.font = "normal 14px Segoe UI";
  52860. this._drawingContext.fillStyle = color;
  52861. this._drawingContext.fillText(label, unitText.x, unitText.y);
  52862. };
  52863. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  52864. var position = mesh.getBoundingInfo().boundingSphere.center;
  52865. var worldMatrix = mesh.getWorldMatrix();
  52866. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  52867. var unit = (unprojectedVector.subtract(position)).length();
  52868. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52869. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52870. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  52871. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52872. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52873. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  52874. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  52875. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  52876. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  52877. };
  52878. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  52879. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  52880. this._drawingContext.font = "normal 12px Segoe UI";
  52881. var textMetrics = this._drawingContext.measureText(text);
  52882. var centerX = projectedPosition.x - textMetrics.width / 2;
  52883. var centerY = projectedPosition.y;
  52884. var clientRect = this._drawingCanvas.getBoundingClientRect();
  52885. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  52886. onClick();
  52887. }
  52888. this._drawingContext.beginPath();
  52889. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  52890. this._drawingContext.fillStyle = getFillStyle();
  52891. this._drawingContext.globalAlpha = 0.5;
  52892. this._drawingContext.fill();
  52893. this._drawingContext.globalAlpha = 1.0;
  52894. this._drawingContext.strokeStyle = '#FFFFFF';
  52895. this._drawingContext.lineWidth = 1;
  52896. this._drawingContext.stroke();
  52897. this._drawingContext.fillStyle = "#FFFFFF";
  52898. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  52899. this._drawingContext.beginPath();
  52900. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  52901. this._drawingContext.fill();
  52902. }
  52903. };
  52904. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  52905. if (!this._clickPosition) {
  52906. return false;
  52907. }
  52908. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  52909. return false;
  52910. }
  52911. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  52912. return false;
  52913. }
  52914. return true;
  52915. };
  52916. DebugLayer.prototype.isVisible = function () {
  52917. return this._enabled;
  52918. };
  52919. DebugLayer.prototype.hide = function () {
  52920. if (!this._enabled) {
  52921. return;
  52922. }
  52923. this._enabled = false;
  52924. var engine = this._scene.getEngine();
  52925. this._scene.unregisterBeforeRender(this._syncData);
  52926. this._scene.unregisterAfterRender(this._syncUI);
  52927. this._rootElement.removeChild(this._globalDiv);
  52928. this._scene.forceShowBoundingBoxes = false;
  52929. this._scene.forceWireframe = false;
  52930. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  52931. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  52932. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  52933. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  52934. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  52935. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  52936. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  52937. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  52938. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  52939. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  52940. this._scene.shadowsEnabled = true;
  52941. this._scene.particlesEnabled = true;
  52942. this._scene.postProcessesEnabled = true;
  52943. this._scene.collisionsEnabled = true;
  52944. this._scene.lightsEnabled = true;
  52945. this._scene.texturesEnabled = true;
  52946. this._scene.lensFlaresEnabled = true;
  52947. this._scene.proceduralTexturesEnabled = true;
  52948. this._scene.renderTargetsEnabled = true;
  52949. this._scene.probesEnabled = true;
  52950. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  52951. this._clearSkeletonViewers();
  52952. };
  52953. DebugLayer.prototype._clearSkeletonViewers = function () {
  52954. for (var index = 0; index < this._skeletonViewers.length; index++) {
  52955. this._skeletonViewers[index].dispose();
  52956. }
  52957. this._skeletonViewers = [];
  52958. };
  52959. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  52960. if (showUI === void 0) { showUI = true; }
  52961. if (camera === void 0) { camera = null; }
  52962. if (rootElement === void 0) { rootElement = null; }
  52963. if (this._enabled) {
  52964. return;
  52965. }
  52966. this._enabled = true;
  52967. if (camera) {
  52968. this._camera = camera;
  52969. }
  52970. else {
  52971. this._camera = this._scene.activeCamera;
  52972. }
  52973. this._showUI = showUI;
  52974. var engine = this._scene.getEngine();
  52975. this._globalDiv = document.createElement("div");
  52976. this._rootElement = rootElement || document.body;
  52977. this._rootElement.appendChild(this._globalDiv);
  52978. this._generateDOMelements();
  52979. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  52980. this._syncPositions();
  52981. this._scene.registerBeforeRender(this._syncData);
  52982. this._scene.registerAfterRender(this._syncUI);
  52983. };
  52984. DebugLayer.prototype._clearLabels = function () {
  52985. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  52986. for (var index = 0; index < this._scene.meshes.length; index++) {
  52987. var mesh = this._scene.meshes[index];
  52988. mesh.renderOverlay = false;
  52989. }
  52990. };
  52991. DebugLayer.prototype._generateheader = function (root, text) {
  52992. var header = document.createElement("div");
  52993. header.innerHTML = text + "&nbsp;";
  52994. header.style.textAlign = "right";
  52995. header.style.width = "100%";
  52996. header.style.color = "white";
  52997. header.style.backgroundColor = "Black";
  52998. header.style.padding = "5px 5px 4px 0px";
  52999. header.style.marginLeft = "-5px";
  53000. header.style.fontWeight = "bold";
  53001. root.appendChild(header);
  53002. };
  53003. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  53004. var label = document.createElement("label");
  53005. label.style.display = "inline";
  53006. label.innerHTML = title;
  53007. label.style.color = color;
  53008. root.appendChild(label);
  53009. root.appendChild(document.createElement("br"));
  53010. };
  53011. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  53012. if (tag === void 0) { tag = null; }
  53013. var label = document.createElement("label");
  53014. label.style.display = "inline";
  53015. var boundingBoxesCheckbox = document.createElement("input");
  53016. boundingBoxesCheckbox.type = "checkbox";
  53017. boundingBoxesCheckbox.checked = initialState;
  53018. boundingBoxesCheckbox.style.display = "inline";
  53019. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  53020. boundingBoxesCheckbox.style.verticalAlign = "sub";
  53021. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  53022. task(evt.target, tag);
  53023. });
  53024. label.appendChild(boundingBoxesCheckbox);
  53025. var container = document.createElement("span");
  53026. var leftPart = document.createElement("span");
  53027. var rightPart = document.createElement("span");
  53028. rightPart.style.cssFloat = "right";
  53029. leftPart.innerHTML = leftTitle;
  53030. rightPart.innerHTML = rightTitle;
  53031. rightPart.style.fontSize = "12px";
  53032. rightPart.style.maxWidth = "200px";
  53033. container.appendChild(leftPart);
  53034. container.appendChild(rightPart);
  53035. label.appendChild(container);
  53036. root.appendChild(label);
  53037. root.appendChild(document.createElement("br"));
  53038. };
  53039. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  53040. if (tag === void 0) { tag = null; }
  53041. var label = document.createElement("label");
  53042. label.style.display = "inline";
  53043. var checkBox = document.createElement("input");
  53044. checkBox.type = "checkbox";
  53045. checkBox.checked = initialState;
  53046. checkBox.style.display = "inline";
  53047. checkBox.style.margin = "0px 5px 0px 0px";
  53048. checkBox.style.verticalAlign = "sub";
  53049. checkBox.addEventListener("change", function (evt) {
  53050. task(evt.target, tag);
  53051. });
  53052. label.appendChild(checkBox);
  53053. label.appendChild(document.createTextNode(title));
  53054. root.appendChild(label);
  53055. root.appendChild(document.createElement("br"));
  53056. };
  53057. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  53058. if (tag === void 0) { tag = null; }
  53059. var button = document.createElement("button");
  53060. button.innerHTML = title;
  53061. button.style.height = "24px";
  53062. button.style.width = "150px";
  53063. button.style.marginBottom = "5px";
  53064. button.style.color = "#444444";
  53065. button.style.border = "1px solid white";
  53066. button.className = "debugLayerButton";
  53067. button.addEventListener("click", function (evt) {
  53068. task(evt.target, tag);
  53069. });
  53070. root.appendChild(button);
  53071. root.appendChild(document.createElement("br"));
  53072. };
  53073. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  53074. if (tag === void 0) { tag = null; }
  53075. var label = document.createElement("label");
  53076. label.style.display = "inline";
  53077. var boundingBoxesRadio = document.createElement("input");
  53078. boundingBoxesRadio.type = "radio";
  53079. boundingBoxesRadio.name = name;
  53080. boundingBoxesRadio.checked = initialState;
  53081. boundingBoxesRadio.style.display = "inline";
  53082. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  53083. boundingBoxesRadio.style.verticalAlign = "sub";
  53084. boundingBoxesRadio.addEventListener("change", function (evt) {
  53085. task(evt.target, tag);
  53086. });
  53087. label.appendChild(boundingBoxesRadio);
  53088. label.appendChild(document.createTextNode(title));
  53089. root.appendChild(label);
  53090. root.appendChild(document.createElement("br"));
  53091. };
  53092. DebugLayer.prototype._generateDOMelements = function () {
  53093. var _this = this;
  53094. this._globalDiv.id = "DebugLayer";
  53095. this._globalDiv.style.position = "absolute";
  53096. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  53097. this._globalDiv.style.fontSize = "14px";
  53098. this._globalDiv.style.color = "white";
  53099. // Drawing canvas
  53100. this._drawingCanvas = document.createElement("canvas");
  53101. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  53102. this._drawingCanvas.style.position = "absolute";
  53103. this._drawingCanvas.style.pointerEvents = "none";
  53104. this._drawingCanvas.style.backgroundColor = "transparent";
  53105. this._drawingContext = this._drawingCanvas.getContext("2d");
  53106. this._globalDiv.appendChild(this._drawingCanvas);
  53107. if (this._showUI) {
  53108. var background = "rgba(128, 128, 128, 0.4)";
  53109. var border = "rgb(180, 180, 180) solid 1px";
  53110. // Stats
  53111. this._statsDiv = document.createElement("div");
  53112. this._statsDiv.id = "DebugLayerStats";
  53113. this._statsDiv.style.border = border;
  53114. this._statsDiv.style.position = "absolute";
  53115. this._statsDiv.style.background = background;
  53116. this._statsDiv.style.padding = "0px 0px 0px 5px";
  53117. this._generateheader(this._statsDiv, "STATISTICS");
  53118. this._statsSubsetDiv = document.createElement("div");
  53119. this._statsSubsetDiv.style.paddingTop = "5px";
  53120. this._statsSubsetDiv.style.paddingBottom = "5px";
  53121. this._statsSubsetDiv.style.overflowY = "auto";
  53122. this._statsDiv.appendChild(this._statsSubsetDiv);
  53123. // Tree
  53124. this._treeDiv = document.createElement("div");
  53125. this._treeDiv.id = "DebugLayerTree";
  53126. this._treeDiv.style.border = border;
  53127. this._treeDiv.style.position = "absolute";
  53128. this._treeDiv.style.background = background;
  53129. this._treeDiv.style.padding = "0px 0px 0px 5px";
  53130. this._treeDiv.style.display = "none";
  53131. this._generateheader(this._treeDiv, "MESHES TREE");
  53132. this._treeSubsetDiv = document.createElement("div");
  53133. this._treeSubsetDiv.style.paddingTop = "5px";
  53134. this._treeSubsetDiv.style.paddingRight = "5px";
  53135. this._treeSubsetDiv.style.overflowY = "auto";
  53136. this._treeSubsetDiv.style.maxHeight = "300px";
  53137. this._treeDiv.appendChild(this._treeSubsetDiv);
  53138. this._needToRefreshMeshesTree = true;
  53139. // Logs
  53140. this._logDiv = document.createElement("div");
  53141. this._logDiv.style.border = border;
  53142. this._logDiv.id = "DebugLayerLogs";
  53143. this._logDiv.style.position = "absolute";
  53144. this._logDiv.style.background = background;
  53145. this._logDiv.style.padding = "0px 0px 0px 5px";
  53146. this._logDiv.style.display = "none";
  53147. this._generateheader(this._logDiv, "LOGS");
  53148. this._logSubsetDiv = document.createElement("div");
  53149. this._logSubsetDiv.style.height = "127px";
  53150. this._logSubsetDiv.style.paddingTop = "5px";
  53151. this._logSubsetDiv.style.overflowY = "auto";
  53152. this._logSubsetDiv.style.fontSize = "12px";
  53153. this._logSubsetDiv.style.fontFamily = "consolas";
  53154. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  53155. this._logDiv.appendChild(this._logSubsetDiv);
  53156. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  53157. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  53158. };
  53159. // Options
  53160. this._optionsDiv = document.createElement("div");
  53161. this._optionsDiv.id = "DebugLayerOptions";
  53162. this._optionsDiv.style.border = border;
  53163. this._optionsDiv.style.position = "absolute";
  53164. this._optionsDiv.style.background = background;
  53165. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  53166. this._optionsDiv.style.overflowY = "auto";
  53167. this._generateheader(this._optionsDiv, "OPTIONS");
  53168. this._optionsSubsetDiv = document.createElement("div");
  53169. this._optionsSubsetDiv.style.paddingTop = "5px";
  53170. this._optionsSubsetDiv.style.paddingBottom = "5px";
  53171. this._optionsSubsetDiv.style.overflowY = "auto";
  53172. this._optionsSubsetDiv.style.maxHeight = "200px";
  53173. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  53174. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  53175. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  53176. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  53177. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  53178. _this._displayTree = element.checked;
  53179. _this._needToRefreshMeshesTree = true;
  53180. });
  53181. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53182. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  53183. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  53184. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  53185. _this._labelsEnabled = element.checked;
  53186. if (!_this._labelsEnabled) {
  53187. _this._clearLabels();
  53188. }
  53189. });
  53190. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  53191. if (element.checked) {
  53192. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  53193. }
  53194. else {
  53195. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  53196. }
  53197. });
  53198. ;
  53199. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53200. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  53201. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  53202. if (element.checked) {
  53203. _this._scene.forceWireframe = false;
  53204. _this._scene.forcePointsCloud = false;
  53205. }
  53206. });
  53207. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  53208. if (element.checked) {
  53209. _this._scene.forceWireframe = true;
  53210. _this._scene.forcePointsCloud = false;
  53211. }
  53212. });
  53213. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  53214. if (element.checked) {
  53215. _this._scene.forceWireframe = false;
  53216. _this._scene.forcePointsCloud = true;
  53217. }
  53218. });
  53219. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53220. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  53221. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  53222. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  53223. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  53224. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  53225. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  53226. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  53227. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  53228. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  53229. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  53230. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  53231. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  53232. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53233. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  53234. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  53235. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  53236. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  53237. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  53238. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  53239. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  53240. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  53241. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  53242. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  53243. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  53244. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  53245. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  53246. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  53247. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  53248. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  53249. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53250. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  53251. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  53252. if (element.checked) {
  53253. _this._scene.headphone = true;
  53254. }
  53255. });
  53256. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  53257. if (element.checked) {
  53258. _this._scene.headphone = false;
  53259. }
  53260. });
  53261. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  53262. _this._scene.audioEnabled = !element.checked;
  53263. });
  53264. }
  53265. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53266. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  53267. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  53268. if (!element.checked) {
  53269. _this._clearSkeletonViewers();
  53270. return;
  53271. }
  53272. for (var index = 0; index < _this._scene.meshes.length; index++) {
  53273. var mesh = _this._scene.meshes[index];
  53274. if (mesh.skeleton) {
  53275. var found = false;
  53276. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  53277. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  53278. found = true;
  53279. break;
  53280. }
  53281. }
  53282. if (found) {
  53283. continue;
  53284. }
  53285. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  53286. viewer.isEnabled = true;
  53287. _this._skeletonViewers.push(viewer);
  53288. }
  53289. }
  53290. });
  53291. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53292. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  53293. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  53294. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  53295. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  53296. if (_this._camera) {
  53297. console.log(_this._camera);
  53298. }
  53299. else {
  53300. console.warn("No camera defined, or debug layer created before camera creation!");
  53301. }
  53302. });
  53303. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53304. this._globalDiv.appendChild(this._statsDiv);
  53305. this._globalDiv.appendChild(this._logDiv);
  53306. this._globalDiv.appendChild(this._optionsDiv);
  53307. this._globalDiv.appendChild(this._treeDiv);
  53308. }
  53309. };
  53310. DebugLayer.prototype._displayStats = function () {
  53311. var scene = this._scene;
  53312. var engine = scene.getEngine();
  53313. var glInfo = engine.getGlInfo();
  53314. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  53315. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53316. + "<b>Count</b><br>"
  53317. + "Total meshes: " + scene.meshes.length + "<br>"
  53318. + "Total lights: " + scene.lights.length + "<br>"
  53319. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  53320. + "Total materials: " + scene.materials.length + "<br>"
  53321. + "Total textures: " + scene.textures.length + "<br>"
  53322. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  53323. + "Active indices: " + scene.getActiveIndices() + "<br>"
  53324. + "Active bones: " + scene.getActiveBones() + "<br>"
  53325. + "Active particles: " + scene.getActiveParticles() + "<br>"
  53326. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  53327. + "<b>Duration</b><br>"
  53328. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  53329. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  53330. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  53331. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  53332. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  53333. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  53334. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  53335. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  53336. + "</div>"
  53337. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53338. + "<b>Extensions</b><br>"
  53339. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  53340. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  53341. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  53342. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  53343. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  53344. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  53345. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  53346. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  53347. + "</div><br>"
  53348. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53349. + "<b>Caps.</b><br>"
  53350. + "Stencil: " + (engine.isStencilEnable ? "Enabled" : "Disabled") + "<br>"
  53351. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  53352. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  53353. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  53354. + "<b>Info</b><br>"
  53355. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  53356. + glInfo.version + "<br>"
  53357. + "</div><br>"
  53358. + glInfo.renderer + "<br>";
  53359. if (this.customStatsFunction) {
  53360. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  53361. }
  53362. };
  53363. return DebugLayer;
  53364. }());
  53365. BABYLON.DebugLayer = DebugLayer;
  53366. })(BABYLON || (BABYLON = {}));
  53367. var BABYLON;
  53368. (function (BABYLON) {
  53369. var StandardRenderingPipeline = (function (_super) {
  53370. __extends(StandardRenderingPipeline, _super);
  53371. /**
  53372. * @constructor
  53373. * @param {string} name - The rendering pipeline name
  53374. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53375. * @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)
  53376. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53377. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53378. */
  53379. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53380. var _this = this;
  53381. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53382. _super.call(this, scene.getEngine(), name);
  53383. this.downSampleX4PostProcess = null;
  53384. this.brightPassPostProcess = null;
  53385. this.gaussianBlurHPostProcesses = [];
  53386. this.gaussianBlurVPostProcesses = [];
  53387. this.textureAdderPostProcess = null;
  53388. this.textureAdderFinalPostProcess = null;
  53389. this.lensFlarePostProcess = null;
  53390. this.lensFlareComposePostProcess = null;
  53391. this.depthOfFieldPostProcess = null;
  53392. // Values
  53393. this.brightThreshold = 1.0;
  53394. this.blurWidth = 2.0;
  53395. this.gaussianCoefficient = 0.25;
  53396. this.gaussianMean = 1.0;
  53397. this.gaussianStandardDeviation = 1.0;
  53398. this.exposure = 1.0;
  53399. this.lensTexture = null;
  53400. this.lensColorTexture = null;
  53401. this.lensFlareStrength = 20.0;
  53402. this.lensFlareGhostDispersal = 1.4;
  53403. this.lensFlareHaloWidth = 0.7;
  53404. this.lensFlareDistortionStrength = 16.0;
  53405. this.lensStarTexture = null;
  53406. this.lensFlareDirtTexture = null;
  53407. this.depthOfFieldDistance = 10.0;
  53408. // IAnimatable
  53409. this.animations = [];
  53410. this._depthRenderer = null;
  53411. // Getters and setters
  53412. this._depthOfFieldEnabled = true;
  53413. this._lensFlareEnabled = true;
  53414. // Initialize
  53415. this._scene = scene;
  53416. // Create pass post-processe
  53417. if (!originalPostProcess) {
  53418. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  53419. }
  53420. else {
  53421. this.originalPostProcess = originalPostProcess;
  53422. }
  53423. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  53424. // Create down sample X4 post-process
  53425. this._createDownSampleX4PostProcess(scene, ratio / 2);
  53426. // Create bright pass post-process
  53427. this._createBrightPassPostProcess(scene, ratio / 2);
  53428. // Create gaussian blur post-processes (down sampling blurs)
  53429. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  53430. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  53431. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  53432. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  53433. // Create texture adder post-process
  53434. this._createTextureAdderPostProcess(scene, ratio);
  53435. // Create depth-of-field source post-process
  53436. this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53437. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  53438. // Create lens flare post-process
  53439. this._createLensFlarePostProcess(scene, ratio);
  53440. // Create gaussian blur used by depth-of-field
  53441. this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  53442. // Create depth-of-field post-process
  53443. this._createDepthOfFieldPostProcess(scene, ratio);
  53444. // Finish
  53445. scene.postProcessRenderPipelineManager.addPipeline(this);
  53446. if (cameras !== null) {
  53447. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53448. }
  53449. // Deactivate
  53450. this.LensFlareEnabled = false;
  53451. this.DepthOfFieldEnabled = false;
  53452. }
  53453. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  53454. get: function () {
  53455. return this._depthOfFieldEnabled;
  53456. },
  53457. set: function (enabled) {
  53458. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  53459. if (enabled && !this._depthOfFieldEnabled) {
  53460. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53461. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53462. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  53463. this._depthRenderer = this._scene.enableDepthRenderer();
  53464. }
  53465. else if (!enabled && this._depthOfFieldEnabled) {
  53466. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53467. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53468. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  53469. }
  53470. this._depthOfFieldEnabled = enabled;
  53471. },
  53472. enumerable: true,
  53473. configurable: true
  53474. });
  53475. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  53476. get: function () {
  53477. return this._lensFlareEnabled;
  53478. },
  53479. set: function (enabled) {
  53480. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  53481. if (enabled && !this._lensFlareEnabled) {
  53482. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  53483. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  53484. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53485. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53486. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  53487. }
  53488. else if (!enabled && this._lensFlareEnabled) {
  53489. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  53490. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  53491. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53492. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53493. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  53494. }
  53495. this._lensFlareEnabled = enabled;
  53496. },
  53497. enumerable: true,
  53498. configurable: true
  53499. });
  53500. // Down Sample X4 Post-Processs
  53501. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53502. var _this = this;
  53503. var downSampleX4Offsets = new Array(32);
  53504. 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);
  53505. this.downSampleX4PostProcess.onApply = function (effect) {
  53506. var id = 0;
  53507. for (var i = -2; i < 2; i++) {
  53508. for (var j = -2; j < 2; j++) {
  53509. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  53510. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  53511. id += 2;
  53512. }
  53513. }
  53514. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53515. };
  53516. // Add to pipeline
  53517. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  53518. };
  53519. // Brightpass Post-Process
  53520. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53521. var _this = this;
  53522. var brightOffsets = new Array(8);
  53523. 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);
  53524. this.brightPassPostProcess.onApply = function (effect) {
  53525. var sU = (1.0 / _this.brightPassPostProcess.width);
  53526. var sV = (1.0 / _this.brightPassPostProcess.height);
  53527. brightOffsets[0] = -0.5 * sU;
  53528. brightOffsets[1] = 0.5 * sV;
  53529. brightOffsets[2] = 0.5 * sU;
  53530. brightOffsets[3] = 0.5 * sV;
  53531. brightOffsets[4] = -0.5 * sU;
  53532. brightOffsets[5] = -0.5 * sV;
  53533. brightOffsets[6] = 0.5 * sU;
  53534. brightOffsets[7] = -0.5 * sV;
  53535. effect.setArray2("dsOffsets", brightOffsets);
  53536. effect.setFloat("brightThreshold", _this.brightThreshold);
  53537. };
  53538. // Add to pipeline
  53539. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  53540. };
  53541. // Create gaussian blur H&V post-processes
  53542. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  53543. var _this = this;
  53544. var blurOffsets = new Array(9);
  53545. var blurWeights = new Array(9);
  53546. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  53547. var callback = function (height) {
  53548. return function (effect) {
  53549. // Weights
  53550. var x = 0.0;
  53551. for (var i = 0; i < 9; i++) {
  53552. x = (i - 4.0) / 4.0;
  53553. blurWeights[i] =
  53554. _this.gaussianCoefficient
  53555. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  53556. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  53557. }
  53558. var lastOutputDimensions = {
  53559. width: scene.getEngine().getRenderWidth(),
  53560. height: scene.getEngine().getRenderHeight()
  53561. };
  53562. for (var i = 0; i < 9; i++) {
  53563. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  53564. blurOffsets[i] = value;
  53565. }
  53566. effect.setArray("blurOffsets", blurOffsets);
  53567. effect.setArray("blurWeights", blurWeights);
  53568. effect.setFloat("blurWidth", _this.blurWidth);
  53569. };
  53570. };
  53571. // Create horizontal gaussian blur post-processes
  53572. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53573. gaussianBlurHPostProcess.onApply = callback(false);
  53574. // Create vertical gaussian blur post-process
  53575. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53576. gaussianBlurVPostProcess.onApply = callback(true);
  53577. // Add to pipeline
  53578. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  53579. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  53580. // Finish
  53581. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  53582. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  53583. };
  53584. // Create texture adder post-process
  53585. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53586. var _this = this;
  53587. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  53588. 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);
  53589. this.textureAdderPostProcess.onApply = function (effect) {
  53590. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  53591. effect.setTexture("lensSampler", _this.lensTexture);
  53592. effect.setFloat("exposure", _this.exposure);
  53593. };
  53594. // Add to pipeline
  53595. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  53596. };
  53597. // Create lens flare post-process
  53598. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  53599. var _this = this;
  53600. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53601. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  53602. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  53603. 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);
  53604. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  53605. var resolution = new BABYLON.Vector2(0, 0);
  53606. // Lens flare
  53607. this.lensFlarePostProcess.onApply = function (effect) {
  53608. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  53609. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  53610. effect.setFloat("strength", _this.lensFlareStrength);
  53611. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  53612. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  53613. // Shift
  53614. resolution.x = _this.lensFlarePostProcess.width;
  53615. resolution.y = _this.lensFlarePostProcess.height;
  53616. effect.setVector2("resolution", resolution);
  53617. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  53618. };
  53619. // Compose
  53620. 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);
  53621. 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);
  53622. this.lensFlareComposePostProcess.onApply = function (effect) {
  53623. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  53624. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  53625. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  53626. // Lens start rotation matrix
  53627. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  53628. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  53629. 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));
  53630. camRot *= 4.0;
  53631. 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);
  53632. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  53633. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  53634. };
  53635. };
  53636. // Create depth-of-field post-process
  53637. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  53638. var _this = this;
  53639. 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);
  53640. this.depthOfFieldPostProcess.onApply = function (effect) {
  53641. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  53642. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  53643. effect.setFloat("distance", _this.depthOfFieldDistance);
  53644. };
  53645. // Add to pipeline
  53646. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  53647. };
  53648. // Dispose
  53649. StandardRenderingPipeline.prototype.dispose = function () {
  53650. for (var i = 0; i < this._scene.cameras.length; i++) {
  53651. var camera = this._scene.cameras[i];
  53652. this.originalPostProcess.dispose(camera);
  53653. this.downSampleX4PostProcess.dispose(camera);
  53654. this.brightPassPostProcess.dispose(camera);
  53655. this.textureAdderPostProcess.dispose(camera);
  53656. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  53657. this.gaussianBlurHPostProcesses[j].dispose(camera);
  53658. }
  53659. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  53660. this.gaussianBlurVPostProcesses[j].dispose(camera);
  53661. }
  53662. this.textureAdderFinalPostProcess.dispose(camera);
  53663. this.lensFlarePostProcess.dispose(camera);
  53664. this.lensFlareComposePostProcess.dispose(camera);
  53665. this.depthOfFieldPostProcess.dispose(camera);
  53666. }
  53667. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53668. _super.prototype.dispose.call(this);
  53669. };
  53670. return StandardRenderingPipeline;
  53671. }(BABYLON.PostProcessRenderPipeline));
  53672. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  53673. })(BABYLON || (BABYLON = {}));
  53674. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\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 REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\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 REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\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#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\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).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 SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\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\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\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\nuniform mat4 world;\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#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.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 position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\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 REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\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#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\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\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)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\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\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).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);\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 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.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\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\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\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 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\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,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\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\nuniform mat4 world;\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#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\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#if defined(REFLECTIVITY)\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#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\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)\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 OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\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]*2.0,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*2.0))*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;\ngl_FragColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nfloat hash(vec2 p) {\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) {\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) {\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}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec4 result=vec4(0.0);\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*float(i));\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=texture2D(textureSampler,offset)*weight;\n}\nfloat patternWeight=0.4*length(vec2(0.5)-uv);\nresult=mix(result,result*vec4(pattern(uv),1.0),0.6);\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-vUV)/length(vec2(0.5))));\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,5.0);\nvec4 halo=texture2D(textureSampler,uv+haloVec)*weight;\ngl_FragColor=(result+halo)*strength;\n}\n#endif\n#if defined(LENS_FLARE_SHIFT)\nuniform vec2 resolution;\nuniform float distortionStrength;\nvoid main(void)\n{\nconst float dispersion=0.15;\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-vUV);\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec2 direction=vec2(normalize(ghostDir));\nvec4 rgbShift=vec4(\ntexture2D(textureSampler,vUV+direction*distortion.r).r,\ntexture2D(textureSampler,vUV+direction*distortion.g).g,\ntexture2D(textureSampler,vUV+direction*distortion.b).b,\n1.0\n);\ngl_FragColor=rgbShift;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 viewMatrix;\nuniform mat3 scaleBias1;\nuniform mat3 scaleBias2;\nvoid main(void)\n{\nvec3 camerax=viewMatrix[0].xyz;\nvec3 cameraz=viewMatrix[1].xyz;\nfloat camRot=dot(camerax,vec3(0.0,0.0,1.0))+dot(cameraz,vec3(0.0,1.0,0.0));\nmat3 rotation=mat3(\ncos(camRot),-sin(camRot),0.0,\nsin(camRot),cos(camRot),0.0,\n0.0,0.0,1.0\n);\nmat3 lensMatrix=scaleBias2*rotation*scaleBias1;\nvec2 lensFlareCoords=(lensMatrix*vec3(vUV,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,lensFlareCoords);\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 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\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}"};
  53675. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  53676. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,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.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return-n<=r&&r<=n},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,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.getClassName=function(){return\"Color3\"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},n.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},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.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},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.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},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.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},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.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},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.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},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,e=t.g+(i.g-t.g)*r,s=t.b+(i.b-t.b)*r;return new n(o,e,s)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,e)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.getClassName=function(){return\"Vector2\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n((-this.x),(-this.y))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>r.y?r.y:e,e=e<i.y?i.y:e,new n(o,e)},n.Hermite=function(t,i,r,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+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r;return new n(o,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=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];n.x=r,n.y=o},n.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),e=o<0?-1:1,s=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*e,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var e=r.subtract(i),s=Math.max(0,Math.min(1,n.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return n.Distance(t,h)},n}();t.Vector2=o;var e=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.getClassName=function(){return\"Vector3\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=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=r*s,t.y=-o*s,t.z=n*e,t.w=i*e,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.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},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.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},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.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},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var e=n.Dot(t,r)-o,s=n.Dot(i,r)-o,h=e/(e-s);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.Forward=function(){return new n(0,0,1)},n.Right=function(){return new n(1,0,0)},n.Left=function(){return new n((-1),0,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=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];n.x=r/s,n.y=o/s,n.z=e/s},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var e=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],s=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=e/a,o.y=s/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){var r=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];n.x=r,n.y=o,n.z=e},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*e+(2*t.z-5*i.z+4*r.z-o.z)*s+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>r.y?r.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>r.z?r.z:s,s=s<i.z?i.z:s,new n(o,e,s)},n.Hermite=function(t,i,r,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+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r,s=t.z+(i.z-t.z)*r;return new n(o,e,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,n.copyFrom(M.Vector3[0])},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=n._viewportMatrixCache?n._viewportMatrixCache:n._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=n._matrixCache?n._matrixCache:n._matrixCache=new u;return i.multiplyToRef(r,y),y.multiplyToRef(m,y),n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,e,s){var h=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.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},n.Unproject=function(t,r,o,e,s,h){var a=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new n(t.x/r*2-1,(-(t.y/o*2-1)),t.z),y=n.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},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,e,s){var h=r.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],R=0,T=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),n.CrossToRef(h,T,g),g.normalize(),n.Dot(a,g)<0&&(v=1),R=n.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,n.Dot(T,u)<0&&(f=Math.PI+f,T=T.scaleInPlace(-1),d++);var _=M.Vector3[2],A=M.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),n.CrossToRef(_,T,A),A.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(T,g)<0&&(v=1),R=n.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,n.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,T,g),g.normalize(),n.Dot(g,m)<0&&(v=1),R=n.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},n}();t.Vector3=e;var s=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},n.prototype.getClassName=function(){return\"Vector4\"},n.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)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.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},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z),(-this.w))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.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},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.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},n.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return n*n+r*r+o*o+e*e},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,n){return new t(this.width*i,this.height*n)},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 n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,e=i.height+(n.height-i.height)*r;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-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(n,r,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n=this.x,r=this.y,o=this.z,e=this.w,s=n*n,h=-2*(s+r*r)+1,a=2*(o*n+e*r),u=-2*(o*r-e*n),m=2*(n*r+e*o),y=-2*(o*o+s)+1;return u=u>1?1:u,u=u<-1?-1:u,t.x=Math.asin(u),t.z=Math.atan2(m,y),t.y=Math.atan2(a,h),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=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*(n+r),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*(r+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*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],e=r[4],s=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(s-m)*n,i.z=(h-e)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(e+h)/n,i.z=(s+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(s-m)/n,i.x=(e+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-e)/n,i.x=(s+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){return t.RotationAxisToRef(i,n,new t)},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(i/2);return t.normalize(),n.w=Math.cos(i/2),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,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);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),e=.5*(n-t),s=.5*i;r.x=Math.cos(e)*Math.sin(s),r.y=Math.sin(e)*Math.sin(s),r.z=Math.sin(o)*Math.cos(s),r.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,n,r){var o,e,s=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.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}return new t(e*i.x+o*n.x,e*i.y+o*n.y,e*i.z+o*n.z,e*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.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])},t.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],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=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]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*e)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;n<16;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),b=1/(i*T+n*_+r*M+o*A),F=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,D=s*y-h*m,q=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*R)*b,t.m[13]=(i*v-n*g+r*R)*b,t.m[2]=(n*F-r*L+o*C)*b,t.m[6]=-(i*F-r*P+o*Z)*b,t.m[10]=(i*L-n*P+o*S)*b,t.m[14]=-(i*C-n*Z+r*S)*b,t.m[3]=-(n*I-r*H+o*D)*b,t.m[7]=(i*I-r*q+o*V)*b,t.m[11]=-(i*H-n*q+o*N)*b,t.m[15]=(i*D-n*V+r*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;n<16;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),\nthis},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],b=t.m[8],F=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[n]=r*v+o*T+e*b+s*P,i[n+1]=r*d+o*_+e*F+s*Z,i[n+2]=r*g+o*M+e*L+s*S,i[n+3]=r*R+o*A+e*C+s*I,i[n+4]=h*v+a*T+u*b+m*P,i[n+5]=h*d+a*_+u*F+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*R+a*A+u*C+m*I,i[n+8]=y*v+c*T+p*b+f*P,i[n+9]=y*d+c*_+p*F+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*R+c*A+p*C+f*I,i[n+12]=x*v+l*T+z*b+w*P,i[n+13]=x*d+l*_+z*F+w*Z,i[n+14]=x*g+l*M+z*L+w*S,i[n+15]=x*R+l*A+z*C+w*I,this},t.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]},t.prototype.clone=function(){return t.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])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,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 n.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z?(r.x=0,r.y=0,r.z=0,r.w=1,!1):(t.FromValuesToRef(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1,M.Matrix[0]),a.FromRotationMatrixToRef(M.Matrix[0],r),!0)},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;r<16;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;o<16;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=n,l.m[3]=r,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},t.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])},t.prototype.setRow=function(t,i){if(t<0||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,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},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return n.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,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},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,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},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,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},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),n.m[0]=t.x*t.x*e+o,n.m[1]=t.x*t.y*e-t.z*r,n.m[2]=t.x*t.z*e+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*e+t.z*r,n.m[5]=t.y*t.y*e+o,n.m[6]=t.y*t.z*e-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*e-t.y*r,n.m[9]=t.z*t.y*e+t.x*r,n.m[10]=t.z*t.z*e+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-r)+n.m[e]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,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,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.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)},t.LookAtRH=function(i,n,r){var o=t.Zero();return t.LookAtRHToRef(i,n,r,o),o},t.LookAtRHToRef=function(i,n,r,o){i.subtractToRef(n,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,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,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.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)},t.OrthoLH=function(i,n,r,o){var e=t.Zero();return t.OrthoLHToRef(i,n,r,o,e),e},t.OrthoLHToRef=function(i,n,r,o,e){var s=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-n),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(e-o),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(r+n)/(n-r),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,n,r,o,e,s,h){t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,n,r,o){var e=t.Zero();return e.m[0]=2*r/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*r/n,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(r-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=r*o/(r-o),e},t.PerspectiveFovLH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,e),e},t.PerspectiveFovLHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(r-n),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(n*r)/(r-n)},t.PerspectiveFovRH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,n,r,o,e),e},t.PerspectiveFovRHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(n-r),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.PerspectiveFovWebVRToRef=function(t,i,n,r,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);r.m[0]=u,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=m,r.m[6]=r.m[7]=0,r.m[8]=(h-a)*u*.5,r.m[9]=-((e-s)*m*.5),r.m[10]=-n/(i-n),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=i*n/(i-n)},t.GetFinalMatrix=function(i,n,r,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.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 n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.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]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,e=-2*n,s=-2*r,h=-2*o;i.m[0]=e*n+1,i.m[1]=s*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=e*r,i.m[5]=s*r+1,i.m[6]=h*r,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},t.FromXYZAxesToRef=function(t,i,n,r){r.m[0]=t.x,r.m[1]=t.y,r.m[2]=t.z,r.m[3]=0,r.m[4]=i.x,r.m[5]=i.y,r.m[6]=i.z,r.m[7]=0,r.m[8]=n.x,r.m[9]=n.y,r.m[10]=n.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}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 n=u.Transpose(i),r=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=r*n.m[0]+o*n.m[1]+e*n.m[2]+s*n.m[3],a=r*n.m[4]+o*n.m[5]+e*n.m[6]+s*n.m[7],m=r*n.m[8]+o*n.m[9]+e*n.m[10]+s*n.m[11],y=r*n.m[12]+o*n.m[13]+e*n.m[14]+s*n.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,n){var r,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.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 r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,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 n=e.Dot(this.normal,t);return n<=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,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;r<6;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},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,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var e=1-3*r+3*i,s=3*r-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*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,l=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,n){var r=n.subtract(i),o=Math.atan2(r.y,r.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=l;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,s=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-n.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-n.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.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?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=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 n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,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(n,r),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.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],n=this._points[0];t+=n.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(),n=0,r=0;r<this._points.length;r++){var e=(r+1)%this._points.length,s=this._points[r],h=this._points[e],a=h.subtract(s),u=a.length()+n;if(i>=n&&i<=u){var m=a.normalize(),y=i-n;return new o(s.x+m.x*y,s.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){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 r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.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 n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,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()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var s,h=r.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(r.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.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(r,a)}else s=e.Cross(r,o),e.CrossToRef(s,r,s);return s.normalize(),s},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)r.push(o[e].subtract(o[0]).add(n));var s=new t(r);return s},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=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,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);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=g;var R=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 n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=R;var T=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=T;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  53677. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  53678. module.exports = BABYLON;
  53679. };