babylon.max.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492
  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.TransformCoordinates = function (vector, transformation) {
  834. var result = Vector3.Zero();
  835. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  836. return result;
  837. };
  838. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  839. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  840. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  841. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  842. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  843. result.x = x / w;
  844. result.y = y / w;
  845. result.z = z / w;
  846. };
  847. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  848. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  849. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  850. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  851. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  852. result.x = rx / rw;
  853. result.y = ry / rw;
  854. result.z = rz / rw;
  855. };
  856. Vector3.TransformNormal = function (vector, transformation) {
  857. var result = Vector3.Zero();
  858. Vector3.TransformNormalToRef(vector, transformation, result);
  859. return result;
  860. };
  861. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  862. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  863. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  864. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  865. };
  866. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  867. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  868. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  869. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  870. };
  871. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  872. var squared = amount * amount;
  873. var cubed = amount * squared;
  874. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  875. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  876. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  877. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  878. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  879. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  880. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  881. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  882. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  883. return new Vector3(x, y, z);
  884. };
  885. Vector3.Clamp = function (value, min, max) {
  886. var x = value.x;
  887. x = (x > max.x) ? max.x : x;
  888. x = (x < min.x) ? min.x : x;
  889. var y = value.y;
  890. y = (y > max.y) ? max.y : y;
  891. y = (y < min.y) ? min.y : y;
  892. var z = value.z;
  893. z = (z > max.z) ? max.z : z;
  894. z = (z < min.z) ? min.z : z;
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  898. var squared = amount * amount;
  899. var cubed = amount * squared;
  900. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  901. var part2 = (-2.0 * cubed) + (3.0 * squared);
  902. var part3 = (cubed - (2.0 * squared)) + amount;
  903. var part4 = cubed - squared;
  904. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  905. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  906. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Lerp = function (start, end, amount) {
  910. var x = start.x + ((end.x - start.x) * amount);
  911. var y = start.y + ((end.y - start.y) * amount);
  912. var z = start.z + ((end.z - start.z) * amount);
  913. return new Vector3(x, y, z);
  914. };
  915. Vector3.Dot = function (left, right) {
  916. return (left.x * right.x + left.y * right.y + left.z * right.z);
  917. };
  918. Vector3.Cross = function (left, right) {
  919. var result = Vector3.Zero();
  920. Vector3.CrossToRef(left, right, result);
  921. return result;
  922. };
  923. Vector3.CrossToRef = function (left, right, result) {
  924. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  925. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  926. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  927. result.copyFrom(Tmp.Vector3[0]);
  928. };
  929. Vector3.Normalize = function (vector) {
  930. var result = Vector3.Zero();
  931. Vector3.NormalizeToRef(vector, result);
  932. return result;
  933. };
  934. Vector3.NormalizeToRef = function (vector, result) {
  935. result.copyFrom(vector);
  936. result.normalize();
  937. };
  938. Vector3.Project = function (vector, world, transform, viewport) {
  939. var cw = viewport.width;
  940. var ch = viewport.height;
  941. var cx = viewport.x;
  942. var cy = viewport.y;
  943. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  944. 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);
  945. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  946. world.multiplyToRef(transform, matrix);
  947. matrix.multiplyToRef(viewportMatrix, matrix);
  948. return Vector3.TransformCoordinates(vector, matrix);
  949. };
  950. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  951. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  952. world.multiplyToRef(transform, matrix);
  953. matrix.invert();
  954. source.x = source.x / viewportWidth * 2 - 1;
  955. source.y = -(source.y / viewportHeight * 2 - 1);
  956. var vector = Vector3.TransformCoordinates(source, matrix);
  957. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  958. if (MathTools.WithinEpsilon(num, 1.0)) {
  959. vector = vector.scale(1.0 / num);
  960. }
  961. return vector;
  962. };
  963. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  964. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  965. world.multiplyToRef(view, matrix);
  966. matrix.multiplyToRef(projection, matrix);
  967. matrix.invert();
  968. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  969. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  970. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  971. if (MathTools.WithinEpsilon(num, 1.0)) {
  972. vector = vector.scale(1.0 / num);
  973. }
  974. return vector;
  975. };
  976. Vector3.Minimize = function (left, right) {
  977. var min = left.clone();
  978. min.MinimizeInPlace(right);
  979. return min;
  980. };
  981. Vector3.Maximize = function (left, right) {
  982. var max = left.clone();
  983. max.MaximizeInPlace(right);
  984. return max;
  985. };
  986. Vector3.Distance = function (value1, value2) {
  987. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  988. };
  989. Vector3.DistanceSquared = function (value1, value2) {
  990. var x = value1.x - value2.x;
  991. var y = value1.y - value2.y;
  992. var z = value1.z - value2.z;
  993. return (x * x) + (y * y) + (z * z);
  994. };
  995. Vector3.Center = function (value1, value2) {
  996. var center = value1.add(value2);
  997. center.scaleInPlace(0.5);
  998. return center;
  999. };
  1000. /**
  1001. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1002. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1003. * to something in order to rotate it from its local system to the given target system.
  1004. */
  1005. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1006. var rotation = Vector3.Zero();
  1007. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1008. return rotation;
  1009. };
  1010. /**
  1011. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1012. */
  1013. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1014. var u = axis1.normalize();
  1015. var w = axis3.normalize();
  1016. // world axis
  1017. var X = Axis.X;
  1018. var Y = Axis.Y;
  1019. // equation unknowns and vars
  1020. var yaw = 0.0;
  1021. var pitch = 0.0;
  1022. var roll = 0.0;
  1023. var x = 0.0;
  1024. var y = 0.0;
  1025. var z = 0.0;
  1026. var t = 0.0;
  1027. var sign = -1.0;
  1028. var nbRevert = 0;
  1029. var cross = Tmp.Vector3[0];
  1030. var dot = 0.0;
  1031. // step 1 : rotation around w
  1032. // Rv3(u) = u1, and u1 belongs to plane xOz
  1033. // Rv3(w) = w1 = w invariant
  1034. var u1 = Tmp.Vector3[1];
  1035. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1036. z = 1.0;
  1037. }
  1038. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1039. x = 1.0;
  1040. }
  1041. else {
  1042. t = w.z / w.x;
  1043. x = -t * Math.sqrt(1 / (1 + t * t));
  1044. z = Math.sqrt(1 / (1 + t * t));
  1045. }
  1046. u1.x = x;
  1047. u1.y = y;
  1048. u1.z = z;
  1049. u1.normalize();
  1050. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1051. cross.normalize();
  1052. if (Vector3.Dot(w, cross) < 0) {
  1053. sign = 1.0;
  1054. }
  1055. dot = Vector3.Dot(u, u1);
  1056. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1057. roll = Math.acos(dot) * sign;
  1058. if (Vector3.Dot(u1, X) < 0) {
  1059. roll = Math.PI + roll;
  1060. u1 = u1.scaleInPlace(-1);
  1061. nbRevert++;
  1062. }
  1063. // step 2 : rotate around u1
  1064. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1065. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1066. var w2 = Tmp.Vector3[2];
  1067. var v2 = Tmp.Vector3[3];
  1068. x = 0.0;
  1069. y = 0.0;
  1070. z = 0.0;
  1071. sign = -1.0;
  1072. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1073. x = 1.0;
  1074. }
  1075. else {
  1076. t = u1.z / u1.x;
  1077. x = -t * Math.sqrt(1 / (1 + t * t));
  1078. z = Math.sqrt(1 / (1 + t * t));
  1079. }
  1080. w2.x = x;
  1081. w2.y = y;
  1082. w2.z = z;
  1083. w2.normalize();
  1084. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1085. v2.normalize();
  1086. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1087. cross.normalize();
  1088. if (Vector3.Dot(u1, cross) < 0) {
  1089. sign = 1.0;
  1090. }
  1091. dot = Vector3.Dot(w, w2);
  1092. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1093. pitch = Math.acos(dot) * sign;
  1094. if (Vector3.Dot(v2, Y) < 0) {
  1095. pitch = Math.PI + pitch;
  1096. nbRevert++;
  1097. }
  1098. // step 3 : rotate around v2
  1099. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1100. sign = -1.0;
  1101. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1102. cross.normalize();
  1103. if (Vector3.Dot(cross, Y) < 0) {
  1104. sign = 1.0;
  1105. }
  1106. dot = Vector3.Dot(u1, X);
  1107. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1108. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1109. if (dot < 0 && nbRevert < 2) {
  1110. yaw = Math.PI + yaw;
  1111. }
  1112. ref.x = pitch;
  1113. ref.y = yaw;
  1114. ref.z = roll;
  1115. };
  1116. return Vector3;
  1117. }());
  1118. BABYLON.Vector3 = Vector3;
  1119. //Vector4 class created for EulerAngle class conversion to Quaternion
  1120. var Vector4 = (function () {
  1121. function Vector4(x, y, z, w) {
  1122. this.x = x;
  1123. this.y = y;
  1124. this.z = z;
  1125. this.w = w;
  1126. }
  1127. Vector4.prototype.toString = function () {
  1128. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1129. };
  1130. Vector4.prototype.getClassName = function () {
  1131. return "Vector4";
  1132. };
  1133. Vector4.prototype.getHashCode = function () {
  1134. var hash = this.x || 0;
  1135. hash = (hash * 397) ^ (this.y || 0);
  1136. hash = (hash * 397) ^ (this.z || 0);
  1137. hash = (hash * 397) ^ (this.w || 0);
  1138. return hash;
  1139. };
  1140. // Operators
  1141. Vector4.prototype.asArray = function () {
  1142. var result = [];
  1143. this.toArray(result, 0);
  1144. return result;
  1145. };
  1146. Vector4.prototype.toArray = function (array, index) {
  1147. if (index === undefined) {
  1148. index = 0;
  1149. }
  1150. array[index] = this.x;
  1151. array[index + 1] = this.y;
  1152. array[index + 2] = this.z;
  1153. array[index + 3] = this.w;
  1154. return this;
  1155. };
  1156. Vector4.prototype.addInPlace = function (otherVector) {
  1157. this.x += otherVector.x;
  1158. this.y += otherVector.y;
  1159. this.z += otherVector.z;
  1160. this.w += otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.add = function (otherVector) {
  1164. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1165. };
  1166. Vector4.prototype.addToRef = function (otherVector, result) {
  1167. result.x = this.x + otherVector.x;
  1168. result.y = this.y + otherVector.y;
  1169. result.z = this.z + otherVector.z;
  1170. result.w = this.w + otherVector.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.subtractInPlace = function (otherVector) {
  1174. this.x -= otherVector.x;
  1175. this.y -= otherVector.y;
  1176. this.z -= otherVector.z;
  1177. this.w -= otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtract = function (otherVector) {
  1181. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1182. };
  1183. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1184. result.x = this.x - otherVector.x;
  1185. result.y = this.y - otherVector.y;
  1186. result.z = this.z - otherVector.z;
  1187. result.w = this.w - otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1191. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1192. };
  1193. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1194. result.x = this.x - x;
  1195. result.y = this.y - y;
  1196. result.z = this.z - z;
  1197. result.w = this.w - w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.negate = function () {
  1201. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1202. };
  1203. Vector4.prototype.scaleInPlace = function (scale) {
  1204. this.x *= scale;
  1205. this.y *= scale;
  1206. this.z *= scale;
  1207. this.w *= scale;
  1208. return this;
  1209. };
  1210. Vector4.prototype.scale = function (scale) {
  1211. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1212. };
  1213. Vector4.prototype.scaleToRef = function (scale, result) {
  1214. result.x = this.x * scale;
  1215. result.y = this.y * scale;
  1216. result.z = this.z * scale;
  1217. result.w = this.w * scale;
  1218. };
  1219. Vector4.prototype.equals = function (otherVector) {
  1220. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1221. };
  1222. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1223. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1224. return otherVector
  1225. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1226. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1227. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1228. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1229. };
  1230. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1231. return this.x === x && this.y === y && this.z === z && this.w === w;
  1232. };
  1233. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1234. this.x *= otherVector.x;
  1235. this.y *= otherVector.y;
  1236. this.z *= otherVector.z;
  1237. this.w *= otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiply = function (otherVector) {
  1241. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1242. };
  1243. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1244. result.x = this.x * otherVector.x;
  1245. result.y = this.y * otherVector.y;
  1246. result.z = this.z * otherVector.z;
  1247. result.w = this.w * otherVector.w;
  1248. return this;
  1249. };
  1250. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1251. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1252. };
  1253. Vector4.prototype.divide = function (otherVector) {
  1254. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1255. };
  1256. Vector4.prototype.divideToRef = function (otherVector, result) {
  1257. result.x = this.x / otherVector.x;
  1258. result.y = this.y / otherVector.y;
  1259. result.z = this.z / otherVector.z;
  1260. result.w = this.w / otherVector.w;
  1261. return this;
  1262. };
  1263. Vector4.prototype.MinimizeInPlace = function (other) {
  1264. if (other.x < this.x)
  1265. this.x = other.x;
  1266. if (other.y < this.y)
  1267. this.y = other.y;
  1268. if (other.z < this.z)
  1269. this.z = other.z;
  1270. if (other.w < this.w)
  1271. this.w = other.w;
  1272. return this;
  1273. };
  1274. Vector4.prototype.MaximizeInPlace = function (other) {
  1275. if (other.x > this.x)
  1276. this.x = other.x;
  1277. if (other.y > this.y)
  1278. this.y = other.y;
  1279. if (other.z > this.z)
  1280. this.z = other.z;
  1281. if (other.w > this.w)
  1282. this.w = other.w;
  1283. return this;
  1284. };
  1285. // Properties
  1286. Vector4.prototype.length = function () {
  1287. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1288. };
  1289. Vector4.prototype.lengthSquared = function () {
  1290. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1291. };
  1292. // Methods
  1293. Vector4.prototype.normalize = function () {
  1294. var len = this.length();
  1295. if (len === 0)
  1296. return this;
  1297. var num = 1.0 / len;
  1298. this.x *= num;
  1299. this.y *= num;
  1300. this.z *= num;
  1301. this.w *= num;
  1302. return this;
  1303. };
  1304. Vector4.prototype.toVector3 = function () {
  1305. return new Vector3(this.x, this.y, this.z);
  1306. };
  1307. Vector4.prototype.clone = function () {
  1308. return new Vector4(this.x, this.y, this.z, this.w);
  1309. };
  1310. Vector4.prototype.copyFrom = function (source) {
  1311. this.x = source.x;
  1312. this.y = source.y;
  1313. this.z = source.z;
  1314. this.w = source.w;
  1315. return this;
  1316. };
  1317. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1318. this.x = x;
  1319. this.y = y;
  1320. this.z = z;
  1321. this.w = w;
  1322. return this;
  1323. };
  1324. // Statics
  1325. Vector4.FromArray = function (array, offset) {
  1326. if (!offset) {
  1327. offset = 0;
  1328. }
  1329. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1330. };
  1331. Vector4.FromArrayToRef = function (array, offset, result) {
  1332. result.x = array[offset];
  1333. result.y = array[offset + 1];
  1334. result.z = array[offset + 2];
  1335. result.w = array[offset + 3];
  1336. };
  1337. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. result.w = array[offset + 3];
  1342. };
  1343. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1344. result.x = x;
  1345. result.y = y;
  1346. result.z = z;
  1347. result.w = w;
  1348. };
  1349. Vector4.Zero = function () {
  1350. return new Vector4(0, 0, 0, 0);
  1351. };
  1352. Vector4.Normalize = function (vector) {
  1353. var result = Vector4.Zero();
  1354. Vector4.NormalizeToRef(vector, result);
  1355. return result;
  1356. };
  1357. Vector4.NormalizeToRef = function (vector, result) {
  1358. result.copyFrom(vector);
  1359. result.normalize();
  1360. };
  1361. Vector4.Minimize = function (left, right) {
  1362. var min = left.clone();
  1363. min.MinimizeInPlace(right);
  1364. return min;
  1365. };
  1366. Vector4.Maximize = function (left, right) {
  1367. var max = left.clone();
  1368. max.MaximizeInPlace(right);
  1369. return max;
  1370. };
  1371. Vector4.Distance = function (value1, value2) {
  1372. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1373. };
  1374. Vector4.DistanceSquared = function (value1, value2) {
  1375. var x = value1.x - value2.x;
  1376. var y = value1.y - value2.y;
  1377. var z = value1.z - value2.z;
  1378. var w = value1.w - value2.w;
  1379. return (x * x) + (y * y) + (z * z) + (w * w);
  1380. };
  1381. Vector4.Center = function (value1, value2) {
  1382. var center = value1.add(value2);
  1383. center.scaleInPlace(0.5);
  1384. return center;
  1385. };
  1386. return Vector4;
  1387. }());
  1388. BABYLON.Vector4 = Vector4;
  1389. var Size = (function () {
  1390. function Size(width, height) {
  1391. this.width = width;
  1392. this.height = height;
  1393. }
  1394. Size.prototype.toString = function () {
  1395. return "{W: " + this.width + ", H: " + this.height + "}";
  1396. };
  1397. Size.prototype.getClassName = function () {
  1398. return "Size";
  1399. };
  1400. Size.prototype.getHashCode = function () {
  1401. var hash = this.width || 0;
  1402. hash = (hash * 397) ^ (this.height || 0);
  1403. return hash;
  1404. };
  1405. Size.prototype.copyFrom = function (src) {
  1406. this.width = src.width;
  1407. this.height = src.height;
  1408. };
  1409. Size.prototype.copyFromFloats = function (width, height) {
  1410. this.width = width;
  1411. this.height = height;
  1412. };
  1413. Size.prototype.multiplyByFloats = function (w, h) {
  1414. return new Size(this.width * w, this.height * h);
  1415. };
  1416. Size.prototype.clone = function () {
  1417. return new Size(this.width, this.height);
  1418. };
  1419. Size.prototype.equals = function (other) {
  1420. if (!other) {
  1421. return false;
  1422. }
  1423. return (this.width === other.width) && (this.height === other.height);
  1424. };
  1425. Object.defineProperty(Size.prototype, "surface", {
  1426. get: function () {
  1427. return this.width * this.height;
  1428. },
  1429. enumerable: true,
  1430. configurable: true
  1431. });
  1432. Size.Zero = function () {
  1433. return new Size(0, 0);
  1434. };
  1435. Size.prototype.add = function (otherSize) {
  1436. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1437. return r;
  1438. };
  1439. Size.prototype.substract = function (otherSize) {
  1440. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1441. return r;
  1442. };
  1443. Size.Lerp = function (start, end, amount) {
  1444. var w = start.width + ((end.width - start.width) * amount);
  1445. var h = start.height + ((end.height - start.height) * amount);
  1446. return new Size(w, h);
  1447. };
  1448. return Size;
  1449. }());
  1450. BABYLON.Size = Size;
  1451. var Quaternion = (function () {
  1452. function Quaternion(x, y, z, w) {
  1453. if (x === void 0) { x = 0; }
  1454. if (y === void 0) { y = 0; }
  1455. if (z === void 0) { z = 0; }
  1456. if (w === void 0) { w = 1; }
  1457. this.x = x;
  1458. this.y = y;
  1459. this.z = z;
  1460. this.w = w;
  1461. }
  1462. Quaternion.prototype.toString = function () {
  1463. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1464. };
  1465. Quaternion.prototype.getClassName = function () {
  1466. return "Quaternion";
  1467. };
  1468. Quaternion.prototype.getHashCode = function () {
  1469. var hash = this.x || 0;
  1470. hash = (hash * 397) ^ (this.y || 0);
  1471. hash = (hash * 397) ^ (this.z || 0);
  1472. hash = (hash * 397) ^ (this.w || 0);
  1473. return hash;
  1474. };
  1475. Quaternion.prototype.asArray = function () {
  1476. return [this.x, this.y, this.z, this.w];
  1477. };
  1478. Quaternion.prototype.equals = function (otherQuaternion) {
  1479. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1480. };
  1481. Quaternion.prototype.clone = function () {
  1482. return new Quaternion(this.x, this.y, this.z, this.w);
  1483. };
  1484. Quaternion.prototype.copyFrom = function (other) {
  1485. this.x = other.x;
  1486. this.y = other.y;
  1487. this.z = other.z;
  1488. this.w = other.w;
  1489. return this;
  1490. };
  1491. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. this.w = w;
  1496. return this;
  1497. };
  1498. Quaternion.prototype.add = function (other) {
  1499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1500. };
  1501. Quaternion.prototype.subtract = function (other) {
  1502. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1503. };
  1504. Quaternion.prototype.scale = function (value) {
  1505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1506. };
  1507. Quaternion.prototype.multiply = function (q1) {
  1508. var result = new Quaternion(0, 0, 0, 1.0);
  1509. this.multiplyToRef(q1, result);
  1510. return result;
  1511. };
  1512. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1513. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1514. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1515. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1516. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1517. result.copyFromFloats(x, y, z, w);
  1518. return this;
  1519. };
  1520. Quaternion.prototype.multiplyInPlace = function (q1) {
  1521. this.multiplyToRef(q1, this);
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugateToRef = function (ref) {
  1525. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1526. return this;
  1527. };
  1528. Quaternion.prototype.conjugateInPlace = function () {
  1529. this.x *= -1;
  1530. this.y *= -1;
  1531. this.z *= -1;
  1532. return this;
  1533. };
  1534. Quaternion.prototype.conjugate = function () {
  1535. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1536. return result;
  1537. };
  1538. Quaternion.prototype.length = function () {
  1539. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1540. };
  1541. Quaternion.prototype.normalize = function () {
  1542. var length = 1.0 / this.length();
  1543. this.x *= length;
  1544. this.y *= length;
  1545. this.z *= length;
  1546. this.w *= length;
  1547. return this;
  1548. };
  1549. Quaternion.prototype.toEulerAngles = function (order) {
  1550. if (order === void 0) { order = "YZX"; }
  1551. var result = Vector3.Zero();
  1552. this.toEulerAnglesToRef(result, order);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1556. if (order === void 0) { order = "YZX"; }
  1557. var heading, attitude, bank;
  1558. var x = this.x, y = this.y, z = this.z, w = this.w;
  1559. switch (order) {
  1560. case "YZX":
  1561. var test = x * y + z * w;
  1562. if (test > 0.499) {
  1563. heading = 2 * Math.atan2(x, w);
  1564. attitude = Math.PI / 2;
  1565. bank = 0;
  1566. }
  1567. if (test < -0.499) {
  1568. heading = -2 * Math.atan2(x, w);
  1569. attitude = -Math.PI / 2;
  1570. bank = 0;
  1571. }
  1572. if (isNaN(heading)) {
  1573. var sqx = x * x;
  1574. var sqy = y * y;
  1575. var sqz = z * z;
  1576. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1577. attitude = Math.asin(2 * test); // attitude
  1578. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1579. }
  1580. break;
  1581. default:
  1582. throw new Error("Euler order " + order + " not supported yet.");
  1583. }
  1584. result.y = heading;
  1585. result.z = attitude;
  1586. result.x = bank;
  1587. return this;
  1588. };
  1589. ;
  1590. Quaternion.prototype.toRotationMatrix = function (result) {
  1591. var xx = this.x * this.x;
  1592. var yy = this.y * this.y;
  1593. var zz = this.z * this.z;
  1594. var xy = this.x * this.y;
  1595. var zw = this.z * this.w;
  1596. var zx = this.z * this.x;
  1597. var yw = this.y * this.w;
  1598. var yz = this.y * this.z;
  1599. var xw = this.x * this.w;
  1600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1601. result.m[1] = 2.0 * (xy + zw);
  1602. result.m[2] = 2.0 * (zx - yw);
  1603. result.m[3] = 0;
  1604. result.m[4] = 2.0 * (xy - zw);
  1605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1606. result.m[6] = 2.0 * (yz + xw);
  1607. result.m[7] = 0;
  1608. result.m[8] = 2.0 * (zx + yw);
  1609. result.m[9] = 2.0 * (yz - xw);
  1610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1611. result.m[11] = 0;
  1612. result.m[12] = 0;
  1613. result.m[13] = 0;
  1614. result.m[14] = 0;
  1615. result.m[15] = 1.0;
  1616. return this;
  1617. };
  1618. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1619. Quaternion.FromRotationMatrixToRef(matrix, this);
  1620. return this;
  1621. };
  1622. // Statics
  1623. Quaternion.FromRotationMatrix = function (matrix) {
  1624. var result = new Quaternion();
  1625. Quaternion.FromRotationMatrixToRef(matrix, result);
  1626. return result;
  1627. };
  1628. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1629. var data = matrix.m;
  1630. var m11 = data[0], m12 = data[4], m13 = data[8];
  1631. var m21 = data[1], m22 = data[5], m23 = data[9];
  1632. var m31 = data[2], m32 = data[6], m33 = data[10];
  1633. var trace = m11 + m22 + m33;
  1634. var s;
  1635. if (trace > 0) {
  1636. s = 0.5 / Math.sqrt(trace + 1.0);
  1637. result.w = 0.25 / s;
  1638. result.x = (m32 - m23) * s;
  1639. result.y = (m13 - m31) * s;
  1640. result.z = (m21 - m12) * s;
  1641. }
  1642. else if (m11 > m22 && m11 > m33) {
  1643. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1644. result.w = (m32 - m23) / s;
  1645. result.x = 0.25 * s;
  1646. result.y = (m12 + m21) / s;
  1647. result.z = (m13 + m31) / s;
  1648. }
  1649. else if (m22 > m33) {
  1650. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1651. result.w = (m13 - m31) / s;
  1652. result.x = (m12 + m21) / s;
  1653. result.y = 0.25 * s;
  1654. result.z = (m23 + m32) / s;
  1655. }
  1656. else {
  1657. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1658. result.w = (m21 - m12) / s;
  1659. result.x = (m13 + m31) / s;
  1660. result.y = (m23 + m32) / s;
  1661. result.z = 0.25 * s;
  1662. }
  1663. };
  1664. Quaternion.Inverse = function (q) {
  1665. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1666. };
  1667. Quaternion.Identity = function () {
  1668. return new Quaternion(0, 0, 0, 1);
  1669. };
  1670. Quaternion.RotationAxis = function (axis, angle) {
  1671. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1672. };
  1673. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1674. var sin = Math.sin(angle / 2);
  1675. axis.normalize();
  1676. result.w = Math.cos(angle / 2);
  1677. result.x = axis.x * sin;
  1678. result.y = axis.y * sin;
  1679. result.z = axis.z * sin;
  1680. return result;
  1681. };
  1682. Quaternion.FromArray = function (array, offset) {
  1683. if (!offset) {
  1684. offset = 0;
  1685. }
  1686. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1687. };
  1688. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1689. var q = new Quaternion();
  1690. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1691. return q;
  1692. };
  1693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1695. var halfRoll = roll * 0.5;
  1696. var halfPitch = pitch * 0.5;
  1697. var halfYaw = yaw * 0.5;
  1698. var sinRoll = Math.sin(halfRoll);
  1699. var cosRoll = Math.cos(halfRoll);
  1700. var sinPitch = Math.sin(halfPitch);
  1701. var cosPitch = Math.cos(halfPitch);
  1702. var sinYaw = Math.sin(halfYaw);
  1703. var cosYaw = Math.cos(halfYaw);
  1704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1708. };
  1709. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1710. var result = new Quaternion();
  1711. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1712. return result;
  1713. };
  1714. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1715. // Produces a quaternion from Euler angles in the z-x-z orientation
  1716. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1717. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1718. var halfBeta = beta * 0.5;
  1719. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1720. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1721. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1722. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1723. };
  1724. Quaternion.Slerp = function (left, right, amount) {
  1725. var num2;
  1726. var num3;
  1727. var num = amount;
  1728. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1729. var flag = false;
  1730. if (num4 < 0) {
  1731. flag = true;
  1732. num4 = -num4;
  1733. }
  1734. if (num4 > 0.999999) {
  1735. num3 = 1 - num;
  1736. num2 = flag ? -num : num;
  1737. }
  1738. else {
  1739. var num5 = Math.acos(num4);
  1740. var num6 = (1.0 / Math.sin(num5));
  1741. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1742. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1743. }
  1744. 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));
  1745. };
  1746. return Quaternion;
  1747. }());
  1748. BABYLON.Quaternion = Quaternion;
  1749. var Matrix = (function () {
  1750. function Matrix() {
  1751. this.m = new Float32Array(16);
  1752. }
  1753. // Properties
  1754. Matrix.prototype.isIdentity = function () {
  1755. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1756. return false;
  1757. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1758. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1759. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1760. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1761. return false;
  1762. return true;
  1763. };
  1764. Matrix.prototype.determinant = function () {
  1765. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1766. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1767. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1768. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1769. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1770. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1771. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1772. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1773. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1774. };
  1775. // Methods
  1776. Matrix.prototype.toArray = function () {
  1777. return this.m;
  1778. };
  1779. Matrix.prototype.asArray = function () {
  1780. return this.toArray();
  1781. };
  1782. Matrix.prototype.invert = function () {
  1783. this.invertToRef(this);
  1784. return this;
  1785. };
  1786. Matrix.prototype.reset = function () {
  1787. for (var index = 0; index < 16; index++) {
  1788. this.m[index] = 0;
  1789. }
  1790. return this;
  1791. };
  1792. Matrix.prototype.add = function (other) {
  1793. var result = new Matrix();
  1794. this.addToRef(other, result);
  1795. return result;
  1796. };
  1797. Matrix.prototype.addToRef = function (other, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = this.m[index] + other.m[index];
  1800. }
  1801. return this;
  1802. };
  1803. Matrix.prototype.addToSelf = function (other) {
  1804. for (var index = 0; index < 16; index++) {
  1805. this.m[index] += other.m[index];
  1806. }
  1807. return this;
  1808. };
  1809. Matrix.prototype.invertToRef = function (other) {
  1810. var l1 = this.m[0];
  1811. var l2 = this.m[1];
  1812. var l3 = this.m[2];
  1813. var l4 = this.m[3];
  1814. var l5 = this.m[4];
  1815. var l6 = this.m[5];
  1816. var l7 = this.m[6];
  1817. var l8 = this.m[7];
  1818. var l9 = this.m[8];
  1819. var l10 = this.m[9];
  1820. var l11 = this.m[10];
  1821. var l12 = this.m[11];
  1822. var l13 = this.m[12];
  1823. var l14 = this.m[13];
  1824. var l15 = this.m[14];
  1825. var l16 = this.m[15];
  1826. var l17 = (l11 * l16) - (l12 * l15);
  1827. var l18 = (l10 * l16) - (l12 * l14);
  1828. var l19 = (l10 * l15) - (l11 * l14);
  1829. var l20 = (l9 * l16) - (l12 * l13);
  1830. var l21 = (l9 * l15) - (l11 * l13);
  1831. var l22 = (l9 * l14) - (l10 * l13);
  1832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1837. var l28 = (l7 * l16) - (l8 * l15);
  1838. var l29 = (l6 * l16) - (l8 * l14);
  1839. var l30 = (l6 * l15) - (l7 * l14);
  1840. var l31 = (l5 * l16) - (l8 * l13);
  1841. var l32 = (l5 * l15) - (l7 * l13);
  1842. var l33 = (l5 * l14) - (l6 * l13);
  1843. var l34 = (l7 * l12) - (l8 * l11);
  1844. var l35 = (l6 * l12) - (l8 * l10);
  1845. var l36 = (l6 * l11) - (l7 * l10);
  1846. var l37 = (l5 * l12) - (l8 * l9);
  1847. var l38 = (l5 * l11) - (l7 * l9);
  1848. var l39 = (l5 * l10) - (l6 * l9);
  1849. other.m[0] = l23 * l27;
  1850. other.m[4] = l24 * l27;
  1851. other.m[8] = l25 * l27;
  1852. other.m[12] = l26 * l27;
  1853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1865. return this;
  1866. };
  1867. Matrix.prototype.setTranslation = function (vector3) {
  1868. this.m[12] = vector3.x;
  1869. this.m[13] = vector3.y;
  1870. this.m[14] = vector3.z;
  1871. return this;
  1872. };
  1873. Matrix.prototype.getTranslation = function () {
  1874. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1875. };
  1876. Matrix.prototype.multiply = function (other) {
  1877. var result = new Matrix();
  1878. this.multiplyToRef(other, result);
  1879. return result;
  1880. };
  1881. Matrix.prototype.copyFrom = function (other) {
  1882. for (var index = 0; index < 16; index++) {
  1883. this.m[index] = other.m[index];
  1884. }
  1885. return this;
  1886. };
  1887. Matrix.prototype.copyToArray = function (array, offset) {
  1888. if (offset === void 0) { offset = 0; }
  1889. for (var index = 0; index < 16; index++) {
  1890. array[offset + index] = this.m[index];
  1891. }
  1892. return this;
  1893. };
  1894. Matrix.prototype.multiplyToRef = function (other, result) {
  1895. this.multiplyToArray(other, result.m, 0);
  1896. return this;
  1897. };
  1898. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1899. var tm0 = this.m[0];
  1900. var tm1 = this.m[1];
  1901. var tm2 = this.m[2];
  1902. var tm3 = this.m[3];
  1903. var tm4 = this.m[4];
  1904. var tm5 = this.m[5];
  1905. var tm6 = this.m[6];
  1906. var tm7 = this.m[7];
  1907. var tm8 = this.m[8];
  1908. var tm9 = this.m[9];
  1909. var tm10 = this.m[10];
  1910. var tm11 = this.m[11];
  1911. var tm12 = this.m[12];
  1912. var tm13 = this.m[13];
  1913. var tm14 = this.m[14];
  1914. var tm15 = this.m[15];
  1915. var om0 = other.m[0];
  1916. var om1 = other.m[1];
  1917. var om2 = other.m[2];
  1918. var om3 = other.m[3];
  1919. var om4 = other.m[4];
  1920. var om5 = other.m[5];
  1921. var om6 = other.m[6];
  1922. var om7 = other.m[7];
  1923. var om8 = other.m[8];
  1924. var om9 = other.m[9];
  1925. var om10 = other.m[10];
  1926. var om11 = other.m[11];
  1927. var om12 = other.m[12];
  1928. var om13 = other.m[13];
  1929. var om14 = other.m[14];
  1930. var om15 = other.m[15];
  1931. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1932. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1933. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1934. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1935. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1936. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1937. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1938. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1939. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1940. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1941. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1942. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1943. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1944. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1945. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1946. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1947. return this;
  1948. };
  1949. Matrix.prototype.equals = function (value) {
  1950. return value &&
  1951. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1952. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1953. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1954. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1955. };
  1956. Matrix.prototype.clone = function () {
  1957. 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]);
  1958. };
  1959. Matrix.prototype.getClassName = function () {
  1960. return "Matrix";
  1961. };
  1962. Matrix.prototype.getHashCode = function () {
  1963. var hash = this.m[0] || 0;
  1964. for (var i = 1; i < 16; i++) {
  1965. hash = (hash * 397) ^ (this.m[i] || 0);
  1966. }
  1967. return hash;
  1968. };
  1969. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1970. translation.x = this.m[12];
  1971. translation.y = this.m[13];
  1972. translation.z = this.m[14];
  1973. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1974. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1975. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1976. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1977. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1978. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1979. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1980. rotation.x = 0;
  1981. rotation.y = 0;
  1982. rotation.z = 0;
  1983. rotation.w = 1;
  1984. return false;
  1985. }
  1986. 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]);
  1987. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  1988. return true;
  1989. };
  1990. // Statics
  1991. Matrix.FromArray = function (array, offset) {
  1992. var result = new Matrix();
  1993. if (!offset) {
  1994. offset = 0;
  1995. }
  1996. Matrix.FromArrayToRef(array, offset, result);
  1997. return result;
  1998. };
  1999. Matrix.FromArrayToRef = function (array, offset, result) {
  2000. for (var index = 0; index < 16; index++) {
  2001. result.m[index] = array[index + offset];
  2002. }
  2003. };
  2004. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2005. for (var index = 0; index < 16; index++) {
  2006. result.m[index] = array[index + offset] * scale;
  2007. }
  2008. };
  2009. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2010. result.m[0] = initialM11;
  2011. result.m[1] = initialM12;
  2012. result.m[2] = initialM13;
  2013. result.m[3] = initialM14;
  2014. result.m[4] = initialM21;
  2015. result.m[5] = initialM22;
  2016. result.m[6] = initialM23;
  2017. result.m[7] = initialM24;
  2018. result.m[8] = initialM31;
  2019. result.m[9] = initialM32;
  2020. result.m[10] = initialM33;
  2021. result.m[11] = initialM34;
  2022. result.m[12] = initialM41;
  2023. result.m[13] = initialM42;
  2024. result.m[14] = initialM43;
  2025. result.m[15] = initialM44;
  2026. };
  2027. Matrix.prototype.getRow = function (index) {
  2028. if (index < 0 || index > 3) {
  2029. return null;
  2030. }
  2031. var i = index * 4;
  2032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2033. };
  2034. Matrix.prototype.setRow = function (index, row) {
  2035. if (index < 0 || index > 3) {
  2036. return this;
  2037. }
  2038. var i = index * 4;
  2039. this.m[i + 0] = row.x;
  2040. this.m[i + 1] = row.y;
  2041. this.m[i + 2] = row.z;
  2042. this.m[i + 3] = row.w;
  2043. return this;
  2044. };
  2045. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2046. var result = new Matrix();
  2047. result.m[0] = initialM11;
  2048. result.m[1] = initialM12;
  2049. result.m[2] = initialM13;
  2050. result.m[3] = initialM14;
  2051. result.m[4] = initialM21;
  2052. result.m[5] = initialM22;
  2053. result.m[6] = initialM23;
  2054. result.m[7] = initialM24;
  2055. result.m[8] = initialM31;
  2056. result.m[9] = initialM32;
  2057. result.m[10] = initialM33;
  2058. result.m[11] = initialM34;
  2059. result.m[12] = initialM41;
  2060. result.m[13] = initialM42;
  2061. result.m[14] = initialM43;
  2062. result.m[15] = initialM44;
  2063. return result;
  2064. };
  2065. Matrix.Compose = function (scale, rotation, translation) {
  2066. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2067. var rotationMatrix = Matrix.Identity();
  2068. rotation.toRotationMatrix(rotationMatrix);
  2069. result = result.multiply(rotationMatrix);
  2070. result.setTranslation(translation);
  2071. return result;
  2072. };
  2073. Matrix.Identity = function () {
  2074. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2075. };
  2076. Matrix.IdentityToRef = function (result) {
  2077. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2078. };
  2079. Matrix.Zero = function () {
  2080. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2081. };
  2082. Matrix.RotationX = function (angle) {
  2083. var result = new Matrix();
  2084. Matrix.RotationXToRef(angle, result);
  2085. return result;
  2086. };
  2087. Matrix.Invert = function (source) {
  2088. var result = new Matrix();
  2089. source.invertToRef(result);
  2090. return result;
  2091. };
  2092. Matrix.RotationXToRef = function (angle, result) {
  2093. var s = Math.sin(angle);
  2094. var c = Math.cos(angle);
  2095. result.m[0] = 1.0;
  2096. result.m[15] = 1.0;
  2097. result.m[5] = c;
  2098. result.m[10] = c;
  2099. result.m[9] = -s;
  2100. result.m[6] = s;
  2101. result.m[1] = 0;
  2102. result.m[2] = 0;
  2103. result.m[3] = 0;
  2104. result.m[4] = 0;
  2105. result.m[7] = 0;
  2106. result.m[8] = 0;
  2107. result.m[11] = 0;
  2108. result.m[12] = 0;
  2109. result.m[13] = 0;
  2110. result.m[14] = 0;
  2111. };
  2112. Matrix.RotationY = function (angle) {
  2113. var result = new Matrix();
  2114. Matrix.RotationYToRef(angle, result);
  2115. return result;
  2116. };
  2117. Matrix.RotationYToRef = function (angle, result) {
  2118. var s = Math.sin(angle);
  2119. var c = Math.cos(angle);
  2120. result.m[5] = 1.0;
  2121. result.m[15] = 1.0;
  2122. result.m[0] = c;
  2123. result.m[2] = -s;
  2124. result.m[8] = s;
  2125. result.m[10] = c;
  2126. result.m[1] = 0;
  2127. result.m[3] = 0;
  2128. result.m[4] = 0;
  2129. result.m[6] = 0;
  2130. result.m[7] = 0;
  2131. result.m[9] = 0;
  2132. result.m[11] = 0;
  2133. result.m[12] = 0;
  2134. result.m[13] = 0;
  2135. result.m[14] = 0;
  2136. };
  2137. Matrix.RotationZ = function (angle) {
  2138. var result = new Matrix();
  2139. Matrix.RotationZToRef(angle, result);
  2140. return result;
  2141. };
  2142. Matrix.RotationZToRef = function (angle, result) {
  2143. var s = Math.sin(angle);
  2144. var c = Math.cos(angle);
  2145. result.m[10] = 1.0;
  2146. result.m[15] = 1.0;
  2147. result.m[0] = c;
  2148. result.m[1] = s;
  2149. result.m[4] = -s;
  2150. result.m[5] = c;
  2151. result.m[2] = 0;
  2152. result.m[3] = 0;
  2153. result.m[6] = 0;
  2154. result.m[7] = 0;
  2155. result.m[8] = 0;
  2156. result.m[9] = 0;
  2157. result.m[11] = 0;
  2158. result.m[12] = 0;
  2159. result.m[13] = 0;
  2160. result.m[14] = 0;
  2161. };
  2162. Matrix.RotationAxis = function (axis, angle) {
  2163. var result = Matrix.Zero();
  2164. Matrix.RotationAxisToRef(axis, angle, result);
  2165. return result;
  2166. };
  2167. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2168. var s = Math.sin(-angle);
  2169. var c = Math.cos(-angle);
  2170. var c1 = 1 - c;
  2171. axis.normalize();
  2172. result.m[0] = (axis.x * axis.x) * c1 + c;
  2173. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2174. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2175. result.m[3] = 0.0;
  2176. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2177. result.m[5] = (axis.y * axis.y) * c1 + c;
  2178. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2179. result.m[7] = 0.0;
  2180. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2181. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2182. result.m[10] = (axis.z * axis.z) * c1 + c;
  2183. result.m[11] = 0.0;
  2184. result.m[15] = 1.0;
  2185. };
  2186. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2187. var result = new Matrix();
  2188. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2189. return result;
  2190. };
  2191. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2192. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2193. this._tempQuaternion.toRotationMatrix(result);
  2194. };
  2195. Matrix.Scaling = function (x, y, z) {
  2196. var result = Matrix.Zero();
  2197. Matrix.ScalingToRef(x, y, z, result);
  2198. return result;
  2199. };
  2200. Matrix.ScalingToRef = function (x, y, z, result) {
  2201. result.m[0] = x;
  2202. result.m[1] = 0;
  2203. result.m[2] = 0;
  2204. result.m[3] = 0;
  2205. result.m[4] = 0;
  2206. result.m[5] = y;
  2207. result.m[6] = 0;
  2208. result.m[7] = 0;
  2209. result.m[8] = 0;
  2210. result.m[9] = 0;
  2211. result.m[10] = z;
  2212. result.m[11] = 0;
  2213. result.m[12] = 0;
  2214. result.m[13] = 0;
  2215. result.m[14] = 0;
  2216. result.m[15] = 1.0;
  2217. };
  2218. Matrix.Translation = function (x, y, z) {
  2219. var result = Matrix.Identity();
  2220. Matrix.TranslationToRef(x, y, z, result);
  2221. return result;
  2222. };
  2223. Matrix.TranslationToRef = function (x, y, z, result) {
  2224. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2225. };
  2226. Matrix.Lerp = function (startValue, endValue, gradient) {
  2227. var result = Matrix.Zero();
  2228. for (var index = 0; index < 16; index++) {
  2229. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2230. }
  2231. return result;
  2232. };
  2233. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2234. var startScale = new Vector3(0, 0, 0);
  2235. var startRotation = new Quaternion();
  2236. var startTranslation = new Vector3(0, 0, 0);
  2237. startValue.decompose(startScale, startRotation, startTranslation);
  2238. var endScale = new Vector3(0, 0, 0);
  2239. var endRotation = new Quaternion();
  2240. var endTranslation = new Vector3(0, 0, 0);
  2241. endValue.decompose(endScale, endRotation, endTranslation);
  2242. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2243. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2244. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2245. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2246. };
  2247. Matrix.LookAtLH = function (eye, target, up) {
  2248. var result = Matrix.Zero();
  2249. Matrix.LookAtLHToRef(eye, target, up, result);
  2250. return result;
  2251. };
  2252. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2253. // Z axis
  2254. target.subtractToRef(eye, this._zAxis);
  2255. this._zAxis.normalize();
  2256. // X axis
  2257. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2258. if (this._xAxis.lengthSquared() === 0) {
  2259. this._xAxis.x = 1.0;
  2260. }
  2261. else {
  2262. this._xAxis.normalize();
  2263. }
  2264. // Y axis
  2265. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2266. this._yAxis.normalize();
  2267. // Eye angles
  2268. var ex = -Vector3.Dot(this._xAxis, eye);
  2269. var ey = -Vector3.Dot(this._yAxis, eye);
  2270. var ez = -Vector3.Dot(this._zAxis, eye);
  2271. 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);
  2272. };
  2273. Matrix.LookAtRH = function (eye, target, up) {
  2274. var result = Matrix.Zero();
  2275. Matrix.LookAtRHToRef(eye, target, up, result);
  2276. return result;
  2277. };
  2278. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2279. // Z axis
  2280. eye.subtractToRef(target, this._zAxis);
  2281. this._zAxis.normalize();
  2282. // X axis
  2283. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2284. if (this._xAxis.lengthSquared() === 0) {
  2285. this._xAxis.x = 1.0;
  2286. }
  2287. else {
  2288. this._xAxis.normalize();
  2289. }
  2290. // Y axis
  2291. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2292. this._yAxis.normalize();
  2293. // Eye angles
  2294. var ex = -Vector3.Dot(this._xAxis, eye);
  2295. var ey = -Vector3.Dot(this._yAxis, eye);
  2296. var ez = -Vector3.Dot(this._zAxis, eye);
  2297. 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);
  2298. };
  2299. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2300. var matrix = Matrix.Zero();
  2301. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2302. return matrix;
  2303. };
  2304. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2305. var hw = 2.0 / width;
  2306. var hh = 2.0 / height;
  2307. var id = 1.0 / (zfar - znear);
  2308. var nid = znear / (znear - zfar);
  2309. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2310. };
  2311. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2312. var matrix = Matrix.Zero();
  2313. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2314. return matrix;
  2315. };
  2316. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2317. result.m[0] = 2.0 / (right - left);
  2318. result.m[1] = result.m[2] = result.m[3] = 0;
  2319. result.m[5] = 2.0 / (top - bottom);
  2320. result.m[4] = result.m[6] = result.m[7] = 0;
  2321. result.m[10] = 1.0 / (zfar - znear);
  2322. result.m[8] = result.m[9] = result.m[11] = 0;
  2323. result.m[12] = (left + right) / (left - right);
  2324. result.m[13] = (top + bottom) / (bottom - top);
  2325. result.m[14] = -znear / (zfar - znear);
  2326. result.m[15] = 1.0;
  2327. };
  2328. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2329. var matrix = Matrix.Zero();
  2330. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2331. return matrix;
  2332. };
  2333. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2334. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2335. result.m[10] *= -1.0;
  2336. };
  2337. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2338. var matrix = Matrix.Zero();
  2339. matrix.m[0] = (2.0 * znear) / width;
  2340. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2341. matrix.m[5] = (2.0 * znear) / height;
  2342. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2343. matrix.m[10] = -zfar / (znear - zfar);
  2344. matrix.m[8] = matrix.m[9] = 0.0;
  2345. matrix.m[11] = 1.0;
  2346. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2347. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2348. return matrix;
  2349. };
  2350. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2351. var matrix = Matrix.Zero();
  2352. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2353. return matrix;
  2354. };
  2355. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2356. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2357. var tan = 1.0 / (Math.tan(fov * 0.5));
  2358. if (isVerticalFovFixed) {
  2359. result.m[0] = tan / aspect;
  2360. }
  2361. else {
  2362. result.m[0] = tan;
  2363. }
  2364. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2365. if (isVerticalFovFixed) {
  2366. result.m[5] = tan;
  2367. }
  2368. else {
  2369. result.m[5] = tan * aspect;
  2370. }
  2371. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2372. result.m[8] = result.m[9] = 0.0;
  2373. result.m[10] = zfar / (zfar - znear);
  2374. result.m[11] = 1.0;
  2375. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2376. result.m[14] = -(znear * zfar) / (zfar - znear);
  2377. };
  2378. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2379. var matrix = Matrix.Zero();
  2380. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2384. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2385. var tan = 1.0 / (Math.tan(fov * 0.5));
  2386. if (isVerticalFovFixed) {
  2387. result.m[0] = tan / aspect;
  2388. }
  2389. else {
  2390. result.m[0] = tan;
  2391. }
  2392. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2393. if (isVerticalFovFixed) {
  2394. result.m[5] = tan;
  2395. }
  2396. else {
  2397. result.m[5] = tan * aspect;
  2398. }
  2399. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2400. result.m[8] = result.m[9] = 0.0;
  2401. result.m[10] = zfar / (znear - zfar);
  2402. result.m[11] = -1.0;
  2403. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2404. result.m[14] = (znear * zfar) / (znear - zfar);
  2405. };
  2406. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2407. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2408. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2409. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2410. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2411. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2412. var xScale = 2.0 / (leftTan + rightTan);
  2413. var yScale = 2.0 / (upTan + downTan);
  2414. result.m[0] = xScale;
  2415. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2416. result.m[5] = yScale;
  2417. result.m[6] = result.m[7] = 0.0;
  2418. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2419. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2420. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2421. result.m[10] = -zfar / (znear - zfar);
  2422. result.m[11] = 1.0;
  2423. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2424. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2425. result.m[14] = (znear * zfar) / (znear - zfar);
  2426. };
  2427. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2428. var cw = viewport.width;
  2429. var ch = viewport.height;
  2430. var cx = viewport.x;
  2431. var cy = viewport.y;
  2432. 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);
  2433. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2434. };
  2435. Matrix.GetAsMatrix2x2 = function (matrix) {
  2436. return new Float32Array([
  2437. matrix.m[0], matrix.m[1],
  2438. matrix.m[4], matrix.m[5]
  2439. ]);
  2440. };
  2441. Matrix.GetAsMatrix3x3 = function (matrix) {
  2442. return new Float32Array([
  2443. matrix.m[0], matrix.m[1], matrix.m[2],
  2444. matrix.m[4], matrix.m[5], matrix.m[6],
  2445. matrix.m[8], matrix.m[9], matrix.m[10]
  2446. ]);
  2447. };
  2448. Matrix.Transpose = function (matrix) {
  2449. var result = new Matrix();
  2450. result.m[0] = matrix.m[0];
  2451. result.m[1] = matrix.m[4];
  2452. result.m[2] = matrix.m[8];
  2453. result.m[3] = matrix.m[12];
  2454. result.m[4] = matrix.m[1];
  2455. result.m[5] = matrix.m[5];
  2456. result.m[6] = matrix.m[9];
  2457. result.m[7] = matrix.m[13];
  2458. result.m[8] = matrix.m[2];
  2459. result.m[9] = matrix.m[6];
  2460. result.m[10] = matrix.m[10];
  2461. result.m[11] = matrix.m[14];
  2462. result.m[12] = matrix.m[3];
  2463. result.m[13] = matrix.m[7];
  2464. result.m[14] = matrix.m[11];
  2465. result.m[15] = matrix.m[15];
  2466. return result;
  2467. };
  2468. Matrix.Reflection = function (plane) {
  2469. var matrix = new Matrix();
  2470. Matrix.ReflectionToRef(plane, matrix);
  2471. return matrix;
  2472. };
  2473. Matrix.ReflectionToRef = function (plane, result) {
  2474. plane.normalize();
  2475. var x = plane.normal.x;
  2476. var y = plane.normal.y;
  2477. var z = plane.normal.z;
  2478. var temp = -2 * x;
  2479. var temp2 = -2 * y;
  2480. var temp3 = -2 * z;
  2481. result.m[0] = (temp * x) + 1;
  2482. result.m[1] = temp2 * x;
  2483. result.m[2] = temp3 * x;
  2484. result.m[3] = 0.0;
  2485. result.m[4] = temp * y;
  2486. result.m[5] = (temp2 * y) + 1;
  2487. result.m[6] = temp3 * y;
  2488. result.m[7] = 0.0;
  2489. result.m[8] = temp * z;
  2490. result.m[9] = temp2 * z;
  2491. result.m[10] = (temp3 * z) + 1;
  2492. result.m[11] = 0.0;
  2493. result.m[12] = temp * plane.d;
  2494. result.m[13] = temp2 * plane.d;
  2495. result.m[14] = temp3 * plane.d;
  2496. result.m[15] = 1.0;
  2497. };
  2498. Matrix._tempQuaternion = new Quaternion();
  2499. Matrix._xAxis = Vector3.Zero();
  2500. Matrix._yAxis = Vector3.Zero();
  2501. Matrix._zAxis = Vector3.Zero();
  2502. return Matrix;
  2503. }());
  2504. BABYLON.Matrix = Matrix;
  2505. var Plane = (function () {
  2506. function Plane(a, b, c, d) {
  2507. this.normal = new Vector3(a, b, c);
  2508. this.d = d;
  2509. }
  2510. Plane.prototype.asArray = function () {
  2511. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2512. };
  2513. // Methods
  2514. Plane.prototype.clone = function () {
  2515. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2516. };
  2517. Plane.prototype.getClassName = function () {
  2518. return "Plane";
  2519. };
  2520. Plane.prototype.getHashCode = function () {
  2521. var hash = this.normal.getHashCode();
  2522. hash = (hash * 397) ^ (this.d || 0);
  2523. return hash;
  2524. };
  2525. Plane.prototype.normalize = function () {
  2526. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2527. var magnitude = 0;
  2528. if (norm !== 0) {
  2529. magnitude = 1.0 / norm;
  2530. }
  2531. this.normal.x *= magnitude;
  2532. this.normal.y *= magnitude;
  2533. this.normal.z *= magnitude;
  2534. this.d *= magnitude;
  2535. return this;
  2536. };
  2537. Plane.prototype.transform = function (transformation) {
  2538. var transposedMatrix = Matrix.Transpose(transformation);
  2539. var x = this.normal.x;
  2540. var y = this.normal.y;
  2541. var z = this.normal.z;
  2542. var d = this.d;
  2543. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2544. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2545. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2546. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2547. return new Plane(normalX, normalY, normalZ, finalD);
  2548. };
  2549. Plane.prototype.dotCoordinate = function (point) {
  2550. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2551. };
  2552. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2553. var x1 = point2.x - point1.x;
  2554. var y1 = point2.y - point1.y;
  2555. var z1 = point2.z - point1.z;
  2556. var x2 = point3.x - point1.x;
  2557. var y2 = point3.y - point1.y;
  2558. var z2 = point3.z - point1.z;
  2559. var yz = (y1 * z2) - (z1 * y2);
  2560. var xz = (z1 * x2) - (x1 * z2);
  2561. var xy = (x1 * y2) - (y1 * x2);
  2562. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2563. var invPyth;
  2564. if (pyth !== 0) {
  2565. invPyth = 1.0 / pyth;
  2566. }
  2567. else {
  2568. invPyth = 0;
  2569. }
  2570. this.normal.x = yz * invPyth;
  2571. this.normal.y = xz * invPyth;
  2572. this.normal.z = xy * invPyth;
  2573. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2574. return this;
  2575. };
  2576. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2577. var dot = Vector3.Dot(this.normal, direction);
  2578. return (dot <= epsilon);
  2579. };
  2580. Plane.prototype.signedDistanceTo = function (point) {
  2581. return Vector3.Dot(point, this.normal) + this.d;
  2582. };
  2583. // Statics
  2584. Plane.FromArray = function (array) {
  2585. return new Plane(array[0], array[1], array[2], array[3]);
  2586. };
  2587. Plane.FromPoints = function (point1, point2, point3) {
  2588. var result = new Plane(0, 0, 0, 0);
  2589. result.copyFromPoints(point1, point2, point3);
  2590. return result;
  2591. };
  2592. Plane.FromPositionAndNormal = function (origin, normal) {
  2593. var result = new Plane(0, 0, 0, 0);
  2594. normal.normalize();
  2595. result.normal = normal;
  2596. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2597. return result;
  2598. };
  2599. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2600. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2601. return Vector3.Dot(point, normal) + d;
  2602. };
  2603. return Plane;
  2604. }());
  2605. BABYLON.Plane = Plane;
  2606. var Viewport = (function () {
  2607. function Viewport(x, y, width, height) {
  2608. this.x = x;
  2609. this.y = y;
  2610. this.width = width;
  2611. this.height = height;
  2612. }
  2613. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2614. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2615. };
  2616. return Viewport;
  2617. }());
  2618. BABYLON.Viewport = Viewport;
  2619. var Frustum = (function () {
  2620. function Frustum() {
  2621. }
  2622. Frustum.GetPlanes = function (transform) {
  2623. var frustumPlanes = [];
  2624. for (var index = 0; index < 6; index++) {
  2625. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2626. }
  2627. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2628. return frustumPlanes;
  2629. };
  2630. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2631. // Near
  2632. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2633. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2634. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2635. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2636. frustumPlanes[0].normalize();
  2637. // Far
  2638. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2639. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2640. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2641. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2642. frustumPlanes[1].normalize();
  2643. // Left
  2644. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2645. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2646. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2647. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2648. frustumPlanes[2].normalize();
  2649. // Right
  2650. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2651. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2652. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2653. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2654. frustumPlanes[3].normalize();
  2655. // Top
  2656. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2657. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2658. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2659. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2660. frustumPlanes[4].normalize();
  2661. // Bottom
  2662. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2663. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2664. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2665. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2666. frustumPlanes[5].normalize();
  2667. };
  2668. return Frustum;
  2669. }());
  2670. BABYLON.Frustum = Frustum;
  2671. (function (Space) {
  2672. Space[Space["LOCAL"] = 0] = "LOCAL";
  2673. Space[Space["WORLD"] = 1] = "WORLD";
  2674. })(BABYLON.Space || (BABYLON.Space = {}));
  2675. var Space = BABYLON.Space;
  2676. var Axis = (function () {
  2677. function Axis() {
  2678. }
  2679. Axis.X = new Vector3(1, 0, 0);
  2680. Axis.Y = new Vector3(0, 1, 0);
  2681. Axis.Z = new Vector3(0, 0, 1);
  2682. return Axis;
  2683. }());
  2684. BABYLON.Axis = Axis;
  2685. ;
  2686. var BezierCurve = (function () {
  2687. function BezierCurve() {
  2688. }
  2689. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2690. // Extract X (which is equal to time here)
  2691. var f0 = 1 - 3 * x2 + 3 * x1;
  2692. var f1 = 3 * x2 - 6 * x1;
  2693. var f2 = 3 * x1;
  2694. var refinedT = t;
  2695. for (var i = 0; i < 5; i++) {
  2696. var refinedT2 = refinedT * refinedT;
  2697. var refinedT3 = refinedT2 * refinedT;
  2698. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2699. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2700. refinedT -= (x - t) * slope;
  2701. refinedT = Math.min(1, Math.max(0, refinedT));
  2702. }
  2703. // Resolve cubic bezier for the given x
  2704. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2705. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2706. Math.pow(refinedT, 3);
  2707. };
  2708. return BezierCurve;
  2709. }());
  2710. BABYLON.BezierCurve = BezierCurve;
  2711. (function (Orientation) {
  2712. Orientation[Orientation["CW"] = 0] = "CW";
  2713. Orientation[Orientation["CCW"] = 1] = "CCW";
  2714. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2715. var Orientation = BABYLON.Orientation;
  2716. var Angle = (function () {
  2717. function Angle(radians) {
  2718. var _this = this;
  2719. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2720. this.radians = function () { return _this._radians; };
  2721. this._radians = radians;
  2722. if (this._radians < 0)
  2723. this._radians += (2 * Math.PI);
  2724. }
  2725. Angle.BetweenTwoPoints = function (a, b) {
  2726. var delta = b.subtract(a);
  2727. var theta = Math.atan2(delta.y, delta.x);
  2728. return new Angle(theta);
  2729. };
  2730. Angle.FromRadians = function (radians) {
  2731. return new Angle(radians);
  2732. };
  2733. Angle.FromDegrees = function (degrees) {
  2734. return new Angle(degrees * Math.PI / 180);
  2735. };
  2736. return Angle;
  2737. }());
  2738. BABYLON.Angle = Angle;
  2739. var Arc2 = (function () {
  2740. function Arc2(startPoint, midPoint, endPoint) {
  2741. this.startPoint = startPoint;
  2742. this.midPoint = midPoint;
  2743. this.endPoint = endPoint;
  2744. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2745. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2746. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2747. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2748. 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);
  2749. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2750. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2751. var a1 = this.startAngle.degrees();
  2752. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2753. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2754. // angles correction
  2755. if (a2 - a1 > +180.0)
  2756. a2 -= 360.0;
  2757. if (a2 - a1 < -180.0)
  2758. a2 += 360.0;
  2759. if (a3 - a2 > +180.0)
  2760. a3 -= 360.0;
  2761. if (a3 - a2 < -180.0)
  2762. a3 += 360.0;
  2763. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2764. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2765. }
  2766. return Arc2;
  2767. }());
  2768. BABYLON.Arc2 = Arc2;
  2769. var Path2 = (function () {
  2770. function Path2(x, y) {
  2771. this._points = new Array();
  2772. this._length = 0;
  2773. this.closed = false;
  2774. this._points.push(new Vector2(x, y));
  2775. }
  2776. Path2.prototype.addLineTo = function (x, y) {
  2777. if (closed) {
  2778. //Tools.Error("cannot add lines to closed paths");
  2779. return this;
  2780. }
  2781. var newPoint = new Vector2(x, y);
  2782. var previousPoint = this._points[this._points.length - 1];
  2783. this._points.push(newPoint);
  2784. this._length += newPoint.subtract(previousPoint).length();
  2785. return this;
  2786. };
  2787. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2788. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2789. if (closed) {
  2790. //Tools.Error("cannot add arcs to closed paths");
  2791. return this;
  2792. }
  2793. var startPoint = this._points[this._points.length - 1];
  2794. var midPoint = new Vector2(midX, midY);
  2795. var endPoint = new Vector2(endX, endY);
  2796. var arc = new Arc2(startPoint, midPoint, endPoint);
  2797. var increment = arc.angle.radians() / numberOfSegments;
  2798. if (arc.orientation === Orientation.CW)
  2799. increment *= -1;
  2800. var currentAngle = arc.startAngle.radians() + increment;
  2801. for (var i = 0; i < numberOfSegments; i++) {
  2802. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2803. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2804. this.addLineTo(x, y);
  2805. currentAngle += increment;
  2806. }
  2807. return this;
  2808. };
  2809. Path2.prototype.close = function () {
  2810. this.closed = true;
  2811. return this;
  2812. };
  2813. Path2.prototype.length = function () {
  2814. var result = this._length;
  2815. if (!this.closed) {
  2816. var lastPoint = this._points[this._points.length - 1];
  2817. var firstPoint = this._points[0];
  2818. result += (firstPoint.subtract(lastPoint).length());
  2819. }
  2820. return result;
  2821. };
  2822. Path2.prototype.getPoints = function () {
  2823. return this._points;
  2824. };
  2825. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2826. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2827. //Tools.Error("normalized length position should be between 0 and 1.");
  2828. return Vector2.Zero();
  2829. }
  2830. var lengthPosition = normalizedLengthPosition * this.length();
  2831. var previousOffset = 0;
  2832. for (var i = 0; i < this._points.length; i++) {
  2833. var j = (i + 1) % this._points.length;
  2834. var a = this._points[i];
  2835. var b = this._points[j];
  2836. var bToA = b.subtract(a);
  2837. var nextOffset = (bToA.length() + previousOffset);
  2838. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2839. var dir = bToA.normalize();
  2840. var localOffset = lengthPosition - previousOffset;
  2841. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2842. }
  2843. previousOffset = nextOffset;
  2844. }
  2845. //Tools.Error("internal error");
  2846. return Vector2.Zero();
  2847. };
  2848. Path2.StartingAt = function (x, y) {
  2849. return new Path2(x, y);
  2850. };
  2851. return Path2;
  2852. }());
  2853. BABYLON.Path2 = Path2;
  2854. var Path3D = (function () {
  2855. /**
  2856. * new Path3D(path, normal, raw)
  2857. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2858. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2859. * path : an array of Vector3, the curve axis of the Path3D
  2860. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2861. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2862. */
  2863. function Path3D(path, firstNormal, raw) {
  2864. this.path = path;
  2865. this._curve = new Array();
  2866. this._distances = new Array();
  2867. this._tangents = new Array();
  2868. this._normals = new Array();
  2869. this._binormals = new Array();
  2870. for (var p = 0; p < path.length; p++) {
  2871. this._curve[p] = path[p].clone(); // hard copy
  2872. }
  2873. this._raw = raw || false;
  2874. this._compute(firstNormal);
  2875. }
  2876. /**
  2877. * Returns the Path3D array of successive Vector3 designing its curve.
  2878. */
  2879. Path3D.prototype.getCurve = function () {
  2880. return this._curve;
  2881. };
  2882. /**
  2883. * Returns an array populated with tangent vectors on each Path3D curve point.
  2884. */
  2885. Path3D.prototype.getTangents = function () {
  2886. return this._tangents;
  2887. };
  2888. /**
  2889. * Returns an array populated with normal vectors on each Path3D curve point.
  2890. */
  2891. Path3D.prototype.getNormals = function () {
  2892. return this._normals;
  2893. };
  2894. /**
  2895. * Returns an array populated with binormal vectors on each Path3D curve point.
  2896. */
  2897. Path3D.prototype.getBinormals = function () {
  2898. return this._binormals;
  2899. };
  2900. /**
  2901. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2902. */
  2903. Path3D.prototype.getDistances = function () {
  2904. return this._distances;
  2905. };
  2906. /**
  2907. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2908. * Returns the same object updated.
  2909. */
  2910. Path3D.prototype.update = function (path, firstNormal) {
  2911. for (var p = 0; p < path.length; p++) {
  2912. this._curve[p].x = path[p].x;
  2913. this._curve[p].y = path[p].y;
  2914. this._curve[p].z = path[p].z;
  2915. }
  2916. this._compute(firstNormal);
  2917. return this;
  2918. };
  2919. // private function compute() : computes tangents, normals and binormals
  2920. Path3D.prototype._compute = function (firstNormal) {
  2921. var l = this._curve.length;
  2922. // first and last tangents
  2923. this._tangents[0] = this._getFirstNonNullVector(0);
  2924. if (!this._raw) {
  2925. this._tangents[0].normalize();
  2926. }
  2927. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2928. if (!this._raw) {
  2929. this._tangents[l - 1].normalize();
  2930. }
  2931. // normals and binormals at first point : arbitrary vector with _normalVector()
  2932. var tg0 = this._tangents[0];
  2933. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2934. this._normals[0] = pp0;
  2935. if (!this._raw) {
  2936. this._normals[0].normalize();
  2937. }
  2938. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2939. if (!this._raw) {
  2940. this._binormals[0].normalize();
  2941. }
  2942. this._distances[0] = 0.0;
  2943. // normals and binormals : next points
  2944. var prev; // previous vector (segment)
  2945. var cur; // current vector (segment)
  2946. var curTang; // current tangent
  2947. // previous normal
  2948. var prevBinor; // previous binormal
  2949. for (var i = 1; i < l; i++) {
  2950. // tangents
  2951. prev = this._getLastNonNullVector(i);
  2952. if (i < l - 1) {
  2953. cur = this._getFirstNonNullVector(i);
  2954. this._tangents[i] = prev.add(cur);
  2955. this._tangents[i].normalize();
  2956. }
  2957. this._distances[i] = this._distances[i - 1] + prev.length();
  2958. // normals and binormals
  2959. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2960. curTang = this._tangents[i];
  2961. prevBinor = this._binormals[i - 1];
  2962. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2963. if (!this._raw) {
  2964. this._normals[i].normalize();
  2965. }
  2966. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2967. if (!this._raw) {
  2968. this._binormals[i].normalize();
  2969. }
  2970. }
  2971. };
  2972. // private function getFirstNonNullVector(index)
  2973. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2974. Path3D.prototype._getFirstNonNullVector = function (index) {
  2975. var i = 1;
  2976. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2977. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2978. i++;
  2979. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2980. }
  2981. return nNVector;
  2982. };
  2983. // private function getLastNonNullVector(index)
  2984. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2985. Path3D.prototype._getLastNonNullVector = function (index) {
  2986. var i = 1;
  2987. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2988. while (nLVector.length() === 0 && index > i + 1) {
  2989. i++;
  2990. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2991. }
  2992. return nLVector;
  2993. };
  2994. // private function normalVector(v0, vt, va) :
  2995. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2996. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2997. Path3D.prototype._normalVector = function (v0, vt, va) {
  2998. var normal0;
  2999. var tgl = vt.length();
  3000. if (tgl === 0.0) {
  3001. tgl = 1.0;
  3002. }
  3003. if (va === undefined || va === null) {
  3004. var point;
  3005. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3006. point = new Vector3(0.0, -1.0, 0.0);
  3007. }
  3008. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3009. point = new Vector3(1.0, 0.0, 0.0);
  3010. }
  3011. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3012. point = new Vector3(0.0, 0.0, 1.0);
  3013. }
  3014. normal0 = Vector3.Cross(vt, point);
  3015. }
  3016. else {
  3017. normal0 = Vector3.Cross(vt, va);
  3018. Vector3.CrossToRef(normal0, vt, normal0);
  3019. }
  3020. normal0.normalize();
  3021. return normal0;
  3022. };
  3023. return Path3D;
  3024. }());
  3025. BABYLON.Path3D = Path3D;
  3026. var Curve3 = (function () {
  3027. /**
  3028. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3029. * A Curve3 is designed from a series of successive Vector3.
  3030. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3031. */
  3032. function Curve3(points) {
  3033. this._length = 0.0;
  3034. this._points = points;
  3035. this._length = this._computeLength(points);
  3036. }
  3037. /**
  3038. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3039. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3040. * @param v1 (Vector3) the control point
  3041. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3042. * @param nbPoints (integer) the wanted number of points in the curve
  3043. */
  3044. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3045. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3046. var bez = new Array();
  3047. var equation = function (t, val0, val1, val2) {
  3048. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3049. return res;
  3050. };
  3051. for (var i = 0; i <= nbPoints; i++) {
  3052. 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)));
  3053. }
  3054. return new Curve3(bez);
  3055. };
  3056. /**
  3057. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3058. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3059. * @param v1 (Vector3) the first control point
  3060. * @param v2 (Vector3) the second control point
  3061. * @param v3 (Vector3) the end point of the Cubic Bezier
  3062. * @param nbPoints (integer) the wanted number of points in the curve
  3063. */
  3064. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3065. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3066. var bez = new Array();
  3067. var equation = function (t, val0, val1, val2, val3) {
  3068. 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;
  3069. return res;
  3070. };
  3071. for (var i = 0; i <= nbPoints; i++) {
  3072. 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)));
  3073. }
  3074. return new Curve3(bez);
  3075. };
  3076. /**
  3077. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3078. * @param p1 (Vector3) the origin point of the Hermite Spline
  3079. * @param t1 (Vector3) the tangent vector at the origin point
  3080. * @param p2 (Vector3) the end point of the Hermite Spline
  3081. * @param t2 (Vector3) the tangent vector at the end point
  3082. * @param nbPoints (integer) the wanted number of points in the curve
  3083. */
  3084. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3085. var hermite = new Array();
  3086. var step = 1.0 / nbPoints;
  3087. for (var i = 0; i <= nbPoints; i++) {
  3088. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3089. }
  3090. return new Curve3(hermite);
  3091. };
  3092. /**
  3093. * Returns the Curve3 stored array of successive Vector3
  3094. */
  3095. Curve3.prototype.getPoints = function () {
  3096. return this._points;
  3097. };
  3098. /**
  3099. * Returns the computed length (float) of the curve.
  3100. */
  3101. Curve3.prototype.length = function () {
  3102. return this._length;
  3103. };
  3104. /**
  3105. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3106. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3107. * curveA and curveB keep unchanged.
  3108. */
  3109. Curve3.prototype.continue = function (curve) {
  3110. var lastPoint = this._points[this._points.length - 1];
  3111. var continuedPoints = this._points.slice();
  3112. var curvePoints = curve.getPoints();
  3113. for (var i = 1; i < curvePoints.length; i++) {
  3114. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3115. }
  3116. var continuedCurve = new Curve3(continuedPoints);
  3117. return continuedCurve;
  3118. };
  3119. Curve3.prototype._computeLength = function (path) {
  3120. var l = 0;
  3121. for (var i = 1; i < path.length; i++) {
  3122. l += (path[i].subtract(path[i - 1])).length();
  3123. }
  3124. return l;
  3125. };
  3126. return Curve3;
  3127. }());
  3128. BABYLON.Curve3 = Curve3;
  3129. // SphericalHarmonics
  3130. var SphericalHarmonics = (function () {
  3131. function SphericalHarmonics() {
  3132. this.L00 = Vector3.Zero();
  3133. this.L1_1 = Vector3.Zero();
  3134. this.L10 = Vector3.Zero();
  3135. this.L11 = Vector3.Zero();
  3136. this.L2_2 = Vector3.Zero();
  3137. this.L2_1 = Vector3.Zero();
  3138. this.L20 = Vector3.Zero();
  3139. this.L21 = Vector3.Zero();
  3140. this.L22 = Vector3.Zero();
  3141. }
  3142. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3143. var colorVector = new Vector3(color.r, color.g, color.b);
  3144. var c = colorVector.scale(deltaSolidAngle);
  3145. this.L00 = this.L00.add(c.scale(0.282095));
  3146. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3147. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3148. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3149. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3150. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3151. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3152. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3153. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3154. };
  3155. SphericalHarmonics.prototype.scale = function (scale) {
  3156. this.L00 = this.L00.scale(scale);
  3157. this.L1_1 = this.L1_1.scale(scale);
  3158. this.L10 = this.L10.scale(scale);
  3159. this.L11 = this.L11.scale(scale);
  3160. this.L2_2 = this.L2_2.scale(scale);
  3161. this.L2_1 = this.L2_1.scale(scale);
  3162. this.L20 = this.L20.scale(scale);
  3163. this.L21 = this.L21.scale(scale);
  3164. this.L22 = this.L22.scale(scale);
  3165. };
  3166. return SphericalHarmonics;
  3167. }());
  3168. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3169. // SphericalPolynomial
  3170. var SphericalPolynomial = (function () {
  3171. function SphericalPolynomial() {
  3172. this.x = Vector3.Zero();
  3173. this.y = Vector3.Zero();
  3174. this.z = Vector3.Zero();
  3175. this.xx = Vector3.Zero();
  3176. this.yy = Vector3.Zero();
  3177. this.zz = Vector3.Zero();
  3178. this.xy = Vector3.Zero();
  3179. this.yz = Vector3.Zero();
  3180. this.zx = Vector3.Zero();
  3181. }
  3182. SphericalPolynomial.prototype.addAmbient = function (color) {
  3183. var colorVector = new Vector3(color.r, color.g, color.b);
  3184. this.xx = this.xx.add(colorVector);
  3185. this.yy = this.yy.add(colorVector);
  3186. this.zz = this.zz.add(colorVector);
  3187. };
  3188. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3189. var result = new SphericalPolynomial();
  3190. result.x = harmonics.L11.scale(1.02333);
  3191. result.y = harmonics.L1_1.scale(1.02333);
  3192. result.z = harmonics.L10.scale(1.02333);
  3193. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3194. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3195. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3196. result.yz = harmonics.L2_1.scale(0.858086);
  3197. result.zx = harmonics.L21.scale(0.858086);
  3198. result.xy = harmonics.L2_2.scale(0.858086);
  3199. return result;
  3200. };
  3201. return SphericalPolynomial;
  3202. }());
  3203. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3204. // Vertex formats
  3205. var PositionNormalVertex = (function () {
  3206. function PositionNormalVertex(position, normal) {
  3207. if (position === void 0) { position = Vector3.Zero(); }
  3208. if (normal === void 0) { normal = Vector3.Up(); }
  3209. this.position = position;
  3210. this.normal = normal;
  3211. }
  3212. PositionNormalVertex.prototype.clone = function () {
  3213. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3214. };
  3215. return PositionNormalVertex;
  3216. }());
  3217. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3218. var PositionNormalTextureVertex = (function () {
  3219. function PositionNormalTextureVertex(position, normal, uv) {
  3220. if (position === void 0) { position = Vector3.Zero(); }
  3221. if (normal === void 0) { normal = Vector3.Up(); }
  3222. if (uv === void 0) { uv = Vector2.Zero(); }
  3223. this.position = position;
  3224. this.normal = normal;
  3225. this.uv = uv;
  3226. }
  3227. PositionNormalTextureVertex.prototype.clone = function () {
  3228. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3229. };
  3230. return PositionNormalTextureVertex;
  3231. }());
  3232. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3233. // Temporary pre-allocated objects for engine internal use
  3234. // usage in any internal function :
  3235. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3236. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3237. var Tmp = (function () {
  3238. function Tmp() {
  3239. }
  3240. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3241. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3242. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3243. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3244. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3245. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3246. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3247. Matrix.Zero(), Matrix.Zero(),
  3248. Matrix.Zero(), Matrix.Zero(),
  3249. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3250. return Tmp;
  3251. }());
  3252. BABYLON.Tmp = Tmp;
  3253. })(BABYLON || (BABYLON = {}));
  3254. var BABYLON;
  3255. (function (BABYLON) {
  3256. function generateSerializableMember(type, sourceName) {
  3257. return function (target, propertyKey) {
  3258. if (!target.__serializableMembers) {
  3259. target.__serializableMembers = {};
  3260. }
  3261. if (!target.__serializableMembers[propertyKey]) {
  3262. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3263. }
  3264. };
  3265. }
  3266. function serialize(sourceName) {
  3267. return generateSerializableMember(0, sourceName); // value member
  3268. }
  3269. BABYLON.serialize = serialize;
  3270. function serializeAsTexture(sourceName) {
  3271. return generateSerializableMember(1, sourceName); // texture member
  3272. }
  3273. BABYLON.serializeAsTexture = serializeAsTexture;
  3274. function serializeAsColor3(sourceName) {
  3275. return generateSerializableMember(2, sourceName); // color3 member
  3276. }
  3277. BABYLON.serializeAsColor3 = serializeAsColor3;
  3278. function serializeAsFresnelParameters(sourceName) {
  3279. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3280. }
  3281. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3282. function serializeAsVector2(sourceName) {
  3283. return generateSerializableMember(4, sourceName); // vector2 member
  3284. }
  3285. BABYLON.serializeAsVector2 = serializeAsVector2;
  3286. function serializeAsVector3(sourceName) {
  3287. return generateSerializableMember(5, sourceName); // vector3 member
  3288. }
  3289. BABYLON.serializeAsVector3 = serializeAsVector3;
  3290. function serializeAsMeshReference(sourceName) {
  3291. return generateSerializableMember(6, sourceName); // mesh reference member
  3292. }
  3293. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3294. function serializeAsColorCurves(sourceName) {
  3295. return generateSerializableMember(7, sourceName); // color curves
  3296. }
  3297. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3298. var SerializationHelper = (function () {
  3299. function SerializationHelper() {
  3300. }
  3301. SerializationHelper.Serialize = function (entity, serializationObject) {
  3302. if (!serializationObject) {
  3303. serializationObject = {};
  3304. }
  3305. // Tags
  3306. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3307. // Properties
  3308. for (var property in entity.__serializableMembers) {
  3309. var propertyDescriptor = entity.__serializableMembers[property];
  3310. var targetPropertyName = propertyDescriptor.sourceName || property;
  3311. var propertyType = propertyDescriptor.type;
  3312. var sourceProperty = entity[property];
  3313. if (sourceProperty !== undefined && sourceProperty !== null) {
  3314. switch (propertyType) {
  3315. case 0:
  3316. serializationObject[targetPropertyName] = sourceProperty;
  3317. break;
  3318. case 1:
  3319. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3320. break;
  3321. case 2:
  3322. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3323. break;
  3324. case 3:
  3325. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3326. break;
  3327. case 4:
  3328. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3329. break;
  3330. case 5:
  3331. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3332. break;
  3333. case 6:
  3334. serializationObject[targetPropertyName] = sourceProperty.id;
  3335. break;
  3336. case 7:
  3337. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3338. break;
  3339. }
  3340. }
  3341. }
  3342. return serializationObject;
  3343. };
  3344. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3345. var destination = creationFunction();
  3346. // Tags
  3347. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3348. // Properties
  3349. for (var property in destination.__serializableMembers) {
  3350. var propertyDescriptor = destination.__serializableMembers[property];
  3351. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3352. var propertyType = propertyDescriptor.type;
  3353. if (sourceProperty !== undefined && sourceProperty !== null) {
  3354. switch (propertyType) {
  3355. case 0:
  3356. destination[property] = sourceProperty;
  3357. break;
  3358. case 1:
  3359. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3360. break;
  3361. case 2:
  3362. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3363. break;
  3364. case 3:
  3365. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3366. break;
  3367. case 4:
  3368. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3369. break;
  3370. case 5:
  3371. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3372. break;
  3373. case 6:
  3374. destination[property] = scene.getLastMeshByID(sourceProperty);
  3375. break;
  3376. case 7:
  3377. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3378. break;
  3379. }
  3380. }
  3381. }
  3382. return destination;
  3383. };
  3384. SerializationHelper.Clone = function (creationFunction, source) {
  3385. var destination = creationFunction();
  3386. // Tags
  3387. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3388. // Properties
  3389. for (var property in destination.__serializableMembers) {
  3390. var propertyDescriptor = destination.__serializableMembers[property];
  3391. var sourceProperty = source[property];
  3392. var propertyType = propertyDescriptor.type;
  3393. if (sourceProperty !== undefined && sourceProperty !== null) {
  3394. switch (propertyType) {
  3395. case 0: // Value
  3396. case 6:
  3397. destination[property] = sourceProperty;
  3398. break;
  3399. case 1: // Texture
  3400. case 2: // Color3
  3401. case 3: // FresnelParameters
  3402. case 4: // Vector2
  3403. case 5: // Vector3
  3404. case 7:
  3405. destination[property] = sourceProperty.clone();
  3406. break;
  3407. }
  3408. }
  3409. }
  3410. return destination;
  3411. };
  3412. return SerializationHelper;
  3413. }());
  3414. BABYLON.SerializationHelper = SerializationHelper;
  3415. })(BABYLON || (BABYLON = {}));
  3416. var BABYLON;
  3417. (function (BABYLON) {
  3418. /**
  3419. * A class serves as a medium between the observable and its observers
  3420. */
  3421. var EventState = (function () {
  3422. /**
  3423. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3424. */
  3425. function EventState(mask, skipNextObservers) {
  3426. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3427. this.initalize(mask, skipNextObservers);
  3428. }
  3429. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3430. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3431. this.mask = mask;
  3432. this.skipNextObservers = skipNextObservers;
  3433. return this;
  3434. };
  3435. return EventState;
  3436. }());
  3437. BABYLON.EventState = EventState;
  3438. /**
  3439. * Represent an Observer registered to a given Observable object.
  3440. */
  3441. var Observer = (function () {
  3442. function Observer(callback, mask) {
  3443. this.callback = callback;
  3444. this.mask = mask;
  3445. }
  3446. return Observer;
  3447. }());
  3448. BABYLON.Observer = Observer;
  3449. /**
  3450. * The Observable class is a simple implementation of the Observable pattern.
  3451. * 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.
  3452. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3453. * 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).
  3454. * 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.
  3455. */
  3456. var Observable = (function () {
  3457. function Observable() {
  3458. this._observers = new Array();
  3459. this._eventState = new EventState(0);
  3460. }
  3461. /**
  3462. * Create a new Observer with the specified callback
  3463. * @param callback the callback that will be executed for that Observer
  3464. * @param mask the mask used to filter observers
  3465. * @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.
  3466. */
  3467. Observable.prototype.add = function (callback, mask, insertFirst) {
  3468. if (mask === void 0) { mask = -1; }
  3469. if (insertFirst === void 0) { insertFirst = false; }
  3470. if (!callback) {
  3471. return null;
  3472. }
  3473. var observer = new Observer(callback, mask);
  3474. if (insertFirst) {
  3475. this._observers.unshift(observer);
  3476. }
  3477. else {
  3478. this._observers.push(observer);
  3479. }
  3480. return observer;
  3481. };
  3482. /**
  3483. * Remove an Observer from the Observable object
  3484. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3485. */
  3486. Observable.prototype.remove = function (observer) {
  3487. var index = this._observers.indexOf(observer);
  3488. if (index !== -1) {
  3489. this._observers.splice(index, 1);
  3490. return true;
  3491. }
  3492. return false;
  3493. };
  3494. /**
  3495. * Remove a callback from the Observable object
  3496. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3497. */
  3498. Observable.prototype.removeCallback = function (callback) {
  3499. for (var index = 0; index < this._observers.length; index++) {
  3500. if (this._observers[index].callback === callback) {
  3501. this._observers.splice(index, 1);
  3502. return true;
  3503. }
  3504. }
  3505. return false;
  3506. };
  3507. /**
  3508. * Notify all Observers by calling their respective callback with the given data
  3509. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3510. * @param eventData
  3511. * @param mask
  3512. */
  3513. Observable.prototype.notifyObservers = function (eventData, mask) {
  3514. if (mask === void 0) { mask = -1; }
  3515. var state = this._eventState;
  3516. state.mask = mask;
  3517. state.skipNextObservers = false;
  3518. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3519. var obs = _a[_i];
  3520. if (obs.mask & mask) {
  3521. obs.callback(eventData, state);
  3522. }
  3523. if (state.skipNextObservers) {
  3524. return false;
  3525. }
  3526. }
  3527. return true;
  3528. };
  3529. /**
  3530. * return true is the Observable has at least one Observer registered
  3531. */
  3532. Observable.prototype.hasObservers = function () {
  3533. return this._observers.length > 0;
  3534. };
  3535. /**
  3536. * Clear the list of observers
  3537. */
  3538. Observable.prototype.clear = function () {
  3539. this._observers = new Array();
  3540. };
  3541. /**
  3542. * Clone the current observable
  3543. */
  3544. Observable.prototype.clone = function () {
  3545. var result = new Observable();
  3546. result._observers = this._observers.slice(0);
  3547. return result;
  3548. };
  3549. return Observable;
  3550. }());
  3551. BABYLON.Observable = Observable;
  3552. })(BABYLON || (BABYLON = {}));
  3553. var BABYLON;
  3554. (function (BABYLON) {
  3555. var Database = (function () {
  3556. function Database(urlToScene, callbackManifestChecked) {
  3557. // Handling various flavors of prefixed version of IndexedDB
  3558. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3559. this.callbackManifestChecked = callbackManifestChecked;
  3560. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3561. this.db = null;
  3562. this.enableSceneOffline = false;
  3563. this.enableTexturesOffline = false;
  3564. this.manifestVersionFound = 0;
  3565. this.mustUpdateRessources = false;
  3566. this.hasReachedQuota = false;
  3567. if (!Database.IDBStorageEnabled) {
  3568. this.callbackManifestChecked(true);
  3569. }
  3570. else {
  3571. this.checkManifestFile();
  3572. }
  3573. }
  3574. Database.prototype.checkManifestFile = function () {
  3575. var _this = this;
  3576. function noManifestFile() {
  3577. that.enableSceneOffline = false;
  3578. that.enableTexturesOffline = false;
  3579. that.callbackManifestChecked(false);
  3580. }
  3581. var that = this;
  3582. var timeStampUsed = false;
  3583. var manifestURL = this.currentSceneUrl + ".manifest";
  3584. var xhr = new XMLHttpRequest();
  3585. if (navigator.onLine) {
  3586. // Adding a timestamp to by-pass browsers' cache
  3587. timeStampUsed = true;
  3588. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3589. }
  3590. xhr.open("GET", manifestURL, true);
  3591. xhr.addEventListener("load", function () {
  3592. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3593. try {
  3594. var manifestFile = JSON.parse(xhr.response);
  3595. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3596. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3597. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3598. _this.manifestVersionFound = manifestFile.version;
  3599. }
  3600. if (_this.callbackManifestChecked) {
  3601. _this.callbackManifestChecked(true);
  3602. }
  3603. }
  3604. catch (ex) {
  3605. noManifestFile();
  3606. }
  3607. }
  3608. else {
  3609. noManifestFile();
  3610. }
  3611. }, false);
  3612. xhr.addEventListener("error", function (event) {
  3613. if (timeStampUsed) {
  3614. timeStampUsed = false;
  3615. // Let's retry without the timeStamp
  3616. // It could fail when coupled with HTML5 Offline API
  3617. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3618. xhr.open("GET", retryManifestURL, true);
  3619. xhr.send();
  3620. }
  3621. else {
  3622. noManifestFile();
  3623. }
  3624. }, false);
  3625. try {
  3626. xhr.send();
  3627. }
  3628. catch (ex) {
  3629. BABYLON.Tools.Error("Error on XHR send request.");
  3630. that.callbackManifestChecked(false);
  3631. }
  3632. };
  3633. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3634. var _this = this;
  3635. function handleError() {
  3636. that.isSupported = false;
  3637. if (errorCallback)
  3638. errorCallback();
  3639. }
  3640. var that = this;
  3641. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3642. // Your browser doesn't support IndexedDB
  3643. this.isSupported = false;
  3644. if (errorCallback)
  3645. errorCallback();
  3646. }
  3647. else {
  3648. // If the DB hasn't been opened or created yet
  3649. if (!this.db) {
  3650. this.hasReachedQuota = false;
  3651. this.isSupported = true;
  3652. var request = this.idbFactory.open("babylonjs", 1);
  3653. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3654. request.onerror = function (event) {
  3655. handleError();
  3656. };
  3657. // executes when a version change transaction cannot complete due to other active transactions
  3658. request.onblocked = function (event) {
  3659. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3660. handleError();
  3661. };
  3662. // DB has been opened successfully
  3663. request.onsuccess = function (event) {
  3664. _this.db = request.result;
  3665. successCallback();
  3666. };
  3667. // Initialization of the DB. Creating Scenes & Textures stores
  3668. request.onupgradeneeded = function (event) {
  3669. _this.db = (event.target).result;
  3670. try {
  3671. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3672. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3673. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3674. }
  3675. catch (ex) {
  3676. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3677. handleError();
  3678. }
  3679. };
  3680. }
  3681. else {
  3682. if (successCallback)
  3683. successCallback();
  3684. }
  3685. }
  3686. };
  3687. Database.prototype.loadImageFromDB = function (url, image) {
  3688. var _this = this;
  3689. var completeURL = Database.ReturnFullUrlLocation(url);
  3690. var saveAndLoadImage = function () {
  3691. if (!_this.hasReachedQuota && _this.db !== null) {
  3692. // the texture is not yet in the DB, let's try to save it
  3693. _this._saveImageIntoDBAsync(completeURL, image);
  3694. }
  3695. else {
  3696. image.src = url;
  3697. }
  3698. };
  3699. if (!this.mustUpdateRessources) {
  3700. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3701. }
  3702. else {
  3703. saveAndLoadImage();
  3704. }
  3705. };
  3706. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3707. if (this.isSupported && this.db !== null) {
  3708. var texture;
  3709. var transaction = this.db.transaction(["textures"]);
  3710. transaction.onabort = function (event) {
  3711. image.src = url;
  3712. };
  3713. transaction.oncomplete = function (event) {
  3714. var blobTextureURL;
  3715. if (texture) {
  3716. var URL = window.URL || window.webkitURL;
  3717. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3718. image.onerror = function () {
  3719. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3720. image.src = url;
  3721. };
  3722. image.src = blobTextureURL;
  3723. }
  3724. else {
  3725. notInDBCallback();
  3726. }
  3727. };
  3728. var getRequest = transaction.objectStore("textures").get(url);
  3729. getRequest.onsuccess = function (event) {
  3730. texture = (event.target).result;
  3731. };
  3732. getRequest.onerror = function (event) {
  3733. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3734. image.src = url;
  3735. };
  3736. }
  3737. else {
  3738. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3739. image.src = url;
  3740. }
  3741. };
  3742. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3743. var _this = this;
  3744. if (this.isSupported) {
  3745. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3746. var generateBlobUrl = function () {
  3747. var blobTextureURL;
  3748. if (blob) {
  3749. var URL = window.URL || window.webkitURL;
  3750. try {
  3751. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3752. }
  3753. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3754. catch (ex) {
  3755. blobTextureURL = URL.createObjectURL(blob);
  3756. }
  3757. }
  3758. image.src = blobTextureURL;
  3759. };
  3760. if (Database.IsUASupportingBlobStorage) {
  3761. var xhr = new XMLHttpRequest(), blob;
  3762. xhr.open("GET", url, true);
  3763. xhr.responseType = "blob";
  3764. xhr.addEventListener("load", function () {
  3765. if (xhr.status === 200) {
  3766. // Blob as response (XHR2)
  3767. blob = xhr.response;
  3768. var transaction = _this.db.transaction(["textures"], "readwrite");
  3769. // the transaction could abort because of a QuotaExceededError error
  3770. transaction.onabort = function (event) {
  3771. try {
  3772. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3773. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3774. _this.hasReachedQuota = true;
  3775. }
  3776. }
  3777. catch (ex) { }
  3778. generateBlobUrl();
  3779. };
  3780. transaction.oncomplete = function (event) {
  3781. generateBlobUrl();
  3782. };
  3783. var newTexture = { textureUrl: url, data: blob };
  3784. try {
  3785. // Put the blob into the dabase
  3786. var addRequest = transaction.objectStore("textures").put(newTexture);
  3787. addRequest.onsuccess = function (event) {
  3788. };
  3789. addRequest.onerror = function (event) {
  3790. generateBlobUrl();
  3791. };
  3792. }
  3793. catch (ex) {
  3794. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3795. if (ex.code === 25) {
  3796. Database.IsUASupportingBlobStorage = false;
  3797. }
  3798. image.src = url;
  3799. }
  3800. }
  3801. else {
  3802. image.src = url;
  3803. }
  3804. }, false);
  3805. xhr.addEventListener("error", function (event) {
  3806. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3807. image.src = url;
  3808. }, false);
  3809. xhr.send();
  3810. }
  3811. else {
  3812. image.src = url;
  3813. }
  3814. }
  3815. else {
  3816. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3817. image.src = url;
  3818. }
  3819. };
  3820. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3821. var _this = this;
  3822. var updateVersion = function (event) {
  3823. // the version is not yet in the DB or we need to update it
  3824. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3825. };
  3826. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3827. };
  3828. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3829. var _this = this;
  3830. if (this.isSupported) {
  3831. var version;
  3832. try {
  3833. var transaction = this.db.transaction(["versions"]);
  3834. transaction.oncomplete = function (event) {
  3835. if (version) {
  3836. // If the version in the JSON file is > than the version in DB
  3837. if (_this.manifestVersionFound > version.data) {
  3838. _this.mustUpdateRessources = true;
  3839. updateInDBCallback();
  3840. }
  3841. else {
  3842. callback(version.data);
  3843. }
  3844. }
  3845. else {
  3846. _this.mustUpdateRessources = true;
  3847. updateInDBCallback();
  3848. }
  3849. };
  3850. transaction.onabort = function (event) {
  3851. callback(-1);
  3852. };
  3853. var getRequest = transaction.objectStore("versions").get(url);
  3854. getRequest.onsuccess = function (event) {
  3855. version = (event.target).result;
  3856. };
  3857. getRequest.onerror = function (event) {
  3858. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3859. callback(-1);
  3860. };
  3861. }
  3862. catch (ex) {
  3863. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3864. callback(-1);
  3865. }
  3866. }
  3867. else {
  3868. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3869. callback(-1);
  3870. }
  3871. };
  3872. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3873. var _this = this;
  3874. if (this.isSupported && !this.hasReachedQuota) {
  3875. try {
  3876. // Open a transaction to the database
  3877. var transaction = this.db.transaction(["versions"], "readwrite");
  3878. // the transaction could abort because of a QuotaExceededError error
  3879. transaction.onabort = function (event) {
  3880. try {
  3881. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3882. _this.hasReachedQuota = true;
  3883. }
  3884. }
  3885. catch (ex) { }
  3886. callback(-1);
  3887. };
  3888. transaction.oncomplete = function (event) {
  3889. callback(_this.manifestVersionFound);
  3890. };
  3891. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3892. // Put the scene into the database
  3893. var addRequest = transaction.objectStore("versions").put(newVersion);
  3894. addRequest.onsuccess = function (event) {
  3895. };
  3896. addRequest.onerror = function (event) {
  3897. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3898. };
  3899. }
  3900. catch (ex) {
  3901. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3902. callback(-1);
  3903. }
  3904. }
  3905. else {
  3906. callback(-1);
  3907. }
  3908. };
  3909. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3910. var _this = this;
  3911. var completeUrl = Database.ReturnFullUrlLocation(url);
  3912. var saveAndLoadFile = function (event) {
  3913. // the scene is not yet in the DB, let's try to save it
  3914. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3915. };
  3916. this._checkVersionFromDB(completeUrl, function (version) {
  3917. if (version !== -1) {
  3918. if (!_this.mustUpdateRessources) {
  3919. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3920. }
  3921. else {
  3922. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3923. }
  3924. }
  3925. else {
  3926. errorCallback();
  3927. }
  3928. });
  3929. };
  3930. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3931. if (this.isSupported) {
  3932. var targetStore;
  3933. if (url.indexOf(".babylon") !== -1) {
  3934. targetStore = "scenes";
  3935. }
  3936. else {
  3937. targetStore = "textures";
  3938. }
  3939. var file;
  3940. var transaction = this.db.transaction([targetStore]);
  3941. transaction.oncomplete = function (event) {
  3942. if (file) {
  3943. callback(file.data);
  3944. }
  3945. else {
  3946. notInDBCallback();
  3947. }
  3948. };
  3949. transaction.onabort = function (event) {
  3950. notInDBCallback();
  3951. };
  3952. var getRequest = transaction.objectStore(targetStore).get(url);
  3953. getRequest.onsuccess = function (event) {
  3954. file = (event.target).result;
  3955. };
  3956. getRequest.onerror = function (event) {
  3957. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3958. notInDBCallback();
  3959. };
  3960. }
  3961. else {
  3962. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3963. callback();
  3964. }
  3965. };
  3966. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3967. var _this = this;
  3968. if (this.isSupported) {
  3969. var targetStore;
  3970. if (url.indexOf(".babylon") !== -1) {
  3971. targetStore = "scenes";
  3972. }
  3973. else {
  3974. targetStore = "textures";
  3975. }
  3976. // Create XHR
  3977. var xhr = new XMLHttpRequest(), fileData;
  3978. xhr.open("GET", url, true);
  3979. if (useArrayBuffer) {
  3980. xhr.responseType = "arraybuffer";
  3981. }
  3982. xhr.onprogress = progressCallback;
  3983. xhr.addEventListener("load", function () {
  3984. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3985. // Blob as response (XHR2)
  3986. //fileData = xhr.responseText;
  3987. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3988. if (!_this.hasReachedQuota) {
  3989. // Open a transaction to the database
  3990. var transaction = _this.db.transaction([targetStore], "readwrite");
  3991. // the transaction could abort because of a QuotaExceededError error
  3992. transaction.onabort = function (event) {
  3993. try {
  3994. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3995. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3996. _this.hasReachedQuota = true;
  3997. }
  3998. }
  3999. catch (ex) { }
  4000. callback(fileData);
  4001. };
  4002. transaction.oncomplete = function (event) {
  4003. callback(fileData);
  4004. };
  4005. var newFile;
  4006. if (targetStore === "scenes") {
  4007. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4008. }
  4009. else {
  4010. newFile = { textureUrl: url, data: fileData };
  4011. }
  4012. try {
  4013. // Put the scene into the database
  4014. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4015. addRequest.onsuccess = function (event) {
  4016. };
  4017. addRequest.onerror = function (event) {
  4018. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4019. };
  4020. }
  4021. catch (ex) {
  4022. callback(fileData);
  4023. }
  4024. }
  4025. else {
  4026. callback(fileData);
  4027. }
  4028. }
  4029. else {
  4030. callback();
  4031. }
  4032. }, false);
  4033. xhr.addEventListener("error", function (event) {
  4034. BABYLON.Tools.Error("error on XHR request.");
  4035. callback();
  4036. }, false);
  4037. xhr.send();
  4038. }
  4039. else {
  4040. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4041. callback();
  4042. }
  4043. };
  4044. Database.IsUASupportingBlobStorage = true;
  4045. Database.IDBStorageEnabled = true;
  4046. Database.parseURL = function (url) {
  4047. var a = document.createElement('a');
  4048. a.href = url;
  4049. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4050. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4051. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4052. return absLocation;
  4053. };
  4054. Database.ReturnFullUrlLocation = function (url) {
  4055. if (url.indexOf("http:/") === -1) {
  4056. return (Database.parseURL(window.location.href) + url);
  4057. }
  4058. else {
  4059. return url;
  4060. }
  4061. };
  4062. return Database;
  4063. }());
  4064. BABYLON.Database = Database;
  4065. })(BABYLON || (BABYLON = {}));
  4066. var BABYLON;
  4067. (function (BABYLON) {
  4068. var Internals;
  4069. (function (Internals) {
  4070. /*
  4071. * Based on jsTGALoader - Javascript loader for TGA file
  4072. * By Vincent Thibault
  4073. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4074. */
  4075. var TGATools = (function () {
  4076. function TGATools() {
  4077. }
  4078. TGATools.GetTGAHeader = function (data) {
  4079. var offset = 0;
  4080. var header = {
  4081. id_length: data[offset++],
  4082. colormap_type: data[offset++],
  4083. image_type: data[offset++],
  4084. colormap_index: data[offset++] | data[offset++] << 8,
  4085. colormap_length: data[offset++] | data[offset++] << 8,
  4086. colormap_size: data[offset++],
  4087. origin: [
  4088. data[offset++] | data[offset++] << 8,
  4089. data[offset++] | data[offset++] << 8
  4090. ],
  4091. width: data[offset++] | data[offset++] << 8,
  4092. height: data[offset++] | data[offset++] << 8,
  4093. pixel_size: data[offset++],
  4094. flags: data[offset++]
  4095. };
  4096. return header;
  4097. };
  4098. TGATools.UploadContent = function (gl, data) {
  4099. // Not enough data to contain header ?
  4100. if (data.length < 19) {
  4101. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4102. return;
  4103. }
  4104. // Read Header
  4105. var offset = 18;
  4106. var header = TGATools.GetTGAHeader(data);
  4107. // Assume it's a valid Targa file.
  4108. if (header.id_length + offset > data.length) {
  4109. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4110. return;
  4111. }
  4112. // Skip not needed data
  4113. offset += header.id_length;
  4114. var use_rle = false;
  4115. var use_pal = false;
  4116. var use_rgb = false;
  4117. var use_grey = false;
  4118. // Get some informations.
  4119. switch (header.image_type) {
  4120. case TGATools._TYPE_RLE_INDEXED:
  4121. use_rle = true;
  4122. case TGATools._TYPE_INDEXED:
  4123. use_pal = true;
  4124. break;
  4125. case TGATools._TYPE_RLE_RGB:
  4126. use_rle = true;
  4127. case TGATools._TYPE_RGB:
  4128. use_rgb = true;
  4129. break;
  4130. case TGATools._TYPE_RLE_GREY:
  4131. use_rle = true;
  4132. case TGATools._TYPE_GREY:
  4133. use_grey = true;
  4134. break;
  4135. }
  4136. var pixel_data;
  4137. var numAlphaBits = header.flags & 0xf;
  4138. var pixel_size = header.pixel_size >> 3;
  4139. var pixel_total = header.width * header.height * pixel_size;
  4140. // Read palettes
  4141. var palettes;
  4142. if (use_pal) {
  4143. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4144. }
  4145. // Read LRE
  4146. if (use_rle) {
  4147. pixel_data = new Uint8Array(pixel_total);
  4148. var c, count, i;
  4149. var localOffset = 0;
  4150. var pixels = new Uint8Array(pixel_size);
  4151. while (offset < pixel_total && localOffset < pixel_total) {
  4152. c = data[offset++];
  4153. count = (c & 0x7f) + 1;
  4154. // RLE pixels
  4155. if (c & 0x80) {
  4156. // Bind pixel tmp array
  4157. for (i = 0; i < pixel_size; ++i) {
  4158. pixels[i] = data[offset++];
  4159. }
  4160. // Copy pixel array
  4161. for (i = 0; i < count; ++i) {
  4162. pixel_data.set(pixels, localOffset + i * pixel_size);
  4163. }
  4164. localOffset += pixel_size * count;
  4165. }
  4166. else {
  4167. count *= pixel_size;
  4168. for (i = 0; i < count; ++i) {
  4169. pixel_data[localOffset + i] = data[offset++];
  4170. }
  4171. localOffset += count;
  4172. }
  4173. }
  4174. }
  4175. else {
  4176. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4177. }
  4178. // Load to texture
  4179. var x_start, y_start, x_step, y_step, y_end, x_end;
  4180. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4181. default:
  4182. case TGATools._ORIGIN_UL:
  4183. x_start = 0;
  4184. x_step = 1;
  4185. x_end = header.width;
  4186. y_start = 0;
  4187. y_step = 1;
  4188. y_end = header.height;
  4189. break;
  4190. case TGATools._ORIGIN_BL:
  4191. x_start = 0;
  4192. x_step = 1;
  4193. x_end = header.width;
  4194. y_start = header.height - 1;
  4195. y_step = -1;
  4196. y_end = -1;
  4197. break;
  4198. case TGATools._ORIGIN_UR:
  4199. x_start = header.width - 1;
  4200. x_step = -1;
  4201. x_end = -1;
  4202. y_start = 0;
  4203. y_step = 1;
  4204. y_end = header.height;
  4205. break;
  4206. case TGATools._ORIGIN_BR:
  4207. x_start = header.width - 1;
  4208. x_step = -1;
  4209. x_end = -1;
  4210. y_start = header.height - 1;
  4211. y_step = -1;
  4212. y_end = -1;
  4213. break;
  4214. }
  4215. // Load the specify method
  4216. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4217. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4218. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4219. };
  4220. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4221. var image = pixel_data, colormap = palettes;
  4222. var width = header.width, height = header.height;
  4223. var color, i = 0, x, y;
  4224. var imageData = new Uint8Array(width * height * 4);
  4225. for (y = y_start; y !== y_end; y += y_step) {
  4226. for (x = x_start; x !== x_end; x += x_step, i++) {
  4227. color = image[i];
  4228. imageData[(x + width * y) * 4 + 3] = 255;
  4229. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4230. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4231. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4232. }
  4233. }
  4234. return imageData;
  4235. };
  4236. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4237. var image = pixel_data;
  4238. var width = header.width, height = header.height;
  4239. var color, i = 0, x, y;
  4240. var imageData = new Uint8Array(width * height * 4);
  4241. for (y = y_start; y !== y_end; y += y_step) {
  4242. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4243. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4244. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4245. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4246. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4247. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4248. }
  4249. }
  4250. return imageData;
  4251. };
  4252. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4253. var image = pixel_data;
  4254. var width = header.width, height = header.height;
  4255. var i = 0, x, y;
  4256. var imageData = new Uint8Array(width * height * 4);
  4257. for (y = y_start; y !== y_end; y += y_step) {
  4258. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4259. imageData[(x + width * y) * 4 + 3] = 255;
  4260. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4261. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4262. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4263. }
  4264. }
  4265. return imageData;
  4266. };
  4267. TGATools._getImageData32bits = 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 += 4) {
  4274. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4275. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4276. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4277. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4278. }
  4279. }
  4280. return imageData;
  4281. };
  4282. TGATools._getImageDataGrey8bits = 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 color, 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++) {
  4289. color = image[i];
  4290. imageData[(x + width * y) * 4 + 0] = color;
  4291. imageData[(x + width * y) * 4 + 1] = color;
  4292. imageData[(x + width * y) * 4 + 2] = color;
  4293. imageData[(x + width * y) * 4 + 3] = 255;
  4294. }
  4295. }
  4296. return imageData;
  4297. };
  4298. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4299. var image = pixel_data;
  4300. var width = header.width, height = header.height;
  4301. var i = 0, x, y;
  4302. var imageData = new Uint8Array(width * height * 4);
  4303. for (y = y_start; y !== y_end; y += y_step) {
  4304. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4305. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4306. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4307. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4308. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4309. }
  4310. }
  4311. return imageData;
  4312. };
  4313. TGATools._TYPE_NO_DATA = 0;
  4314. TGATools._TYPE_INDEXED = 1;
  4315. TGATools._TYPE_RGB = 2;
  4316. TGATools._TYPE_GREY = 3;
  4317. TGATools._TYPE_RLE_INDEXED = 9;
  4318. TGATools._TYPE_RLE_RGB = 10;
  4319. TGATools._TYPE_RLE_GREY = 11;
  4320. TGATools._ORIGIN_MASK = 0x30;
  4321. TGATools._ORIGIN_SHIFT = 0x04;
  4322. TGATools._ORIGIN_BL = 0x00;
  4323. TGATools._ORIGIN_BR = 0x01;
  4324. TGATools._ORIGIN_UL = 0x02;
  4325. TGATools._ORIGIN_UR = 0x03;
  4326. return TGATools;
  4327. }());
  4328. Internals.TGATools = TGATools;
  4329. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4330. })(BABYLON || (BABYLON = {}));
  4331. var BABYLON;
  4332. (function (BABYLON) {
  4333. var SmartArray = (function () {
  4334. function SmartArray(capacity) {
  4335. this.length = 0;
  4336. this._duplicateId = 0;
  4337. this.data = new Array(capacity);
  4338. this._id = SmartArray._GlobalId++;
  4339. }
  4340. SmartArray.prototype.push = function (value) {
  4341. this.data[this.length++] = value;
  4342. if (this.length > this.data.length) {
  4343. this.data.length *= 2;
  4344. }
  4345. if (!value.__smartArrayFlags) {
  4346. value.__smartArrayFlags = {};
  4347. }
  4348. value.__smartArrayFlags[this._id] = this._duplicateId;
  4349. };
  4350. SmartArray.prototype.pushNoDuplicate = function (value) {
  4351. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4352. return false;
  4353. }
  4354. this.push(value);
  4355. return true;
  4356. };
  4357. SmartArray.prototype.sort = function (compareFn) {
  4358. this.data.sort(compareFn);
  4359. };
  4360. SmartArray.prototype.reset = function () {
  4361. this.length = 0;
  4362. this._duplicateId++;
  4363. };
  4364. SmartArray.prototype.concat = function (array) {
  4365. if (array.length === 0) {
  4366. return;
  4367. }
  4368. if (this.length + array.length > this.data.length) {
  4369. this.data.length = (this.length + array.length) * 2;
  4370. }
  4371. for (var index = 0; index < array.length; index++) {
  4372. this.data[this.length++] = (array.data || array)[index];
  4373. }
  4374. };
  4375. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4376. if (array.length === 0) {
  4377. return;
  4378. }
  4379. if (this.length + array.length > this.data.length) {
  4380. this.data.length = (this.length + array.length) * 2;
  4381. }
  4382. for (var index = 0; index < array.length; index++) {
  4383. var item = (array.data || array)[index];
  4384. this.pushNoDuplicate(item);
  4385. }
  4386. };
  4387. SmartArray.prototype.indexOf = function (value) {
  4388. var position = this.data.indexOf(value);
  4389. if (position >= this.length) {
  4390. return -1;
  4391. }
  4392. return position;
  4393. };
  4394. // Statics
  4395. SmartArray._GlobalId = 0;
  4396. return SmartArray;
  4397. }());
  4398. BABYLON.SmartArray = SmartArray;
  4399. })(BABYLON || (BABYLON = {}));
  4400. var BABYLON;
  4401. (function (BABYLON) {
  4402. /**
  4403. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4404. * The underlying implementation relies on an associative array to ensure the best performances.
  4405. * The value can be anything including 'null' but except 'undefined'
  4406. */
  4407. var StringDictionary = (function () {
  4408. function StringDictionary() {
  4409. this._count = 0;
  4410. this._data = {};
  4411. }
  4412. /**
  4413. * This will clear this dictionary and copy the content from the 'source' one.
  4414. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4415. * @param source the dictionary to take the content from and copy to this dictionary
  4416. */
  4417. StringDictionary.prototype.copyFrom = function (source) {
  4418. var _this = this;
  4419. this.clear();
  4420. source.forEach(function (t, v) { return _this.add(t, v); });
  4421. };
  4422. /**
  4423. * Get a value based from its key
  4424. * @param key the given key to get the matching value from
  4425. * @return the value if found, otherwise undefined is returned
  4426. */
  4427. StringDictionary.prototype.get = function (key) {
  4428. var val = this._data[key];
  4429. if (val !== undefined) {
  4430. return val;
  4431. }
  4432. return undefined;
  4433. };
  4434. /**
  4435. * Get a value from its key or add it if it doesn't exist.
  4436. * This method will ensure you that a given key/data will be present in the dictionary.
  4437. * @param key the given key to get the matching value from
  4438. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4439. * The factory will only be invoked if there's no data for the given key.
  4440. * @return the value corresponding to the key.
  4441. */
  4442. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4443. var val = this.get(key);
  4444. if (val !== undefined) {
  4445. return val;
  4446. }
  4447. val = factory(key);
  4448. if (val) {
  4449. this.add(key, val);
  4450. }
  4451. return val;
  4452. };
  4453. /**
  4454. * Get a value from its key if present in the dictionary otherwise add it
  4455. * @param key the key to get the value from
  4456. * @param val if there's no such key/value pair in the dictionary add it with this value
  4457. * @return the value corresponding to the key
  4458. */
  4459. StringDictionary.prototype.getOrAdd = function (key, val) {
  4460. var curVal = this.get(key);
  4461. if (curVal !== undefined) {
  4462. return curVal;
  4463. }
  4464. this.add(key, val);
  4465. return val;
  4466. };
  4467. /**
  4468. * Check if there's a given key in the dictionary
  4469. * @param key the key to check for
  4470. * @return true if the key is present, false otherwise
  4471. */
  4472. StringDictionary.prototype.contains = function (key) {
  4473. return this._data[key] !== undefined;
  4474. };
  4475. /**
  4476. * Add a new key and its corresponding value
  4477. * @param key the key to add
  4478. * @param value the value corresponding to the key
  4479. * @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
  4480. */
  4481. StringDictionary.prototype.add = function (key, value) {
  4482. if (this._data[key] !== undefined) {
  4483. return false;
  4484. }
  4485. this._data[key] = value;
  4486. ++this._count;
  4487. return true;
  4488. };
  4489. StringDictionary.prototype.set = function (key, value) {
  4490. if (this._data[key] === undefined) {
  4491. return false;
  4492. }
  4493. this._data[key] = value;
  4494. return true;
  4495. };
  4496. /**
  4497. * Get the element of the given key and remove it from the dictionary
  4498. * @param key
  4499. */
  4500. StringDictionary.prototype.getAndRemove = function (key) {
  4501. var val = this.get(key);
  4502. if (val !== undefined) {
  4503. delete this._data[key];
  4504. --this._count;
  4505. return val;
  4506. }
  4507. return null;
  4508. };
  4509. /**
  4510. * Remove a key/value from the dictionary.
  4511. * @param key the key to remove
  4512. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4513. */
  4514. StringDictionary.prototype.remove = function (key) {
  4515. if (this.contains(key)) {
  4516. delete this._data[key];
  4517. --this._count;
  4518. return true;
  4519. }
  4520. return false;
  4521. };
  4522. /**
  4523. * Clear the whole content of the dictionary
  4524. */
  4525. StringDictionary.prototype.clear = function () {
  4526. this._data = {};
  4527. this._count = 0;
  4528. };
  4529. Object.defineProperty(StringDictionary.prototype, "count", {
  4530. get: function () {
  4531. return this._count;
  4532. },
  4533. enumerable: true,
  4534. configurable: true
  4535. });
  4536. /**
  4537. * Execute a callback on each key/val of the dictionary.
  4538. * Note that you can remove any element in this dictionary in the callback implementation
  4539. * @param callback the callback to execute on a given key/value pair
  4540. */
  4541. StringDictionary.prototype.forEach = function (callback) {
  4542. for (var cur in this._data) {
  4543. var val = this._data[cur];
  4544. callback(cur, val);
  4545. }
  4546. };
  4547. /**
  4548. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4549. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4550. * Note that you can remove any element in this dictionary in the callback implementation
  4551. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4552. */
  4553. StringDictionary.prototype.first = function (callback) {
  4554. for (var cur in this._data) {
  4555. var val = this._data[cur];
  4556. var res = callback(cur, val);
  4557. if (res) {
  4558. return res;
  4559. }
  4560. }
  4561. return null;
  4562. };
  4563. return StringDictionary;
  4564. }());
  4565. BABYLON.StringDictionary = StringDictionary;
  4566. })(BABYLON || (BABYLON = {}));
  4567. var BABYLON;
  4568. (function (BABYLON) {
  4569. // Screenshots
  4570. var screenshotCanvas;
  4571. var cloneValue = function (source, destinationObject) {
  4572. if (!source)
  4573. return null;
  4574. if (source instanceof BABYLON.Mesh) {
  4575. return null;
  4576. }
  4577. if (source instanceof BABYLON.SubMesh) {
  4578. return source.clone(destinationObject);
  4579. }
  4580. else if (source.clone) {
  4581. return source.clone();
  4582. }
  4583. return null;
  4584. };
  4585. var Tools = (function () {
  4586. function Tools() {
  4587. }
  4588. Tools.Instantiate = function (className) {
  4589. var arr = className.split(".");
  4590. var fn = (window || this);
  4591. for (var i = 0, len = arr.length; i < len; i++) {
  4592. fn = fn[arr[i]];
  4593. }
  4594. if (typeof fn !== "function") {
  4595. return null;
  4596. }
  4597. return fn;
  4598. };
  4599. Tools.SetImmediate = function (action) {
  4600. if (window.setImmediate) {
  4601. window.setImmediate(action);
  4602. }
  4603. else {
  4604. setTimeout(action, 1);
  4605. }
  4606. };
  4607. Tools.IsExponentOfTwo = function (value) {
  4608. var count = 1;
  4609. do {
  4610. count *= 2;
  4611. } while (count < value);
  4612. return count === value;
  4613. };
  4614. Tools.GetExponentOfTwo = function (value, max) {
  4615. var count = 1;
  4616. do {
  4617. count *= 2;
  4618. } while (count < value);
  4619. if (count > max)
  4620. count = max;
  4621. return count;
  4622. };
  4623. Tools.GetFilename = function (path) {
  4624. var index = path.lastIndexOf("/");
  4625. if (index < 0)
  4626. return path;
  4627. return path.substring(index + 1);
  4628. };
  4629. Tools.GetDOMTextContent = function (element) {
  4630. var result = "";
  4631. var child = element.firstChild;
  4632. while (child) {
  4633. if (child.nodeType === 3) {
  4634. result += child.textContent;
  4635. }
  4636. child = child.nextSibling;
  4637. }
  4638. return result;
  4639. };
  4640. Tools.ToDegrees = function (angle) {
  4641. return angle * 180 / Math.PI;
  4642. };
  4643. Tools.ToRadians = function (angle) {
  4644. return angle * Math.PI / 180;
  4645. };
  4646. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4647. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4648. var output = "";
  4649. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4650. var i = 0;
  4651. var bytes = new Uint8Array(buffer);
  4652. while (i < bytes.length) {
  4653. chr1 = bytes[i++];
  4654. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4655. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4656. enc1 = chr1 >> 2;
  4657. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4658. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4659. enc4 = chr3 & 63;
  4660. if (isNaN(chr2)) {
  4661. enc3 = enc4 = 64;
  4662. }
  4663. else if (isNaN(chr3)) {
  4664. enc4 = 64;
  4665. }
  4666. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4667. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4668. }
  4669. return "data:image/png;base64," + output;
  4670. };
  4671. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4672. if (bias === void 0) { bias = null; }
  4673. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4674. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4675. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4676. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4677. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4678. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4679. }
  4680. if (bias) {
  4681. minimum.x -= minimum.x * bias.x + bias.y;
  4682. minimum.y -= minimum.y * bias.x + bias.y;
  4683. minimum.z -= minimum.z * bias.x + bias.y;
  4684. maximum.x += maximum.x * bias.x + bias.y;
  4685. maximum.y += maximum.y * bias.x + bias.y;
  4686. maximum.z += maximum.z * bias.x + bias.y;
  4687. }
  4688. return {
  4689. minimum: minimum,
  4690. maximum: maximum
  4691. };
  4692. };
  4693. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4694. if (bias === void 0) { bias = null; }
  4695. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4696. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4697. if (!stride) {
  4698. stride = 3;
  4699. }
  4700. for (var index = start; index < start + count; index++) {
  4701. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4702. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4703. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4704. }
  4705. if (bias) {
  4706. minimum.x -= minimum.x * bias.x + bias.y;
  4707. minimum.y -= minimum.y * bias.x + bias.y;
  4708. minimum.z -= minimum.z * bias.x + bias.y;
  4709. maximum.x += maximum.x * bias.x + bias.y;
  4710. maximum.y += maximum.y * bias.x + bias.y;
  4711. maximum.z += maximum.z * bias.x + bias.y;
  4712. }
  4713. return {
  4714. minimum: minimum,
  4715. maximum: maximum
  4716. };
  4717. };
  4718. Tools.Vector2ArrayFeeder = function (array) {
  4719. return function (index) {
  4720. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4721. var length = isFloatArray ? array.length / 2 : array.length;
  4722. if (index >= length) {
  4723. return null;
  4724. }
  4725. if (isFloatArray) {
  4726. var fa = array;
  4727. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4728. }
  4729. var a = array;
  4730. return a[index];
  4731. };
  4732. };
  4733. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4734. if (bias === void 0) { bias = null; }
  4735. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4736. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4737. var i = 0;
  4738. var cur = feeder(i++);
  4739. while (cur) {
  4740. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4741. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4742. cur = feeder(i++);
  4743. }
  4744. if (bias) {
  4745. minimum.x -= minimum.x * bias.x + bias.y;
  4746. minimum.y -= minimum.y * bias.x + bias.y;
  4747. maximum.x += maximum.x * bias.x + bias.y;
  4748. maximum.y += maximum.y * bias.x + bias.y;
  4749. }
  4750. return {
  4751. minimum: minimum,
  4752. maximum: maximum
  4753. };
  4754. };
  4755. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4756. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4757. return undefined;
  4758. return Array.isArray(obj) ? obj : [obj];
  4759. };
  4760. // Misc.
  4761. Tools.GetPointerPrefix = function () {
  4762. var eventPrefix = "pointer";
  4763. // Check if pointer events are supported
  4764. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4765. eventPrefix = "mouse";
  4766. }
  4767. return eventPrefix;
  4768. };
  4769. /**
  4770. * @param func - the function to be called
  4771. * @param requester - the object that will request the next frame. Falls back to window.
  4772. */
  4773. Tools.QueueNewFrame = function (func, requester) {
  4774. if (requester === void 0) { requester = window; }
  4775. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4776. /*if(requester.isPresenting) {
  4777. return;
  4778. } else*/ if (requester.requestAnimationFrame)
  4779. requester.requestAnimationFrame(func);
  4780. else if (requester.msRequestAnimationFrame)
  4781. requester.msRequestAnimationFrame(func);
  4782. else if (requester.webkitRequestAnimationFrame)
  4783. requester.webkitRequestAnimationFrame(func);
  4784. else if (requester.mozRequestAnimationFrame)
  4785. requester.mozRequestAnimationFrame(func);
  4786. else if (requester.oRequestAnimationFrame)
  4787. requester.oRequestAnimationFrame(func);
  4788. else {
  4789. window.setTimeout(func, 16);
  4790. }
  4791. };
  4792. Tools.RequestFullscreen = function (element) {
  4793. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4794. if (!requestFunction)
  4795. return;
  4796. requestFunction.call(element);
  4797. };
  4798. Tools.ExitFullscreen = function () {
  4799. if (document.exitFullscreen) {
  4800. document.exitFullscreen();
  4801. }
  4802. else if (document.mozCancelFullScreen) {
  4803. document.mozCancelFullScreen();
  4804. }
  4805. else if (document.webkitCancelFullScreen) {
  4806. document.webkitCancelFullScreen();
  4807. }
  4808. else if (document.msCancelFullScreen) {
  4809. document.msCancelFullScreen();
  4810. }
  4811. };
  4812. Tools.SetCorsBehavior = function (url, img) {
  4813. if (Tools.CorsBehavior) {
  4814. switch (typeof (Tools.CorsBehavior)) {
  4815. case "function":
  4816. var result = Tools.CorsBehavior(url);
  4817. if (result) {
  4818. return result;
  4819. }
  4820. break;
  4821. case "string":
  4822. default:
  4823. img.crossOrigin = Tools.CorsBehavior;
  4824. break;
  4825. }
  4826. }
  4827. };
  4828. // External files
  4829. Tools.CleanUrl = function (url) {
  4830. url = url.replace(/#/mg, "%23");
  4831. return url;
  4832. };
  4833. Tools.LoadImage = function (url, onload, onerror, database) {
  4834. if (url instanceof ArrayBuffer) {
  4835. url = Tools.EncodeArrayBufferTobase64(url);
  4836. }
  4837. url = Tools.CleanUrl(url);
  4838. var img = new Image();
  4839. if (url.substr(0, 5) !== "data:") {
  4840. Tools.SetCorsBehavior(url, img);
  4841. }
  4842. img.onload = function () {
  4843. onload(img);
  4844. };
  4845. img.onerror = function (err) {
  4846. Tools.Error("Error while trying to load texture: " + url);
  4847. if (Tools.UseFallbackTexture) {
  4848. 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";
  4849. onload(img);
  4850. }
  4851. else {
  4852. onerror();
  4853. }
  4854. };
  4855. var noIndexedDB = function () {
  4856. img.src = url;
  4857. };
  4858. var loadFromIndexedDB = function () {
  4859. database.loadImageFromDB(url, img);
  4860. };
  4861. //ANY database to do!
  4862. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4863. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4864. }
  4865. else {
  4866. if (url.indexOf("file:") === -1) {
  4867. noIndexedDB();
  4868. }
  4869. else {
  4870. try {
  4871. var textureName = url.substring(5).toLowerCase();
  4872. var blobURL;
  4873. try {
  4874. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4875. }
  4876. catch (ex) {
  4877. // Chrome doesn't support oneTimeOnly parameter
  4878. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4879. }
  4880. img.src = blobURL;
  4881. }
  4882. catch (e) {
  4883. img.src = null;
  4884. }
  4885. }
  4886. }
  4887. return img;
  4888. };
  4889. //ANY
  4890. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4891. url = Tools.CleanUrl(url);
  4892. var noIndexedDB = function () {
  4893. var request = new XMLHttpRequest();
  4894. var loadUrl = Tools.BaseUrl + url;
  4895. request.open('GET', loadUrl, true);
  4896. if (useArrayBuffer) {
  4897. request.responseType = "arraybuffer";
  4898. }
  4899. request.onprogress = progressCallBack;
  4900. request.onreadystatechange = function () {
  4901. if (request.readyState === 4) {
  4902. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4903. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4904. callback(!useArrayBuffer ? request.responseText : request.response);
  4905. }
  4906. else {
  4907. if (onError) {
  4908. onError();
  4909. }
  4910. else {
  4911. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4912. }
  4913. }
  4914. }
  4915. };
  4916. request.send(null);
  4917. };
  4918. var loadFromIndexedDB = function () {
  4919. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4920. };
  4921. if (url.indexOf("file:") !== -1) {
  4922. var fileName = url.substring(5).toLowerCase();
  4923. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4924. }
  4925. else {
  4926. // Caching all files
  4927. if (database && database.enableSceneOffline) {
  4928. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4929. }
  4930. else {
  4931. noIndexedDB();
  4932. }
  4933. }
  4934. };
  4935. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4936. var reader = new FileReader();
  4937. reader.onload = function (e) {
  4938. //target doesn't have result from ts 1.3
  4939. callback(e.target['result']);
  4940. };
  4941. reader.onprogress = progressCallback;
  4942. reader.readAsDataURL(fileToLoad);
  4943. };
  4944. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4945. var reader = new FileReader();
  4946. reader.onerror = function (e) {
  4947. Tools.Log("Error while reading file: " + fileToLoad.name);
  4948. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4949. };
  4950. reader.onload = function (e) {
  4951. //target doesn't have result from ts 1.3
  4952. callback(e.target['result']);
  4953. };
  4954. reader.onprogress = progressCallBack;
  4955. if (!useArrayBuffer) {
  4956. // Asynchronous read
  4957. reader.readAsText(fileToLoad);
  4958. }
  4959. else {
  4960. reader.readAsArrayBuffer(fileToLoad);
  4961. }
  4962. };
  4963. //returns a downloadable url to a file content.
  4964. Tools.FileAsURL = function (content) {
  4965. var fileBlob = new Blob([content]);
  4966. var url = window.URL || window.webkitURL;
  4967. var link = url.createObjectURL(fileBlob);
  4968. return link;
  4969. };
  4970. // Misc.
  4971. Tools.Format = function (value, decimals) {
  4972. if (decimals === void 0) { decimals = 2; }
  4973. return value.toFixed(decimals);
  4974. };
  4975. Tools.CheckExtends = function (v, min, max) {
  4976. if (v.x < min.x)
  4977. min.x = v.x;
  4978. if (v.y < min.y)
  4979. min.y = v.y;
  4980. if (v.z < min.z)
  4981. min.z = v.z;
  4982. if (v.x > max.x)
  4983. max.x = v.x;
  4984. if (v.y > max.y)
  4985. max.y = v.y;
  4986. if (v.z > max.z)
  4987. max.z = v.z;
  4988. };
  4989. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4990. for (var prop in source) {
  4991. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4992. continue;
  4993. }
  4994. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4995. continue;
  4996. }
  4997. var sourceValue = source[prop];
  4998. var typeOfSourceValue = typeof sourceValue;
  4999. if (typeOfSourceValue === "function") {
  5000. continue;
  5001. }
  5002. if (typeOfSourceValue === "object") {
  5003. if (sourceValue instanceof Array) {
  5004. destination[prop] = [];
  5005. if (sourceValue.length > 0) {
  5006. if (typeof sourceValue[0] == "object") {
  5007. for (var index = 0; index < sourceValue.length; index++) {
  5008. var clonedValue = cloneValue(sourceValue[index], destination);
  5009. if (destination[prop].indexOf(clonedValue) === -1) {
  5010. destination[prop].push(clonedValue);
  5011. }
  5012. }
  5013. }
  5014. else {
  5015. destination[prop] = sourceValue.slice(0);
  5016. }
  5017. }
  5018. }
  5019. else {
  5020. destination[prop] = cloneValue(sourceValue, destination);
  5021. }
  5022. }
  5023. else {
  5024. destination[prop] = sourceValue;
  5025. }
  5026. }
  5027. };
  5028. Tools.IsEmpty = function (obj) {
  5029. for (var i in obj) {
  5030. return false;
  5031. }
  5032. return true;
  5033. };
  5034. Tools.RegisterTopRootEvents = function (events) {
  5035. for (var index = 0; index < events.length; index++) {
  5036. var event = events[index];
  5037. window.addEventListener(event.name, event.handler, false);
  5038. try {
  5039. if (window.parent) {
  5040. window.parent.addEventListener(event.name, event.handler, false);
  5041. }
  5042. }
  5043. catch (e) {
  5044. }
  5045. }
  5046. };
  5047. Tools.UnregisterTopRootEvents = function (events) {
  5048. for (var index = 0; index < events.length; index++) {
  5049. var event = events[index];
  5050. window.removeEventListener(event.name, event.handler);
  5051. try {
  5052. if (window.parent) {
  5053. window.parent.removeEventListener(event.name, event.handler);
  5054. }
  5055. }
  5056. catch (e) {
  5057. }
  5058. }
  5059. };
  5060. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5061. if (mimeType === void 0) { mimeType = "image/png"; }
  5062. // Read the contents of the framebuffer
  5063. var numberOfChannelsByLine = width * 4;
  5064. var halfHeight = height / 2;
  5065. //Reading datas from WebGL
  5066. var data = engine.readPixels(0, 0, width, height);
  5067. //To flip image on Y axis.
  5068. for (var i = 0; i < halfHeight; i++) {
  5069. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5070. var currentCell = j + i * numberOfChannelsByLine;
  5071. var targetLine = height - i - 1;
  5072. var targetCell = j + targetLine * numberOfChannelsByLine;
  5073. var temp = data[currentCell];
  5074. data[currentCell] = data[targetCell];
  5075. data[targetCell] = temp;
  5076. }
  5077. }
  5078. // Create a 2D canvas to store the result
  5079. if (!screenshotCanvas) {
  5080. screenshotCanvas = document.createElement('canvas');
  5081. }
  5082. screenshotCanvas.width = width;
  5083. screenshotCanvas.height = height;
  5084. var context = screenshotCanvas.getContext('2d');
  5085. // Copy the pixels to a 2D canvas
  5086. var imageData = context.createImageData(width, height);
  5087. var castData = (imageData.data);
  5088. castData.set(data);
  5089. context.putImageData(imageData, 0, 0);
  5090. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5091. };
  5092. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5093. if (mimeType === void 0) { mimeType = "image/png"; }
  5094. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5095. if (successCallback) {
  5096. successCallback(base64Image);
  5097. }
  5098. else {
  5099. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5100. if (("download" in document.createElement("a"))) {
  5101. var a = window.document.createElement("a");
  5102. a.href = base64Image;
  5103. var date = new Date();
  5104. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5105. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5106. window.document.body.appendChild(a);
  5107. a.addEventListener("click", function () {
  5108. a.parentElement.removeChild(a);
  5109. });
  5110. a.click();
  5111. }
  5112. else {
  5113. var newWindow = window.open("");
  5114. var img = newWindow.document.createElement("img");
  5115. img.src = base64Image;
  5116. newWindow.document.body.appendChild(img);
  5117. }
  5118. }
  5119. };
  5120. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5121. if (mimeType === void 0) { mimeType = "image/png"; }
  5122. var width;
  5123. var height;
  5124. // If a precision value is specified
  5125. if (size.precision) {
  5126. width = Math.round(engine.getRenderWidth() * size.precision);
  5127. height = Math.round(width / engine.getAspectRatio(camera));
  5128. }
  5129. else if (size.width && size.height) {
  5130. width = size.width;
  5131. height = size.height;
  5132. }
  5133. else if (size.width && !size.height) {
  5134. width = size.width;
  5135. height = Math.round(width / engine.getAspectRatio(camera));
  5136. }
  5137. else if (size.height && !size.width) {
  5138. height = size.height;
  5139. width = Math.round(height * engine.getAspectRatio(camera));
  5140. }
  5141. else if (!isNaN(size)) {
  5142. height = size;
  5143. width = size;
  5144. }
  5145. else {
  5146. Tools.Error("Invalid 'size' parameter !");
  5147. return;
  5148. }
  5149. if (!screenshotCanvas) {
  5150. screenshotCanvas = document.createElement('canvas');
  5151. }
  5152. screenshotCanvas.width = width;
  5153. screenshotCanvas.height = height;
  5154. var renderContext = screenshotCanvas.getContext("2d");
  5155. renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
  5156. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5157. };
  5158. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5159. if (mimeType === void 0) { mimeType = "image/png"; }
  5160. var width;
  5161. var height;
  5162. //If a precision value is specified
  5163. if (size.precision) {
  5164. width = Math.round(engine.getRenderWidth() * size.precision);
  5165. height = Math.round(width / engine.getAspectRatio(camera));
  5166. size = { width: width, height: height };
  5167. }
  5168. else if (size.width && size.height) {
  5169. width = size.width;
  5170. height = size.height;
  5171. }
  5172. else if (size.width && !size.height) {
  5173. width = size.width;
  5174. height = Math.round(width / engine.getAspectRatio(camera));
  5175. size = { width: width, height: height };
  5176. }
  5177. else if (size.height && !size.width) {
  5178. height = size.height;
  5179. width = Math.round(height * engine.getAspectRatio(camera));
  5180. size = { width: width, height: height };
  5181. }
  5182. else if (!isNaN(size)) {
  5183. height = size;
  5184. width = size;
  5185. }
  5186. else {
  5187. Tools.Error("Invalid 'size' parameter !");
  5188. return;
  5189. }
  5190. var scene = camera.getScene();
  5191. var previousCamera = null;
  5192. if (scene.activeCamera !== camera) {
  5193. previousCamera = scene.activeCamera;
  5194. scene.activeCamera = camera;
  5195. }
  5196. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5197. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5198. texture.renderList = scene.meshes;
  5199. texture.onAfterRenderObservable.add(function () {
  5200. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5201. });
  5202. scene.incrementRenderId();
  5203. scene.resetCachedMaterial();
  5204. texture.render(true);
  5205. texture.dispose();
  5206. if (previousCamera) {
  5207. scene.activeCamera = previousCamera;
  5208. }
  5209. camera.getProjectionMatrix(true); // Force cache refresh;
  5210. };
  5211. // XHR response validator for local file scenario
  5212. Tools.ValidateXHRData = function (xhr, dataType) {
  5213. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5214. if (dataType === void 0) { dataType = 7; }
  5215. try {
  5216. if (dataType & 1) {
  5217. if (xhr.responseText && xhr.responseText.length > 0) {
  5218. return true;
  5219. }
  5220. else if (dataType === 1) {
  5221. return false;
  5222. }
  5223. }
  5224. if (dataType & 2) {
  5225. // Check header width and height since there is no "TGA" magic number
  5226. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5227. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5228. return true;
  5229. }
  5230. else if (dataType === 2) {
  5231. return false;
  5232. }
  5233. }
  5234. if (dataType & 4) {
  5235. // Check for the "DDS" magic number
  5236. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5237. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5238. return true;
  5239. }
  5240. else {
  5241. return false;
  5242. }
  5243. }
  5244. }
  5245. catch (e) {
  5246. }
  5247. return false;
  5248. };
  5249. /**
  5250. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5251. * Be aware Math.random() could cause collisions, but:
  5252. * "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"
  5253. */
  5254. Tools.RandomId = function () {
  5255. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5256. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5257. return v.toString(16);
  5258. });
  5259. };
  5260. Object.defineProperty(Tools, "NoneLogLevel", {
  5261. get: function () {
  5262. return Tools._NoneLogLevel;
  5263. },
  5264. enumerable: true,
  5265. configurable: true
  5266. });
  5267. Object.defineProperty(Tools, "MessageLogLevel", {
  5268. get: function () {
  5269. return Tools._MessageLogLevel;
  5270. },
  5271. enumerable: true,
  5272. configurable: true
  5273. });
  5274. Object.defineProperty(Tools, "WarningLogLevel", {
  5275. get: function () {
  5276. return Tools._WarningLogLevel;
  5277. },
  5278. enumerable: true,
  5279. configurable: true
  5280. });
  5281. Object.defineProperty(Tools, "ErrorLogLevel", {
  5282. get: function () {
  5283. return Tools._ErrorLogLevel;
  5284. },
  5285. enumerable: true,
  5286. configurable: true
  5287. });
  5288. Object.defineProperty(Tools, "AllLogLevel", {
  5289. get: function () {
  5290. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5291. },
  5292. enumerable: true,
  5293. configurable: true
  5294. });
  5295. Tools._AddLogEntry = function (entry) {
  5296. Tools._LogCache = entry + Tools._LogCache;
  5297. if (Tools.OnNewCacheEntry) {
  5298. Tools.OnNewCacheEntry(entry);
  5299. }
  5300. };
  5301. Tools._FormatMessage = function (message) {
  5302. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5303. var date = new Date();
  5304. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5305. };
  5306. Tools._LogDisabled = function (message) {
  5307. // nothing to do
  5308. };
  5309. Tools._LogEnabled = function (message) {
  5310. var formattedMessage = Tools._FormatMessage(message);
  5311. console.log("BJS - " + formattedMessage);
  5312. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5313. Tools._AddLogEntry(entry);
  5314. };
  5315. Tools._WarnDisabled = function (message) {
  5316. // nothing to do
  5317. };
  5318. Tools._WarnEnabled = function (message) {
  5319. var formattedMessage = Tools._FormatMessage(message);
  5320. console.warn("BJS - " + formattedMessage);
  5321. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5322. Tools._AddLogEntry(entry);
  5323. };
  5324. Tools._ErrorDisabled = function (message) {
  5325. // nothing to do
  5326. };
  5327. Tools._ErrorEnabled = function (message) {
  5328. Tools.errorsCount++;
  5329. var formattedMessage = Tools._FormatMessage(message);
  5330. console.error("BJS - " + formattedMessage);
  5331. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5332. Tools._AddLogEntry(entry);
  5333. };
  5334. Object.defineProperty(Tools, "LogCache", {
  5335. get: function () {
  5336. return Tools._LogCache;
  5337. },
  5338. enumerable: true,
  5339. configurable: true
  5340. });
  5341. Tools.ClearLogCache = function () {
  5342. Tools._LogCache = "";
  5343. Tools.errorsCount = 0;
  5344. };
  5345. Object.defineProperty(Tools, "LogLevels", {
  5346. set: function (level) {
  5347. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5348. Tools.Log = Tools._LogEnabled;
  5349. }
  5350. else {
  5351. Tools.Log = Tools._LogDisabled;
  5352. }
  5353. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5354. Tools.Warn = Tools._WarnEnabled;
  5355. }
  5356. else {
  5357. Tools.Warn = Tools._WarnDisabled;
  5358. }
  5359. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5360. Tools.Error = Tools._ErrorEnabled;
  5361. }
  5362. else {
  5363. Tools.Error = Tools._ErrorDisabled;
  5364. }
  5365. },
  5366. enumerable: true,
  5367. configurable: true
  5368. });
  5369. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5370. get: function () {
  5371. return Tools._PerformanceNoneLogLevel;
  5372. },
  5373. enumerable: true,
  5374. configurable: true
  5375. });
  5376. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5377. get: function () {
  5378. return Tools._PerformanceUserMarkLogLevel;
  5379. },
  5380. enumerable: true,
  5381. configurable: true
  5382. });
  5383. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5384. get: function () {
  5385. return Tools._PerformanceConsoleLogLevel;
  5386. },
  5387. enumerable: true,
  5388. configurable: true
  5389. });
  5390. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5391. set: function (level) {
  5392. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5393. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5394. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5395. return;
  5396. }
  5397. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5398. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5399. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5400. return;
  5401. }
  5402. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5403. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5404. },
  5405. enumerable: true,
  5406. configurable: true
  5407. });
  5408. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5409. };
  5410. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5411. };
  5412. Tools._StartUserMark = function (counterName, condition) {
  5413. if (condition === void 0) { condition = true; }
  5414. if (!condition || !Tools._performance.mark) {
  5415. return;
  5416. }
  5417. Tools._performance.mark(counterName + "-Begin");
  5418. };
  5419. Tools._EndUserMark = function (counterName, condition) {
  5420. if (condition === void 0) { condition = true; }
  5421. if (!condition || !Tools._performance.mark) {
  5422. return;
  5423. }
  5424. Tools._performance.mark(counterName + "-End");
  5425. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5426. };
  5427. Tools._StartPerformanceConsole = function (counterName, condition) {
  5428. if (condition === void 0) { condition = true; }
  5429. if (!condition) {
  5430. return;
  5431. }
  5432. Tools._StartUserMark(counterName, condition);
  5433. if (console.time) {
  5434. console.time(counterName);
  5435. }
  5436. };
  5437. Tools._EndPerformanceConsole = function (counterName, condition) {
  5438. if (condition === void 0) { condition = true; }
  5439. if (!condition) {
  5440. return;
  5441. }
  5442. Tools._EndUserMark(counterName, condition);
  5443. if (console.time) {
  5444. console.timeEnd(counterName);
  5445. }
  5446. };
  5447. Object.defineProperty(Tools, "Now", {
  5448. get: function () {
  5449. if (window.performance && window.performance.now) {
  5450. return window.performance.now();
  5451. }
  5452. return new Date().getTime();
  5453. },
  5454. enumerable: true,
  5455. configurable: true
  5456. });
  5457. /**
  5458. * This method will return the name of the class used to create the instance of the given object.
  5459. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5460. * @param object the object to get the class name from
  5461. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5462. */
  5463. Tools.getClassName = function (object, isType) {
  5464. if (isType === void 0) { isType = false; }
  5465. var name = null;
  5466. if (!isType && object.getClassName) {
  5467. name = object.getClassName();
  5468. }
  5469. else {
  5470. if (object instanceof Object) {
  5471. var classObj = isType ? object : Object.getPrototypeOf(object);
  5472. name = classObj.constructor["__bjsclassName__"];
  5473. }
  5474. if (!name) {
  5475. name = typeof object;
  5476. }
  5477. }
  5478. return name;
  5479. };
  5480. Tools.first = function (array, predicate) {
  5481. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5482. var el = array_1[_i];
  5483. if (predicate(el)) {
  5484. return el;
  5485. }
  5486. }
  5487. };
  5488. /**
  5489. * This method will return the name of the full name of the class, including its owning module (if any).
  5490. * 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).
  5491. * @param object the object to get the class name from
  5492. * @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.
  5493. */
  5494. Tools.getFullClassName = function (object, isType) {
  5495. if (isType === void 0) { isType = false; }
  5496. var className = null;
  5497. var moduleName = null;
  5498. if (!isType && object.getClassName) {
  5499. className = object.getClassName();
  5500. }
  5501. else {
  5502. if (object instanceof Object) {
  5503. var classObj = isType ? object : Object.getPrototypeOf(object);
  5504. className = classObj.constructor["__bjsclassName__"];
  5505. moduleName = classObj.constructor["__bjsmoduleName__"];
  5506. }
  5507. if (!className) {
  5508. className = typeof object;
  5509. }
  5510. }
  5511. if (!className) {
  5512. return null;
  5513. }
  5514. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5515. };
  5516. /**
  5517. * 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.
  5518. * @param array
  5519. */
  5520. Tools.arrayOrStringFeeder = function (array) {
  5521. return function (index) {
  5522. if (index >= array.length) {
  5523. return null;
  5524. }
  5525. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5526. if (val && val.getHashCode) {
  5527. val = val.getHashCode();
  5528. }
  5529. if (typeof val === "string") {
  5530. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5531. }
  5532. return val;
  5533. };
  5534. };
  5535. /**
  5536. * Compute the hashCode of a stream of number
  5537. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5538. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5539. * @return the hash code computed
  5540. */
  5541. Tools.hashCodeFromStream = function (feeder) {
  5542. // Based from here: http://stackoverflow.com/a/7616484/802124
  5543. var hash = 0;
  5544. var index = 0;
  5545. var chr = feeder(index++);
  5546. while (chr != null) {
  5547. hash = ((hash << 5) - hash) + chr;
  5548. hash |= 0; // Convert to 32bit integer
  5549. chr = feeder(index++);
  5550. }
  5551. return hash;
  5552. };
  5553. Tools.BaseUrl = "";
  5554. Tools.CorsBehavior = "anonymous";
  5555. Tools.UseFallbackTexture = true;
  5556. // Logs
  5557. Tools._NoneLogLevel = 0;
  5558. Tools._MessageLogLevel = 1;
  5559. Tools._WarningLogLevel = 2;
  5560. Tools._ErrorLogLevel = 4;
  5561. Tools._LogCache = "";
  5562. Tools.errorsCount = 0;
  5563. Tools.Log = Tools._LogEnabled;
  5564. Tools.Warn = Tools._WarnEnabled;
  5565. Tools.Error = Tools._ErrorEnabled;
  5566. // Performances
  5567. Tools._PerformanceNoneLogLevel = 0;
  5568. Tools._PerformanceUserMarkLogLevel = 1;
  5569. Tools._PerformanceConsoleLogLevel = 2;
  5570. Tools._performance = window.performance;
  5571. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5572. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5573. return Tools;
  5574. }());
  5575. BABYLON.Tools = Tools;
  5576. /**
  5577. * This class is used to track a performance counter which is number based.
  5578. * The user has access to many properties which give statistics of different nature
  5579. *
  5580. * The implementer can track two kinds of Performance Counter: time and count
  5581. * 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.
  5582. * 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.
  5583. */
  5584. var PerfCounter = (function () {
  5585. function PerfCounter() {
  5586. this._startMonitoringTime = 0;
  5587. this._min = 0;
  5588. this._max = 0;
  5589. this._average = 0;
  5590. this._lastSecAverage = 0;
  5591. this._current = 0;
  5592. this._totalValueCount = 0;
  5593. this._totalAccumulated = 0;
  5594. this._lastSecAccumulated = 0;
  5595. this._lastSecTime = 0;
  5596. this._lastSecValueCount = 0;
  5597. }
  5598. Object.defineProperty(PerfCounter.prototype, "min", {
  5599. /**
  5600. * Returns the smallest value ever
  5601. */
  5602. get: function () {
  5603. return this._min;
  5604. },
  5605. enumerable: true,
  5606. configurable: true
  5607. });
  5608. Object.defineProperty(PerfCounter.prototype, "max", {
  5609. /**
  5610. * Returns the biggest value ever
  5611. */
  5612. get: function () {
  5613. return this._max;
  5614. },
  5615. enumerable: true,
  5616. configurable: true
  5617. });
  5618. Object.defineProperty(PerfCounter.prototype, "average", {
  5619. /**
  5620. * Returns the average value since the performance counter is running
  5621. */
  5622. get: function () {
  5623. return this._average;
  5624. },
  5625. enumerable: true,
  5626. configurable: true
  5627. });
  5628. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5629. /**
  5630. * Returns the average value of the last second the counter was monitored
  5631. */
  5632. get: function () {
  5633. return this._lastSecAverage;
  5634. },
  5635. enumerable: true,
  5636. configurable: true
  5637. });
  5638. Object.defineProperty(PerfCounter.prototype, "current", {
  5639. /**
  5640. * Returns the current value
  5641. */
  5642. get: function () {
  5643. return this._current;
  5644. },
  5645. enumerable: true,
  5646. configurable: true
  5647. });
  5648. Object.defineProperty(PerfCounter.prototype, "total", {
  5649. get: function () {
  5650. return this._totalAccumulated;
  5651. },
  5652. enumerable: true,
  5653. configurable: true
  5654. });
  5655. /**
  5656. * Call this method to start monitoring a new frame.
  5657. * 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.
  5658. */
  5659. PerfCounter.prototype.fetchNewFrame = function () {
  5660. this._totalValueCount++;
  5661. this._current = 0;
  5662. this._lastSecValueCount++;
  5663. };
  5664. /**
  5665. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5666. * @param newCount the count value to add to the monitored count
  5667. * @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.
  5668. */
  5669. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5670. this._current += newCount;
  5671. if (fetchResult) {
  5672. this._fetchResult();
  5673. }
  5674. };
  5675. /**
  5676. * Start monitoring this performance counter
  5677. */
  5678. PerfCounter.prototype.beginMonitoring = function () {
  5679. this._startMonitoringTime = Tools.Now;
  5680. };
  5681. /**
  5682. * Compute the time lapsed since the previous beginMonitoring() call.
  5683. * @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
  5684. */
  5685. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5686. if (newFrame === void 0) { newFrame = true; }
  5687. if (newFrame) {
  5688. this.fetchNewFrame();
  5689. }
  5690. var currentTime = Tools.Now;
  5691. this._current = currentTime - this._startMonitoringTime;
  5692. if (newFrame) {
  5693. this._fetchResult();
  5694. }
  5695. };
  5696. PerfCounter.prototype._fetchResult = function () {
  5697. this._totalAccumulated += this._current;
  5698. this._lastSecAccumulated += this._current;
  5699. // Min/Max update
  5700. this._min = Math.min(this._min, this._current);
  5701. this._max = Math.max(this._max, this._current);
  5702. this._average = this._totalAccumulated / this._totalValueCount;
  5703. // Reset last sec?
  5704. var now = Tools.Now;
  5705. if ((now - this._lastSecTime) > 1000) {
  5706. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5707. this._lastSecTime = now;
  5708. this._lastSecAccumulated = 0;
  5709. this._lastSecValueCount = 0;
  5710. }
  5711. };
  5712. return PerfCounter;
  5713. }());
  5714. BABYLON.PerfCounter = PerfCounter;
  5715. /**
  5716. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5717. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5718. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5719. * @param name The name of the class, case should be preserved
  5720. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5721. */
  5722. function className(name, module) {
  5723. return function (target) {
  5724. target["__bjsclassName__"] = name;
  5725. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5726. };
  5727. }
  5728. BABYLON.className = className;
  5729. /**
  5730. * An implementation of a loop for asynchronous functions.
  5731. */
  5732. var AsyncLoop = (function () {
  5733. /**
  5734. * Constroctor.
  5735. * @param iterations the number of iterations.
  5736. * @param _fn the function to run each iteration
  5737. * @param _successCallback the callback that will be called upon succesful execution
  5738. * @param offset starting offset.
  5739. */
  5740. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5741. if (offset === void 0) { offset = 0; }
  5742. this.iterations = iterations;
  5743. this._fn = _fn;
  5744. this._successCallback = _successCallback;
  5745. this.index = offset - 1;
  5746. this._done = false;
  5747. }
  5748. /**
  5749. * Execute the next iteration. Must be called after the last iteration was finished.
  5750. */
  5751. AsyncLoop.prototype.executeNext = function () {
  5752. if (!this._done) {
  5753. if (this.index + 1 < this.iterations) {
  5754. ++this.index;
  5755. this._fn(this);
  5756. }
  5757. else {
  5758. this.breakLoop();
  5759. }
  5760. }
  5761. };
  5762. /**
  5763. * Break the loop and run the success callback.
  5764. */
  5765. AsyncLoop.prototype.breakLoop = function () {
  5766. this._done = true;
  5767. this._successCallback();
  5768. };
  5769. /**
  5770. * Helper function
  5771. */
  5772. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5773. if (offset === void 0) { offset = 0; }
  5774. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5775. loop.executeNext();
  5776. return loop;
  5777. };
  5778. /**
  5779. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5780. * @param iterations total number of iterations
  5781. * @param syncedIterations number of synchronous iterations in each async iteration.
  5782. * @param fn the function to call each iteration.
  5783. * @param callback a success call back that will be called when iterating stops.
  5784. * @param breakFunction a break condition (optional)
  5785. * @param timeout timeout settings for the setTimeout function. default - 0.
  5786. * @constructor
  5787. */
  5788. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5789. if (timeout === void 0) { timeout = 0; }
  5790. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5791. if (breakFunction && breakFunction())
  5792. loop.breakLoop();
  5793. else {
  5794. setTimeout(function () {
  5795. for (var i = 0; i < syncedIterations; ++i) {
  5796. var iteration = (loop.index * syncedIterations) + i;
  5797. if (iteration >= iterations)
  5798. break;
  5799. fn(iteration);
  5800. if (breakFunction && breakFunction()) {
  5801. loop.breakLoop();
  5802. break;
  5803. }
  5804. }
  5805. loop.executeNext();
  5806. }, timeout);
  5807. }
  5808. }, callback);
  5809. };
  5810. return AsyncLoop;
  5811. }());
  5812. BABYLON.AsyncLoop = AsyncLoop;
  5813. })(BABYLON || (BABYLON = {}));
  5814. var BABYLON;
  5815. (function (BABYLON) {
  5816. var Internals;
  5817. (function (Internals) {
  5818. var _AlphaState = (function () {
  5819. function _AlphaState() {
  5820. this._isAlphaBlendDirty = false;
  5821. this._isBlendFunctionParametersDirty = false;
  5822. this._alphaBlend = false;
  5823. this._blendFunctionParameters = new Array(4);
  5824. }
  5825. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5826. get: function () {
  5827. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5828. },
  5829. enumerable: true,
  5830. configurable: true
  5831. });
  5832. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5833. get: function () {
  5834. return this._alphaBlend;
  5835. },
  5836. set: function (value) {
  5837. if (this._alphaBlend === value) {
  5838. return;
  5839. }
  5840. this._alphaBlend = value;
  5841. this._isAlphaBlendDirty = true;
  5842. },
  5843. enumerable: true,
  5844. configurable: true
  5845. });
  5846. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5847. if (this._blendFunctionParameters[0] === value0 &&
  5848. this._blendFunctionParameters[1] === value1 &&
  5849. this._blendFunctionParameters[2] === value2 &&
  5850. this._blendFunctionParameters[3] === value3) {
  5851. return;
  5852. }
  5853. this._blendFunctionParameters[0] = value0;
  5854. this._blendFunctionParameters[1] = value1;
  5855. this._blendFunctionParameters[2] = value2;
  5856. this._blendFunctionParameters[3] = value3;
  5857. this._isBlendFunctionParametersDirty = true;
  5858. };
  5859. _AlphaState.prototype.reset = function () {
  5860. this._alphaBlend = false;
  5861. this._blendFunctionParameters[0] = null;
  5862. this._blendFunctionParameters[1] = null;
  5863. this._blendFunctionParameters[2] = null;
  5864. this._blendFunctionParameters[3] = null;
  5865. this._isAlphaBlendDirty = true;
  5866. this._isBlendFunctionParametersDirty = false;
  5867. };
  5868. _AlphaState.prototype.apply = function (gl) {
  5869. if (!this.isDirty) {
  5870. return;
  5871. }
  5872. // Alpha blend
  5873. if (this._isAlphaBlendDirty) {
  5874. if (this._alphaBlend) {
  5875. gl.enable(gl.BLEND);
  5876. }
  5877. else {
  5878. gl.disable(gl.BLEND);
  5879. }
  5880. this._isAlphaBlendDirty = false;
  5881. }
  5882. // Alpha function
  5883. if (this._isBlendFunctionParametersDirty) {
  5884. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5885. this._isBlendFunctionParametersDirty = false;
  5886. }
  5887. };
  5888. return _AlphaState;
  5889. }());
  5890. Internals._AlphaState = _AlphaState;
  5891. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5892. })(BABYLON || (BABYLON = {}));
  5893. var BABYLON;
  5894. (function (BABYLON) {
  5895. var Internals;
  5896. (function (Internals) {
  5897. var _DepthCullingState = (function () {
  5898. function _DepthCullingState() {
  5899. this._isDepthTestDirty = false;
  5900. this._isDepthMaskDirty = false;
  5901. this._isDepthFuncDirty = false;
  5902. this._isCullFaceDirty = false;
  5903. this._isCullDirty = false;
  5904. this._isZOffsetDirty = false;
  5905. }
  5906. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5907. get: function () {
  5908. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5909. },
  5910. enumerable: true,
  5911. configurable: true
  5912. });
  5913. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5914. get: function () {
  5915. return this._zOffset;
  5916. },
  5917. set: function (value) {
  5918. if (this._zOffset === value) {
  5919. return;
  5920. }
  5921. this._zOffset = value;
  5922. this._isZOffsetDirty = true;
  5923. },
  5924. enumerable: true,
  5925. configurable: true
  5926. });
  5927. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5928. get: function () {
  5929. return this._cullFace;
  5930. },
  5931. set: function (value) {
  5932. if (this._cullFace === value) {
  5933. return;
  5934. }
  5935. this._cullFace = value;
  5936. this._isCullFaceDirty = true;
  5937. },
  5938. enumerable: true,
  5939. configurable: true
  5940. });
  5941. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5942. get: function () {
  5943. return this._cull;
  5944. },
  5945. set: function (value) {
  5946. if (this._cull === value) {
  5947. return;
  5948. }
  5949. this._cull = value;
  5950. this._isCullDirty = true;
  5951. },
  5952. enumerable: true,
  5953. configurable: true
  5954. });
  5955. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5956. get: function () {
  5957. return this._depthFunc;
  5958. },
  5959. set: function (value) {
  5960. if (this._depthFunc === value) {
  5961. return;
  5962. }
  5963. this._depthFunc = value;
  5964. this._isDepthFuncDirty = true;
  5965. },
  5966. enumerable: true,
  5967. configurable: true
  5968. });
  5969. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5970. get: function () {
  5971. return this._depthMask;
  5972. },
  5973. set: function (value) {
  5974. if (this._depthMask === value) {
  5975. return;
  5976. }
  5977. this._depthMask = value;
  5978. this._isDepthMaskDirty = true;
  5979. },
  5980. enumerable: true,
  5981. configurable: true
  5982. });
  5983. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5984. get: function () {
  5985. return this._depthTest;
  5986. },
  5987. set: function (value) {
  5988. if (this._depthTest === value) {
  5989. return;
  5990. }
  5991. this._depthTest = value;
  5992. this._isDepthTestDirty = true;
  5993. },
  5994. enumerable: true,
  5995. configurable: true
  5996. });
  5997. _DepthCullingState.prototype.reset = function () {
  5998. this._depthMask = true;
  5999. this._depthTest = true;
  6000. this._depthFunc = null;
  6001. this._cullFace = null;
  6002. this._cull = null;
  6003. this._zOffset = 0;
  6004. this._isDepthTestDirty = true;
  6005. this._isDepthMaskDirty = true;
  6006. this._isDepthFuncDirty = false;
  6007. this._isCullFaceDirty = false;
  6008. this._isCullDirty = false;
  6009. this._isZOffsetDirty = false;
  6010. };
  6011. _DepthCullingState.prototype.apply = function (gl) {
  6012. if (!this.isDirty) {
  6013. return;
  6014. }
  6015. // Cull
  6016. if (this._isCullDirty) {
  6017. if (this.cull) {
  6018. gl.enable(gl.CULL_FACE);
  6019. }
  6020. else {
  6021. gl.disable(gl.CULL_FACE);
  6022. }
  6023. this._isCullDirty = false;
  6024. }
  6025. // Cull face
  6026. if (this._isCullFaceDirty) {
  6027. gl.cullFace(this.cullFace);
  6028. this._isCullFaceDirty = false;
  6029. }
  6030. // Depth mask
  6031. if (this._isDepthMaskDirty) {
  6032. gl.depthMask(this.depthMask);
  6033. this._isDepthMaskDirty = false;
  6034. }
  6035. // Depth test
  6036. if (this._isDepthTestDirty) {
  6037. if (this.depthTest) {
  6038. gl.enable(gl.DEPTH_TEST);
  6039. }
  6040. else {
  6041. gl.disable(gl.DEPTH_TEST);
  6042. }
  6043. this._isDepthTestDirty = false;
  6044. }
  6045. // Depth func
  6046. if (this._isDepthFuncDirty) {
  6047. gl.depthFunc(this.depthFunc);
  6048. this._isDepthFuncDirty = false;
  6049. }
  6050. // zOffset
  6051. if (this._isZOffsetDirty) {
  6052. if (this.zOffset) {
  6053. gl.enable(gl.POLYGON_OFFSET_FILL);
  6054. gl.polygonOffset(this.zOffset, 0);
  6055. }
  6056. else {
  6057. gl.disable(gl.POLYGON_OFFSET_FILL);
  6058. }
  6059. this._isZOffsetDirty = false;
  6060. }
  6061. };
  6062. return _DepthCullingState;
  6063. }());
  6064. Internals._DepthCullingState = _DepthCullingState;
  6065. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6066. })(BABYLON || (BABYLON = {}));
  6067. var BABYLON;
  6068. (function (BABYLON) {
  6069. var Internals;
  6070. (function (Internals) {
  6071. var _StencilState = (function () {
  6072. function _StencilState() {
  6073. this._isStencilTestDirty = false;
  6074. this._isStencilMaskDirty = false;
  6075. this._isStencilFuncDirty = false;
  6076. this._isStencilOpDirty = false;
  6077. this.reset();
  6078. }
  6079. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6080. get: function () {
  6081. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6082. },
  6083. enumerable: true,
  6084. configurable: true
  6085. });
  6086. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6087. get: function () {
  6088. return this._stencilFunc;
  6089. },
  6090. set: function (value) {
  6091. if (this._stencilFunc === value) {
  6092. return;
  6093. }
  6094. this._stencilFunc = value;
  6095. this._isStencilFuncDirty = true;
  6096. },
  6097. enumerable: true,
  6098. configurable: true
  6099. });
  6100. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6101. get: function () {
  6102. return this._stencilFuncRef;
  6103. },
  6104. set: function (value) {
  6105. if (this._stencilFuncRef === value) {
  6106. return;
  6107. }
  6108. this._stencilFuncRef = value;
  6109. this._isStencilFuncDirty = true;
  6110. },
  6111. enumerable: true,
  6112. configurable: true
  6113. });
  6114. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6115. get: function () {
  6116. return this._stencilFuncMask;
  6117. },
  6118. set: function (value) {
  6119. if (this._stencilFuncMask === value) {
  6120. return;
  6121. }
  6122. this._stencilFuncMask = value;
  6123. this._isStencilFuncDirty = true;
  6124. },
  6125. enumerable: true,
  6126. configurable: true
  6127. });
  6128. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6129. get: function () {
  6130. return this._stencilOpStencilFail;
  6131. },
  6132. set: function (value) {
  6133. if (this._stencilOpStencilFail === value) {
  6134. return;
  6135. }
  6136. this._stencilOpStencilFail = value;
  6137. this._isStencilOpDirty = true;
  6138. },
  6139. enumerable: true,
  6140. configurable: true
  6141. });
  6142. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6143. get: function () {
  6144. return this._stencilOpDepthFail;
  6145. },
  6146. set: function (value) {
  6147. if (this._stencilOpDepthFail === value) {
  6148. return;
  6149. }
  6150. this._stencilOpDepthFail = value;
  6151. this._isStencilOpDirty = true;
  6152. },
  6153. enumerable: true,
  6154. configurable: true
  6155. });
  6156. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6157. get: function () {
  6158. return this._stencilOpStencilDepthPass;
  6159. },
  6160. set: function (value) {
  6161. if (this._stencilOpStencilDepthPass === value) {
  6162. return;
  6163. }
  6164. this._stencilOpStencilDepthPass = value;
  6165. this._isStencilOpDirty = true;
  6166. },
  6167. enumerable: true,
  6168. configurable: true
  6169. });
  6170. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6171. get: function () {
  6172. return this._stencilMask;
  6173. },
  6174. set: function (value) {
  6175. if (this._stencilMask === value) {
  6176. return;
  6177. }
  6178. this._stencilMask = value;
  6179. this._isStencilMaskDirty = true;
  6180. },
  6181. enumerable: true,
  6182. configurable: true
  6183. });
  6184. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6185. get: function () {
  6186. return this._stencilTest;
  6187. },
  6188. set: function (value) {
  6189. if (this._stencilTest === value) {
  6190. return;
  6191. }
  6192. this._stencilTest = value;
  6193. this._isStencilTestDirty = true;
  6194. },
  6195. enumerable: true,
  6196. configurable: true
  6197. });
  6198. _StencilState.prototype.reset = function () {
  6199. this._stencilTest = false;
  6200. this._stencilMask = 0xFF;
  6201. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6202. this._stencilFuncRef = 1;
  6203. this._stencilFuncMask = 0xFF;
  6204. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6205. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6206. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6207. this._isStencilTestDirty = true;
  6208. this._isStencilMaskDirty = true;
  6209. this._isStencilFuncDirty = true;
  6210. this._isStencilOpDirty = true;
  6211. };
  6212. _StencilState.prototype.apply = function (gl) {
  6213. if (!this.isDirty) {
  6214. return;
  6215. }
  6216. // Stencil test
  6217. if (this._isStencilTestDirty) {
  6218. if (this.stencilTest) {
  6219. gl.enable(gl.STENCIL_TEST);
  6220. }
  6221. else {
  6222. gl.disable(gl.STENCIL_TEST);
  6223. }
  6224. this._isStencilTestDirty = false;
  6225. }
  6226. // Stencil mask
  6227. if (this._isStencilMaskDirty) {
  6228. gl.stencilMask(this.stencilMask);
  6229. this._isStencilMaskDirty = false;
  6230. }
  6231. // Stencil func
  6232. if (this._isStencilFuncDirty) {
  6233. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6234. this._isStencilFuncDirty = false;
  6235. }
  6236. // Stencil op
  6237. if (this._isStencilOpDirty) {
  6238. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6239. this._isStencilOpDirty = false;
  6240. }
  6241. };
  6242. return _StencilState;
  6243. }());
  6244. Internals._StencilState = _StencilState;
  6245. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6246. })(BABYLON || (BABYLON = {}));
  6247. var BABYLON;
  6248. (function (BABYLON) {
  6249. var compileShader = function (gl, source, type, defines) {
  6250. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6251. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6252. gl.compileShader(shader);
  6253. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6254. throw new Error(gl.getShaderInfoLog(shader));
  6255. }
  6256. return shader;
  6257. };
  6258. var HALF_FLOAT_OES = 0x8D61;
  6259. var getWebGLTextureType = function (gl, type) {
  6260. if (type === Engine.TEXTURETYPE_FLOAT) {
  6261. return gl.FLOAT;
  6262. }
  6263. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6264. // Add Half Float Constant.
  6265. return HALF_FLOAT_OES;
  6266. }
  6267. return gl.UNSIGNED_BYTE;
  6268. };
  6269. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6270. var magFilter = gl.NEAREST;
  6271. var minFilter = gl.NEAREST;
  6272. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6273. magFilter = gl.LINEAR;
  6274. if (generateMipMaps) {
  6275. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6276. }
  6277. else {
  6278. minFilter = gl.LINEAR;
  6279. }
  6280. }
  6281. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6282. magFilter = gl.LINEAR;
  6283. if (generateMipMaps) {
  6284. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6285. }
  6286. else {
  6287. minFilter = gl.LINEAR;
  6288. }
  6289. }
  6290. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6291. magFilter = gl.NEAREST;
  6292. if (generateMipMaps) {
  6293. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6294. }
  6295. else {
  6296. minFilter = gl.NEAREST;
  6297. }
  6298. }
  6299. return {
  6300. min: minFilter,
  6301. mag: magFilter
  6302. };
  6303. };
  6304. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6306. var engine = scene.getEngine();
  6307. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6308. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6309. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6310. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6311. texture._baseWidth = width;
  6312. texture._baseHeight = height;
  6313. texture._width = potWidth;
  6314. texture._height = potHeight;
  6315. texture.isReady = true;
  6316. processFunction(potWidth, potHeight);
  6317. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6319. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6320. if (!noMipmap && !isCompressed) {
  6321. gl.generateMipmap(gl.TEXTURE_2D);
  6322. }
  6323. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6324. engine.resetTextureCache();
  6325. scene._removePendingData(texture);
  6326. texture.onLoadedCallbacks.forEach(function (callback) {
  6327. callback();
  6328. });
  6329. texture.onLoadedCallbacks = [];
  6330. };
  6331. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6332. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6333. var img;
  6334. var onload = function () {
  6335. loadedImages[index] = img;
  6336. loadedImages._internalCount++;
  6337. scene._removePendingData(img);
  6338. if (loadedImages._internalCount === 6) {
  6339. onfinish(loadedImages);
  6340. }
  6341. };
  6342. var onerror = function () {
  6343. scene._removePendingData(img);
  6344. if (onErrorCallBack) {
  6345. onErrorCallBack();
  6346. }
  6347. };
  6348. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6349. scene._addPendingData(img);
  6350. };
  6351. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6352. if (onError === void 0) { onError = null; }
  6353. var loadedImages = [];
  6354. loadedImages._internalCount = 0;
  6355. for (var index = 0; index < 6; index++) {
  6356. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6357. }
  6358. };
  6359. var InstancingAttributeInfo = (function () {
  6360. function InstancingAttributeInfo() {
  6361. }
  6362. return InstancingAttributeInfo;
  6363. }());
  6364. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6365. var EngineCapabilities = (function () {
  6366. function EngineCapabilities() {
  6367. }
  6368. return EngineCapabilities;
  6369. }());
  6370. BABYLON.EngineCapabilities = EngineCapabilities;
  6371. /**
  6372. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6373. */
  6374. var Engine = (function () {
  6375. /**
  6376. * @constructor
  6377. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6378. * @param {boolean} [antialias] - enable antialias
  6379. * @param options - further options to be sent to the getContext function
  6380. */
  6381. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6382. var _this = this;
  6383. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6384. // Public members
  6385. this.isFullscreen = false;
  6386. this.isPointerLock = false;
  6387. this.cullBackFaces = true;
  6388. this.renderEvenInBackground = true;
  6389. // To enable/disable IDB support and avoid XHR on .manifest
  6390. this.enableOfflineSupport = true;
  6391. this.scenes = new Array();
  6392. this._windowIsBackground = false;
  6393. this._webGLVersion = "1.0";
  6394. this._badOS = false;
  6395. this._drawCalls = new BABYLON.PerfCounter();
  6396. this._renderingQueueLaunched = false;
  6397. this._activeRenderLoops = [];
  6398. // FPS
  6399. this.fpsRange = 60;
  6400. this.previousFramesDuration = [];
  6401. this.fps = 60;
  6402. this.deltaTime = 0;
  6403. // States
  6404. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6405. this._stencilState = new BABYLON.Internals._StencilState();
  6406. this._alphaState = new BABYLON.Internals._AlphaState();
  6407. this._alphaMode = Engine.ALPHA_DISABLE;
  6408. // Cache
  6409. this._loadedTexturesCache = new Array();
  6410. this._maxTextureChannels = 16;
  6411. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6412. this._compiledEffects = {};
  6413. this._vertexAttribArraysEnabled = [];
  6414. this._uintIndicesCurrentlySet = false;
  6415. this._currentBoundBuffer = new Array();
  6416. this._currentBufferPointers = [];
  6417. this._currentInstanceLocations = new Array();
  6418. this._currentInstanceBuffers = new Array();
  6419. this._onVRFullScreenTriggered = function () {
  6420. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6421. //get the old size before we change
  6422. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6423. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6424. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6425. //But actually, no browser follow the specs...
  6426. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6427. //get the width and height, change the render size
  6428. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6429. var width, height;
  6430. _this.setHardwareScalingLevel(1);
  6431. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6432. }
  6433. else {
  6434. //When the specs are implemented, need to uncomment this.
  6435. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6436. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6437. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6438. _this._vrDisplayEnabled = undefined;
  6439. }
  6440. };
  6441. this._renderingCanvas = canvas;
  6442. this._externalData = new BABYLON.StringDictionary();
  6443. options = options || {};
  6444. if (antialias != null) {
  6445. options.antialias = antialias;
  6446. }
  6447. if (options.preserveDrawingBuffer === undefined) {
  6448. options.preserveDrawingBuffer = false;
  6449. }
  6450. // Checks if some of the format renders first to allow the use of webgl inspector.
  6451. var renderToFullFloat = this._canRenderToFloatTexture();
  6452. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6453. // GL
  6454. //try {
  6455. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6456. // if (this._gl) {
  6457. // this._webGLVersion = "2.0";
  6458. // }
  6459. //} catch (e) {
  6460. // // Do nothing
  6461. //}
  6462. if (!this._gl) {
  6463. try {
  6464. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6465. }
  6466. catch (e) {
  6467. throw new Error("WebGL not supported");
  6468. }
  6469. }
  6470. if (!this._gl) {
  6471. throw new Error("WebGL not supported");
  6472. }
  6473. this._onBlur = function () {
  6474. _this._windowIsBackground = true;
  6475. };
  6476. this._onFocus = function () {
  6477. _this._windowIsBackground = false;
  6478. };
  6479. window.addEventListener("blur", this._onBlur);
  6480. window.addEventListener("focus", this._onFocus);
  6481. // Viewport
  6482. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6483. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6484. this.resize();
  6485. // Caps
  6486. this._isStencilEnable = options.stencil;
  6487. this._caps = new EngineCapabilities();
  6488. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6489. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6490. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6491. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6492. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6493. // Infos
  6494. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6495. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6496. if (rendererInfo != null) {
  6497. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6498. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6499. }
  6500. if (!this._glVendor) {
  6501. this._glVendor = "Unknown vendor";
  6502. }
  6503. if (!this._glRenderer) {
  6504. this._glRenderer = "Unknown renderer";
  6505. }
  6506. // Extensions
  6507. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6508. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6509. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6510. 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');
  6511. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6512. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6513. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6514. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6515. this._caps.highPrecisionShaderSupported = true;
  6516. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6517. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6518. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6519. this._caps.textureFloatRender = renderToFullFloat;
  6520. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6521. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6522. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6523. if (this._gl.getShaderPrecisionFormat) {
  6524. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6525. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6526. }
  6527. // Depth buffer
  6528. this.setDepthBuffer(true);
  6529. this.setDepthFunctionToLessOrEqual();
  6530. this.setDepthWrite(true);
  6531. // Fullscreen
  6532. this._onFullscreenChange = function () {
  6533. if (document.fullscreen !== undefined) {
  6534. _this.isFullscreen = document.fullscreen;
  6535. }
  6536. else if (document.mozFullScreen !== undefined) {
  6537. _this.isFullscreen = document.mozFullScreen;
  6538. }
  6539. else if (document.webkitIsFullScreen !== undefined) {
  6540. _this.isFullscreen = document.webkitIsFullScreen;
  6541. }
  6542. else if (document.msIsFullScreen !== undefined) {
  6543. _this.isFullscreen = document.msIsFullScreen;
  6544. }
  6545. // Pointer lock
  6546. if (_this.isFullscreen && _this._pointerLockRequested) {
  6547. canvas.requestPointerLock = canvas.requestPointerLock ||
  6548. canvas.msRequestPointerLock ||
  6549. canvas.mozRequestPointerLock ||
  6550. canvas.webkitRequestPointerLock;
  6551. if (canvas.requestPointerLock) {
  6552. canvas.requestPointerLock();
  6553. }
  6554. }
  6555. };
  6556. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6557. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6558. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6559. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6560. // Pointer lock
  6561. this._onPointerLockChange = function () {
  6562. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6563. document.webkitPointerLockElement === canvas ||
  6564. document.msPointerLockElement === canvas ||
  6565. document.pointerLockElement === canvas);
  6566. };
  6567. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6568. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6569. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6570. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6571. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6572. Engine.audioEngine = new BABYLON.AudioEngine();
  6573. }
  6574. //default loading screen
  6575. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6576. //Load WebVR Devices
  6577. if (options.autoEnableWebVR) {
  6578. this.initWebVR();
  6579. }
  6580. //Detect if we are running on a faulty buggy OS.
  6581. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6582. //ua sniffing is the tool of the devil.
  6583. this._badOS = regexp.test(navigator.userAgent);
  6584. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6585. }
  6586. Object.defineProperty(Engine, "NEVER", {
  6587. get: function () {
  6588. return Engine._NEVER;
  6589. },
  6590. enumerable: true,
  6591. configurable: true
  6592. });
  6593. Object.defineProperty(Engine, "ALWAYS", {
  6594. get: function () {
  6595. return Engine._ALWAYS;
  6596. },
  6597. enumerable: true,
  6598. configurable: true
  6599. });
  6600. Object.defineProperty(Engine, "LESS", {
  6601. get: function () {
  6602. return Engine._LESS;
  6603. },
  6604. enumerable: true,
  6605. configurable: true
  6606. });
  6607. Object.defineProperty(Engine, "EQUAL", {
  6608. get: function () {
  6609. return Engine._EQUAL;
  6610. },
  6611. enumerable: true,
  6612. configurable: true
  6613. });
  6614. Object.defineProperty(Engine, "LEQUAL", {
  6615. get: function () {
  6616. return Engine._LEQUAL;
  6617. },
  6618. enumerable: true,
  6619. configurable: true
  6620. });
  6621. Object.defineProperty(Engine, "GREATER", {
  6622. get: function () {
  6623. return Engine._GREATER;
  6624. },
  6625. enumerable: true,
  6626. configurable: true
  6627. });
  6628. Object.defineProperty(Engine, "GEQUAL", {
  6629. get: function () {
  6630. return Engine._GEQUAL;
  6631. },
  6632. enumerable: true,
  6633. configurable: true
  6634. });
  6635. Object.defineProperty(Engine, "NOTEQUAL", {
  6636. get: function () {
  6637. return Engine._NOTEQUAL;
  6638. },
  6639. enumerable: true,
  6640. configurable: true
  6641. });
  6642. Object.defineProperty(Engine, "KEEP", {
  6643. get: function () {
  6644. return Engine._KEEP;
  6645. },
  6646. enumerable: true,
  6647. configurable: true
  6648. });
  6649. Object.defineProperty(Engine, "REPLACE", {
  6650. get: function () {
  6651. return Engine._REPLACE;
  6652. },
  6653. enumerable: true,
  6654. configurable: true
  6655. });
  6656. Object.defineProperty(Engine, "INCR", {
  6657. get: function () {
  6658. return Engine._INCR;
  6659. },
  6660. enumerable: true,
  6661. configurable: true
  6662. });
  6663. Object.defineProperty(Engine, "DECR", {
  6664. get: function () {
  6665. return Engine._DECR;
  6666. },
  6667. enumerable: true,
  6668. configurable: true
  6669. });
  6670. Object.defineProperty(Engine, "INVERT", {
  6671. get: function () {
  6672. return Engine._INVERT;
  6673. },
  6674. enumerable: true,
  6675. configurable: true
  6676. });
  6677. Object.defineProperty(Engine, "INCR_WRAP", {
  6678. get: function () {
  6679. return Engine._INCR_WRAP;
  6680. },
  6681. enumerable: true,
  6682. configurable: true
  6683. });
  6684. Object.defineProperty(Engine, "DECR_WRAP", {
  6685. get: function () {
  6686. return Engine._DECR_WRAP;
  6687. },
  6688. enumerable: true,
  6689. configurable: true
  6690. });
  6691. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6692. get: function () {
  6693. return Engine._ALPHA_DISABLE;
  6694. },
  6695. enumerable: true,
  6696. configurable: true
  6697. });
  6698. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6699. get: function () {
  6700. return Engine._ALPHA_ONEONE;
  6701. },
  6702. enumerable: true,
  6703. configurable: true
  6704. });
  6705. Object.defineProperty(Engine, "ALPHA_ADD", {
  6706. get: function () {
  6707. return Engine._ALPHA_ADD;
  6708. },
  6709. enumerable: true,
  6710. configurable: true
  6711. });
  6712. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6713. get: function () {
  6714. return Engine._ALPHA_COMBINE;
  6715. },
  6716. enumerable: true,
  6717. configurable: true
  6718. });
  6719. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6720. get: function () {
  6721. return Engine._ALPHA_SUBTRACT;
  6722. },
  6723. enumerable: true,
  6724. configurable: true
  6725. });
  6726. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6727. get: function () {
  6728. return Engine._ALPHA_MULTIPLY;
  6729. },
  6730. enumerable: true,
  6731. configurable: true
  6732. });
  6733. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6734. get: function () {
  6735. return Engine._ALPHA_MAXIMIZED;
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6741. get: function () {
  6742. return Engine._DELAYLOADSTATE_NONE;
  6743. },
  6744. enumerable: true,
  6745. configurable: true
  6746. });
  6747. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6748. get: function () {
  6749. return Engine._DELAYLOADSTATE_LOADED;
  6750. },
  6751. enumerable: true,
  6752. configurable: true
  6753. });
  6754. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6755. get: function () {
  6756. return Engine._DELAYLOADSTATE_LOADING;
  6757. },
  6758. enumerable: true,
  6759. configurable: true
  6760. });
  6761. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6762. get: function () {
  6763. return Engine._DELAYLOADSTATE_NOTLOADED;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6769. get: function () {
  6770. return Engine._TEXTUREFORMAT_ALPHA;
  6771. },
  6772. enumerable: true,
  6773. configurable: true
  6774. });
  6775. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6776. get: function () {
  6777. return Engine._TEXTUREFORMAT_LUMINANCE;
  6778. },
  6779. enumerable: true,
  6780. configurable: true
  6781. });
  6782. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6783. get: function () {
  6784. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6785. },
  6786. enumerable: true,
  6787. configurable: true
  6788. });
  6789. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6790. get: function () {
  6791. return Engine._TEXTUREFORMAT_RGB;
  6792. },
  6793. enumerable: true,
  6794. configurable: true
  6795. });
  6796. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6797. get: function () {
  6798. return Engine._TEXTUREFORMAT_RGBA;
  6799. },
  6800. enumerable: true,
  6801. configurable: true
  6802. });
  6803. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6804. get: function () {
  6805. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6806. },
  6807. enumerable: true,
  6808. configurable: true
  6809. });
  6810. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6811. get: function () {
  6812. return Engine._TEXTURETYPE_FLOAT;
  6813. },
  6814. enumerable: true,
  6815. configurable: true
  6816. });
  6817. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6818. get: function () {
  6819. return Engine._TEXTURETYPE_HALF_FLOAT;
  6820. },
  6821. enumerable: true,
  6822. configurable: true
  6823. });
  6824. Object.defineProperty(Engine, "Version", {
  6825. get: function () {
  6826. return "2.5.-beta";
  6827. },
  6828. enumerable: true,
  6829. configurable: true
  6830. });
  6831. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6832. get: function () {
  6833. return this._webGLVersion;
  6834. },
  6835. enumerable: true,
  6836. configurable: true
  6837. });
  6838. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6839. /**
  6840. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6841. */
  6842. get: function () {
  6843. return this._isStencilEnable;
  6844. },
  6845. enumerable: true,
  6846. configurable: true
  6847. });
  6848. Engine.prototype._prepareWorkingCanvas = function () {
  6849. if (this._workingCanvas) {
  6850. return;
  6851. }
  6852. this._workingCanvas = document.createElement("canvas");
  6853. this._workingContext = this._workingCanvas.getContext("2d");
  6854. };
  6855. Engine.prototype.resetTextureCache = function () {
  6856. for (var index = 0; index < this._maxTextureChannels; index++) {
  6857. this._activeTexturesCache[index] = null;
  6858. }
  6859. };
  6860. Engine.prototype.getGlInfo = function () {
  6861. return {
  6862. vendor: this._glVendor,
  6863. renderer: this._glRenderer,
  6864. version: this._glVersion
  6865. };
  6866. };
  6867. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6868. if (useScreen === void 0) { useScreen = false; }
  6869. var viewport = camera.viewport;
  6870. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6871. };
  6872. Engine.prototype.getRenderWidth = function (useScreen) {
  6873. if (useScreen === void 0) { useScreen = false; }
  6874. if (!useScreen && this._currentRenderTarget) {
  6875. return this._currentRenderTarget._width;
  6876. }
  6877. return this._renderingCanvas.width;
  6878. };
  6879. Engine.prototype.getRenderHeight = function (useScreen) {
  6880. if (useScreen === void 0) { useScreen = false; }
  6881. if (!useScreen && this._currentRenderTarget) {
  6882. return this._currentRenderTarget._height;
  6883. }
  6884. return this._renderingCanvas.height;
  6885. };
  6886. Engine.prototype.getRenderingCanvas = function () {
  6887. return this._renderingCanvas;
  6888. };
  6889. Engine.prototype.getRenderingCanvasClientRect = function () {
  6890. return this._renderingCanvas.getBoundingClientRect();
  6891. };
  6892. Engine.prototype.setHardwareScalingLevel = function (level) {
  6893. this._hardwareScalingLevel = level;
  6894. this.resize();
  6895. };
  6896. Engine.prototype.getHardwareScalingLevel = function () {
  6897. return this._hardwareScalingLevel;
  6898. };
  6899. Engine.prototype.getLoadedTexturesCache = function () {
  6900. return this._loadedTexturesCache;
  6901. };
  6902. Engine.prototype.getCaps = function () {
  6903. return this._caps;
  6904. };
  6905. Object.defineProperty(Engine.prototype, "drawCalls", {
  6906. get: function () {
  6907. return this._drawCalls.current;
  6908. },
  6909. enumerable: true,
  6910. configurable: true
  6911. });
  6912. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6913. get: function () {
  6914. return this._drawCalls;
  6915. },
  6916. enumerable: true,
  6917. configurable: true
  6918. });
  6919. Engine.prototype.getDepthFunction = function () {
  6920. return this._depthCullingState.depthFunc;
  6921. };
  6922. Engine.prototype.setDepthFunction = function (depthFunc) {
  6923. this._depthCullingState.depthFunc = depthFunc;
  6924. };
  6925. Engine.prototype.setDepthFunctionToGreater = function () {
  6926. this._depthCullingState.depthFunc = this._gl.GREATER;
  6927. };
  6928. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6929. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6930. };
  6931. Engine.prototype.setDepthFunctionToLess = function () {
  6932. this._depthCullingState.depthFunc = this._gl.LESS;
  6933. };
  6934. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6935. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6936. };
  6937. Engine.prototype.getStencilBuffer = function () {
  6938. return this._stencilState.stencilTest;
  6939. };
  6940. Engine.prototype.setStencilBuffer = function (enable) {
  6941. this._stencilState.stencilTest = enable;
  6942. };
  6943. Engine.prototype.getStencilMask = function () {
  6944. return this._stencilState.stencilMask;
  6945. };
  6946. Engine.prototype.setStencilMask = function (mask) {
  6947. this._stencilState.stencilMask = mask;
  6948. };
  6949. Engine.prototype.getStencilFunction = function () {
  6950. return this._stencilState.stencilFunc;
  6951. };
  6952. Engine.prototype.getStencilFunctionReference = function () {
  6953. return this._stencilState.stencilFuncRef;
  6954. };
  6955. Engine.prototype.getStencilFunctionMask = function () {
  6956. return this._stencilState.stencilFuncMask;
  6957. };
  6958. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6959. this._stencilState.stencilFunc = stencilFunc;
  6960. };
  6961. Engine.prototype.setStencilFunctionReference = function (reference) {
  6962. this._stencilState.stencilFuncRef = reference;
  6963. };
  6964. Engine.prototype.setStencilFunctionMask = function (mask) {
  6965. this._stencilState.stencilFuncMask = mask;
  6966. };
  6967. Engine.prototype.getStencilOperationFail = function () {
  6968. return this._stencilState.stencilOpStencilFail;
  6969. };
  6970. Engine.prototype.getStencilOperationDepthFail = function () {
  6971. return this._stencilState.stencilOpDepthFail;
  6972. };
  6973. Engine.prototype.getStencilOperationPass = function () {
  6974. return this._stencilState.stencilOpStencilDepthPass;
  6975. };
  6976. Engine.prototype.setStencilOperationFail = function (operation) {
  6977. this._stencilState.stencilOpStencilFail = operation;
  6978. };
  6979. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6980. this._stencilState.stencilOpDepthFail = operation;
  6981. };
  6982. Engine.prototype.setStencilOperationPass = function (operation) {
  6983. this._stencilState.stencilOpStencilDepthPass = operation;
  6984. };
  6985. /**
  6986. * stop executing a render loop function and remove it from the execution array
  6987. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6988. */
  6989. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6990. if (!renderFunction) {
  6991. this._activeRenderLoops = [];
  6992. return;
  6993. }
  6994. var index = this._activeRenderLoops.indexOf(renderFunction);
  6995. if (index >= 0) {
  6996. this._activeRenderLoops.splice(index, 1);
  6997. }
  6998. };
  6999. Engine.prototype._renderLoop = function () {
  7000. var shouldRender = true;
  7001. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7002. shouldRender = false;
  7003. }
  7004. if (shouldRender) {
  7005. // Start new frame
  7006. this.beginFrame();
  7007. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7008. var renderFunction = this._activeRenderLoops[index];
  7009. renderFunction();
  7010. }
  7011. // Present
  7012. this.endFrame();
  7013. }
  7014. if (this._activeRenderLoops.length > 0) {
  7015. // Register new frame
  7016. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7017. }
  7018. else {
  7019. this._renderingQueueLaunched = false;
  7020. }
  7021. };
  7022. /**
  7023. * Register and execute a render loop. The engine can have more than one render function.
  7024. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7025. * @example
  7026. * engine.runRenderLoop(function () {
  7027. * scene.render()
  7028. * })
  7029. */
  7030. Engine.prototype.runRenderLoop = function (renderFunction) {
  7031. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7032. return;
  7033. }
  7034. this._activeRenderLoops.push(renderFunction);
  7035. if (!this._renderingQueueLaunched) {
  7036. this._renderingQueueLaunched = true;
  7037. this._bindedRenderFunction = this._renderLoop.bind(this);
  7038. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7039. }
  7040. };
  7041. /**
  7042. * Toggle full screen mode.
  7043. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7044. * @param {any} options - an options object to be sent to the requestFullscreen function
  7045. */
  7046. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7047. if (this.isFullscreen) {
  7048. BABYLON.Tools.ExitFullscreen();
  7049. }
  7050. else {
  7051. this._pointerLockRequested = requestPointerLock;
  7052. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7053. }
  7054. };
  7055. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7056. if (stencil === void 0) { stencil = false; }
  7057. this.applyStates();
  7058. var mode = 0;
  7059. if (backBuffer) {
  7060. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7061. mode |= this._gl.COLOR_BUFFER_BIT;
  7062. }
  7063. if (depth) {
  7064. this._gl.clearDepth(1.0);
  7065. mode |= this._gl.DEPTH_BUFFER_BIT;
  7066. }
  7067. if (stencil) {
  7068. this._gl.clearStencil(0);
  7069. mode |= this._gl.STENCIL_BUFFER_BIT;
  7070. }
  7071. this._gl.clear(mode);
  7072. };
  7073. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7074. var gl = this._gl;
  7075. // Save state
  7076. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7077. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7078. // Change state
  7079. gl.enable(gl.SCISSOR_TEST);
  7080. gl.scissor(x, y, width, height);
  7081. // Clear
  7082. this.clear(clearColor, true, true, true);
  7083. // Restore state
  7084. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7085. if (curScissor === true) {
  7086. gl.enable(gl.SCISSOR_TEST);
  7087. }
  7088. else {
  7089. gl.disable(gl.SCISSOR_TEST);
  7090. }
  7091. };
  7092. /**
  7093. * Set the WebGL's viewport
  7094. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7095. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7096. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7097. */
  7098. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7099. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  7100. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  7101. var x = viewport.x || 0;
  7102. var y = viewport.y || 0;
  7103. this._cachedViewport = viewport;
  7104. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7105. };
  7106. /**
  7107. * Directly set the WebGL Viewport
  7108. * The x, y, width & height are directly passed to the WebGL call
  7109. * @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.
  7110. */
  7111. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7112. var currentViewport = this._cachedViewport;
  7113. this._cachedViewport = null;
  7114. this._gl.viewport(x, y, width, height);
  7115. return currentViewport;
  7116. };
  7117. Engine.prototype.beginFrame = function () {
  7118. this._measureFps();
  7119. };
  7120. Engine.prototype.endFrame = function () {
  7121. //force a flush in case we are using a bad OS.
  7122. if (this._badOS) {
  7123. this.flushFramebuffer();
  7124. }
  7125. //submit frame to the vr device, if enabled
  7126. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7127. this._vrDisplayEnabled.submitFrame();
  7128. }
  7129. };
  7130. /**
  7131. * resize the view according to the canvas' size.
  7132. * @example
  7133. * window.addEventListener("resize", function () {
  7134. * engine.resize();
  7135. * });
  7136. */
  7137. Engine.prototype.resize = function () {
  7138. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7139. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7140. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7141. for (var index = 0; index < this.scenes.length; index++) {
  7142. var scene = this.scenes[index];
  7143. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  7144. scene.debugLayer._syncPositions();
  7145. }
  7146. }
  7147. };
  7148. /**
  7149. * force a specific size of the canvas
  7150. * @param {number} width - the new canvas' width
  7151. * @param {number} height - the new canvas' height
  7152. */
  7153. Engine.prototype.setSize = function (width, height) {
  7154. this._renderingCanvas.width = width;
  7155. this._renderingCanvas.height = height;
  7156. for (var index = 0; index < this.scenes.length; index++) {
  7157. var scene = this.scenes[index];
  7158. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7159. var cam = scene.cameras[camIndex];
  7160. cam._currentRenderId = 0;
  7161. }
  7162. }
  7163. };
  7164. //WebVR functions
  7165. Engine.prototype.initWebVR = function () {
  7166. if (!this.vrDisplaysPromise) {
  7167. this._getVRDisplays();
  7168. }
  7169. };
  7170. Engine.prototype.enableVR = function (vrDevice) {
  7171. this._vrDisplayEnabled = vrDevice;
  7172. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7173. };
  7174. Engine.prototype.disableVR = function () {
  7175. if (this._vrDisplayEnabled) {
  7176. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7177. }
  7178. };
  7179. Engine.prototype._getVRDisplays = function () {
  7180. var _this = this;
  7181. var getWebVRDevices = function (devices) {
  7182. var size = devices.length;
  7183. var i = 0;
  7184. _this._vrDisplays = devices.filter(function (device) {
  7185. return devices[i] instanceof VRDisplay;
  7186. });
  7187. return _this._vrDisplays;
  7188. };
  7189. //using a key due to typescript
  7190. if (navigator.getVRDisplays) {
  7191. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7192. }
  7193. };
  7194. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7195. this._currentRenderTarget = texture;
  7196. this.bindUnboundFramebuffer(texture._framebuffer);
  7197. var gl = this._gl;
  7198. if (texture.isCube) {
  7199. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7200. }
  7201. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7202. this.wipeCaches();
  7203. };
  7204. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7205. if (this._currentFramebuffer !== framebuffer) {
  7206. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7207. this._currentFramebuffer = framebuffer;
  7208. }
  7209. };
  7210. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7211. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7212. this._currentRenderTarget = null;
  7213. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7214. var gl = this._gl;
  7215. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7216. gl.generateMipmap(gl.TEXTURE_2D);
  7217. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7218. }
  7219. this.bindUnboundFramebuffer(null);
  7220. };
  7221. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7222. if (texture.generateMipMaps) {
  7223. var gl = this._gl;
  7224. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7225. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7226. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7227. }
  7228. };
  7229. Engine.prototype.flushFramebuffer = function () {
  7230. this._gl.flush();
  7231. };
  7232. Engine.prototype.restoreDefaultFramebuffer = function () {
  7233. this._currentRenderTarget = null;
  7234. this.bindUnboundFramebuffer(null);
  7235. this.setViewport(this._cachedViewport);
  7236. this.wipeCaches();
  7237. };
  7238. // VBOs
  7239. Engine.prototype._resetVertexBufferBinding = function () {
  7240. this.bindArrayBuffer(null);
  7241. this._cachedVertexBuffers = null;
  7242. };
  7243. Engine.prototype.createVertexBuffer = function (vertices) {
  7244. var vbo = this._gl.createBuffer();
  7245. this.bindArrayBuffer(vbo);
  7246. if (vertices instanceof Float32Array) {
  7247. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7248. }
  7249. else {
  7250. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7251. }
  7252. this._resetVertexBufferBinding();
  7253. vbo.references = 1;
  7254. return vbo;
  7255. };
  7256. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7257. var vbo = this._gl.createBuffer();
  7258. this.bindArrayBuffer(vbo);
  7259. if (vertices instanceof Float32Array) {
  7260. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7261. }
  7262. else {
  7263. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7264. }
  7265. this._resetVertexBufferBinding();
  7266. vbo.references = 1;
  7267. return vbo;
  7268. };
  7269. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7270. this.bindArrayBuffer(vertexBuffer);
  7271. if (offset === undefined) {
  7272. offset = 0;
  7273. }
  7274. if (count === undefined) {
  7275. if (vertices instanceof Float32Array) {
  7276. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7277. }
  7278. else {
  7279. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7280. }
  7281. }
  7282. else {
  7283. if (vertices instanceof Float32Array) {
  7284. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7285. }
  7286. else {
  7287. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7288. }
  7289. }
  7290. this._resetVertexBufferBinding();
  7291. };
  7292. Engine.prototype._resetIndexBufferBinding = function () {
  7293. this.bindIndexBuffer(null);
  7294. this._cachedIndexBuffer = null;
  7295. };
  7296. Engine.prototype.createIndexBuffer = function (indices) {
  7297. var vbo = this._gl.createBuffer();
  7298. this.bindIndexBuffer(vbo);
  7299. // Check for 32 bits indices
  7300. var arrayBuffer;
  7301. var need32Bits = false;
  7302. if (this._caps.uintIndices) {
  7303. for (var index = 0; index < indices.length; index++) {
  7304. if (indices[index] > 65535) {
  7305. need32Bits = true;
  7306. break;
  7307. }
  7308. }
  7309. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7310. }
  7311. else {
  7312. arrayBuffer = new Uint16Array(indices);
  7313. }
  7314. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7315. this._resetIndexBufferBinding();
  7316. vbo.references = 1;
  7317. vbo.is32Bits = need32Bits;
  7318. return vbo;
  7319. };
  7320. Engine.prototype.bindArrayBuffer = function (buffer) {
  7321. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7322. };
  7323. Engine.prototype.bindIndexBuffer = function (buffer) {
  7324. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7325. };
  7326. Engine.prototype.bindBuffer = function (buffer, target) {
  7327. if (this._currentBoundBuffer[target] !== buffer) {
  7328. this._gl.bindBuffer(target, buffer);
  7329. this._currentBoundBuffer[target] = buffer;
  7330. }
  7331. };
  7332. Engine.prototype.updateArrayBuffer = function (data) {
  7333. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7334. };
  7335. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7336. var pointer = this._currentBufferPointers[indx];
  7337. var changed = false;
  7338. if (!pointer) {
  7339. changed = true;
  7340. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7341. }
  7342. else {
  7343. if (pointer.buffer !== buffer) {
  7344. pointer.buffer = buffer;
  7345. changed = true;
  7346. }
  7347. if (pointer.size !== size) {
  7348. pointer.size = size;
  7349. changed = true;
  7350. }
  7351. if (pointer.type !== type) {
  7352. pointer.type = type;
  7353. changed = true;
  7354. }
  7355. if (pointer.normalized !== normalized) {
  7356. pointer.normalized = normalized;
  7357. changed = true;
  7358. }
  7359. if (pointer.stride !== stride) {
  7360. pointer.stride = stride;
  7361. changed = true;
  7362. }
  7363. if (pointer.offset !== offset) {
  7364. pointer.offset = offset;
  7365. changed = true;
  7366. }
  7367. }
  7368. if (changed) {
  7369. this.bindArrayBuffer(buffer);
  7370. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7371. }
  7372. };
  7373. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7374. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7375. this._cachedVertexBuffers = vertexBuffer;
  7376. this._cachedEffectForVertexBuffers = effect;
  7377. var attributesCount = effect.getAttributesCount();
  7378. var offset = 0;
  7379. for (var index = 0; index < attributesCount; index++) {
  7380. if (index < vertexDeclaration.length) {
  7381. var order = effect.getAttributeLocation(index);
  7382. if (order >= 0) {
  7383. if (!this._vertexAttribArraysEnabled[order]) {
  7384. this._gl.enableVertexAttribArray(order);
  7385. this._vertexAttribArraysEnabled[order] = true;
  7386. }
  7387. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7388. }
  7389. offset += vertexDeclaration[index] * 4;
  7390. }
  7391. else {
  7392. //disable effect attributes that have no data
  7393. var order = effect.getAttributeLocation(index);
  7394. if (this._vertexAttribArraysEnabled[order]) {
  7395. this._gl.disableVertexAttribArray(order);
  7396. this._vertexAttribArraysEnabled[order] = false;
  7397. }
  7398. }
  7399. }
  7400. }
  7401. if (this._cachedIndexBuffer !== indexBuffer) {
  7402. this._cachedIndexBuffer = indexBuffer;
  7403. this.bindIndexBuffer(indexBuffer);
  7404. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7405. }
  7406. };
  7407. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7408. // if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7409. this._cachedVertexBuffers = vertexBuffers;
  7410. this._cachedEffectForVertexBuffers = effect;
  7411. var attributes = effect.getAttributesNames();
  7412. for (var index = 0; index < attributes.length; index++) {
  7413. var order = effect.getAttributeLocation(index);
  7414. if (order >= 0) {
  7415. var vertexBuffer = vertexBuffers[attributes[index]];
  7416. if (!vertexBuffer) {
  7417. if (this._vertexAttribArraysEnabled[order]) {
  7418. this._gl.disableVertexAttribArray(order);
  7419. this._vertexAttribArraysEnabled[order] = false;
  7420. }
  7421. continue;
  7422. }
  7423. if (!this._vertexAttribArraysEnabled[order]) {
  7424. this._gl.enableVertexAttribArray(order);
  7425. this._vertexAttribArraysEnabled[order] = true;
  7426. }
  7427. var buffer = vertexBuffer.getBuffer();
  7428. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7429. if (vertexBuffer.getIsInstanced()) {
  7430. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7431. this._currentInstanceLocations.push(order);
  7432. this._currentInstanceBuffers.push(buffer);
  7433. }
  7434. }
  7435. }
  7436. // }
  7437. // if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7438. this._cachedIndexBuffer = indexBuffer;
  7439. this.bindIndexBuffer(indexBuffer);
  7440. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7441. //}
  7442. };
  7443. Engine.prototype.unbindInstanceAttributes = function () {
  7444. var boundBuffer;
  7445. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7446. var instancesBuffer = this._currentInstanceBuffers[i];
  7447. if (boundBuffer != instancesBuffer) {
  7448. boundBuffer = instancesBuffer;
  7449. this.bindArrayBuffer(instancesBuffer);
  7450. }
  7451. var offsetLocation = this._currentInstanceLocations[i];
  7452. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7453. }
  7454. this._currentInstanceBuffers.length = 0;
  7455. this._currentInstanceLocations.length = 0;
  7456. };
  7457. Engine.prototype._releaseBuffer = function (buffer) {
  7458. buffer.references--;
  7459. if (buffer.references === 0) {
  7460. this._gl.deleteBuffer(buffer);
  7461. return true;
  7462. }
  7463. return false;
  7464. };
  7465. Engine.prototype.createInstancesBuffer = function (capacity) {
  7466. var buffer = this._gl.createBuffer();
  7467. buffer.capacity = capacity;
  7468. this.bindArrayBuffer(buffer);
  7469. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7470. return buffer;
  7471. };
  7472. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7473. this._gl.deleteBuffer(buffer);
  7474. };
  7475. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7476. this.bindArrayBuffer(instancesBuffer);
  7477. if (data) {
  7478. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7479. }
  7480. if (offsetLocations[0].index !== undefined) {
  7481. var stride = 0;
  7482. for (var i = 0; i < offsetLocations.length; i++) {
  7483. var ai = offsetLocations[i];
  7484. stride += ai.attributeSize * 4;
  7485. }
  7486. for (var i = 0; i < offsetLocations.length; i++) {
  7487. var ai = offsetLocations[i];
  7488. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7489. this._gl.enableVertexAttribArray(ai.index);
  7490. this._vertexAttribArraysEnabled[ai.index] = true;
  7491. }
  7492. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7493. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7494. this._currentInstanceLocations.push(ai.index);
  7495. this._currentInstanceBuffers.push(instancesBuffer);
  7496. }
  7497. }
  7498. else {
  7499. for (var index = 0; index < 4; index++) {
  7500. var offsetLocation = offsetLocations[index];
  7501. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7502. this._gl.enableVertexAttribArray(offsetLocation);
  7503. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7504. }
  7505. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7506. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7507. this._currentInstanceLocations.push(offsetLocation);
  7508. this._currentInstanceBuffers.push(instancesBuffer);
  7509. }
  7510. }
  7511. };
  7512. Engine.prototype.applyStates = function () {
  7513. this._depthCullingState.apply(this._gl);
  7514. this._stencilState.apply(this._gl);
  7515. this._alphaState.apply(this._gl);
  7516. };
  7517. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7518. // Apply states
  7519. this.applyStates();
  7520. this._drawCalls.addCount(1, false);
  7521. // Render
  7522. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7523. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7524. if (instancesCount) {
  7525. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7526. return;
  7527. }
  7528. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7529. };
  7530. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7531. // Apply states
  7532. this.applyStates();
  7533. this._drawCalls.addCount(1, false);
  7534. if (instancesCount) {
  7535. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7536. return;
  7537. }
  7538. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7539. };
  7540. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7541. // Apply states
  7542. this.applyStates();
  7543. this._drawCalls.addCount(1, false);
  7544. if (instancesCount) {
  7545. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7546. return;
  7547. }
  7548. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7549. };
  7550. // Shaders
  7551. Engine.prototype._releaseEffect = function (effect) {
  7552. if (this._compiledEffects[effect._key]) {
  7553. delete this._compiledEffects[effect._key];
  7554. if (effect.getProgram()) {
  7555. this._gl.deleteProgram(effect.getProgram());
  7556. }
  7557. }
  7558. };
  7559. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7560. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7561. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7562. var name = vertex + "+" + fragment + "@" + defines;
  7563. if (this._compiledEffects[name]) {
  7564. return this._compiledEffects[name];
  7565. }
  7566. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7567. effect._key = name;
  7568. this._compiledEffects[name] = effect;
  7569. return effect;
  7570. };
  7571. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7572. if (uniformsNames === void 0) { uniformsNames = []; }
  7573. if (samplers === void 0) { samplers = []; }
  7574. if (defines === void 0) { defines = ""; }
  7575. return this.createEffect({
  7576. vertex: "particles",
  7577. fragmentElement: fragmentName
  7578. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7579. };
  7580. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7581. context = context || this._gl;
  7582. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7583. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7584. var shaderProgram = context.createProgram();
  7585. context.attachShader(shaderProgram, vertexShader);
  7586. context.attachShader(shaderProgram, fragmentShader);
  7587. context.linkProgram(shaderProgram);
  7588. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7589. if (!linked) {
  7590. var error = context.getProgramInfoLog(shaderProgram);
  7591. if (error) {
  7592. throw new Error(error);
  7593. }
  7594. }
  7595. context.deleteShader(vertexShader);
  7596. context.deleteShader(fragmentShader);
  7597. return shaderProgram;
  7598. };
  7599. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7600. var results = [];
  7601. for (var index = 0; index < uniformsNames.length; index++) {
  7602. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7603. }
  7604. return results;
  7605. };
  7606. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7607. var results = [];
  7608. for (var index = 0; index < attributesNames.length; index++) {
  7609. try {
  7610. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7611. }
  7612. catch (e) {
  7613. results.push(-1);
  7614. }
  7615. }
  7616. return results;
  7617. };
  7618. Engine.prototype.enableEffect = function (effect) {
  7619. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7620. // if (effect && effect.onBind) {
  7621. // effect.onBind(effect);
  7622. // }
  7623. // return;
  7624. //}
  7625. // Use program
  7626. this.setProgram(effect.getProgram());
  7627. this._currentEffect = effect;
  7628. if (effect.onBind) {
  7629. effect.onBind(effect);
  7630. }
  7631. };
  7632. Engine.prototype.setIntArray = function (uniform, array) {
  7633. if (!uniform)
  7634. return;
  7635. this._gl.uniform1iv(uniform, array);
  7636. };
  7637. Engine.prototype.setIntArray2 = function (uniform, array) {
  7638. if (!uniform || array.length % 2 !== 0)
  7639. return;
  7640. this._gl.uniform2iv(uniform, array);
  7641. };
  7642. Engine.prototype.setIntArray3 = function (uniform, array) {
  7643. if (!uniform || array.length % 3 !== 0)
  7644. return;
  7645. this._gl.uniform3iv(uniform, array);
  7646. };
  7647. Engine.prototype.setIntArray4 = function (uniform, array) {
  7648. if (!uniform || array.length % 4 !== 0)
  7649. return;
  7650. this._gl.uniform4iv(uniform, array);
  7651. };
  7652. Engine.prototype.setFloatArray = function (uniform, array) {
  7653. if (!uniform)
  7654. return;
  7655. this._gl.uniform1fv(uniform, array);
  7656. };
  7657. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7658. if (!uniform || array.length % 2 !== 0)
  7659. return;
  7660. this._gl.uniform2fv(uniform, array);
  7661. };
  7662. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7663. if (!uniform || array.length % 3 !== 0)
  7664. return;
  7665. this._gl.uniform3fv(uniform, array);
  7666. };
  7667. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7668. if (!uniform || array.length % 4 !== 0)
  7669. return;
  7670. this._gl.uniform4fv(uniform, array);
  7671. };
  7672. Engine.prototype.setArray = function (uniform, array) {
  7673. if (!uniform)
  7674. return;
  7675. this._gl.uniform1fv(uniform, array);
  7676. };
  7677. Engine.prototype.setArray2 = function (uniform, array) {
  7678. if (!uniform || array.length % 2 !== 0)
  7679. return;
  7680. this._gl.uniform2fv(uniform, array);
  7681. };
  7682. Engine.prototype.setArray3 = function (uniform, array) {
  7683. if (!uniform || array.length % 3 !== 0)
  7684. return;
  7685. this._gl.uniform3fv(uniform, array);
  7686. };
  7687. Engine.prototype.setArray4 = function (uniform, array) {
  7688. if (!uniform || array.length % 4 !== 0)
  7689. return;
  7690. this._gl.uniform4fv(uniform, array);
  7691. };
  7692. Engine.prototype.setMatrices = function (uniform, matrices) {
  7693. if (!uniform)
  7694. return;
  7695. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7696. };
  7697. Engine.prototype.setMatrix = function (uniform, matrix) {
  7698. if (!uniform)
  7699. return;
  7700. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7701. };
  7702. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7703. if (!uniform)
  7704. return;
  7705. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7706. };
  7707. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7708. if (!uniform)
  7709. return;
  7710. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7711. };
  7712. Engine.prototype.setFloat = function (uniform, value) {
  7713. if (!uniform)
  7714. return;
  7715. this._gl.uniform1f(uniform, value);
  7716. };
  7717. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7718. if (!uniform)
  7719. return;
  7720. this._gl.uniform2f(uniform, x, y);
  7721. };
  7722. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7723. if (!uniform)
  7724. return;
  7725. this._gl.uniform3f(uniform, x, y, z);
  7726. };
  7727. Engine.prototype.setBool = function (uniform, bool) {
  7728. if (!uniform)
  7729. return;
  7730. this._gl.uniform1i(uniform, bool);
  7731. };
  7732. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7733. if (!uniform)
  7734. return;
  7735. this._gl.uniform4f(uniform, x, y, z, w);
  7736. };
  7737. Engine.prototype.setColor3 = function (uniform, color3) {
  7738. if (!uniform)
  7739. return;
  7740. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7741. };
  7742. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7743. if (!uniform)
  7744. return;
  7745. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7746. };
  7747. // States
  7748. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7749. if (zOffset === void 0) { zOffset = 0; }
  7750. if (reverseSide === void 0) { reverseSide = false; }
  7751. // Culling
  7752. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7753. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7754. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7755. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7756. if (culling) {
  7757. this._depthCullingState.cullFace = cullFace;
  7758. this._depthCullingState.cull = true;
  7759. }
  7760. else {
  7761. this._depthCullingState.cull = false;
  7762. }
  7763. }
  7764. // Z offset
  7765. this._depthCullingState.zOffset = zOffset;
  7766. };
  7767. Engine.prototype.setDepthBuffer = function (enable) {
  7768. this._depthCullingState.depthTest = enable;
  7769. };
  7770. Engine.prototype.getDepthWrite = function () {
  7771. return this._depthCullingState.depthMask;
  7772. };
  7773. Engine.prototype.setDepthWrite = function (enable) {
  7774. this._depthCullingState.depthMask = enable;
  7775. };
  7776. Engine.prototype.setColorWrite = function (enable) {
  7777. this._gl.colorMask(enable, enable, enable, enable);
  7778. };
  7779. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7780. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7781. if (this._alphaMode === mode) {
  7782. return;
  7783. }
  7784. switch (mode) {
  7785. case Engine.ALPHA_DISABLE:
  7786. this._alphaState.alphaBlend = false;
  7787. break;
  7788. case Engine.ALPHA_COMBINE:
  7789. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7790. this._alphaState.alphaBlend = true;
  7791. break;
  7792. case Engine.ALPHA_ONEONE:
  7793. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7794. this._alphaState.alphaBlend = true;
  7795. break;
  7796. case Engine.ALPHA_ADD:
  7797. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7798. this._alphaState.alphaBlend = true;
  7799. break;
  7800. case Engine.ALPHA_SUBTRACT:
  7801. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7802. this._alphaState.alphaBlend = true;
  7803. break;
  7804. case Engine.ALPHA_MULTIPLY:
  7805. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7806. this._alphaState.alphaBlend = true;
  7807. break;
  7808. case Engine.ALPHA_MAXIMIZED:
  7809. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7810. this._alphaState.alphaBlend = true;
  7811. break;
  7812. }
  7813. if (!noDepthWriteChange) {
  7814. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7815. }
  7816. this._alphaMode = mode;
  7817. };
  7818. Engine.prototype.getAlphaMode = function () {
  7819. return this._alphaMode;
  7820. };
  7821. Engine.prototype.setAlphaTesting = function (enable) {
  7822. this._alphaTest = enable;
  7823. };
  7824. Engine.prototype.getAlphaTesting = function () {
  7825. return this._alphaTest;
  7826. };
  7827. // Textures
  7828. Engine.prototype.wipeCaches = function () {
  7829. this.resetTextureCache();
  7830. this._currentEffect = null;
  7831. this._stencilState.reset();
  7832. this._depthCullingState.reset();
  7833. this.setDepthFunctionToLessOrEqual();
  7834. this._alphaState.reset();
  7835. this._cachedVertexBuffers = null;
  7836. this._cachedIndexBuffer = null;
  7837. this._cachedEffectForVertexBuffers = null;
  7838. };
  7839. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7840. var gl = this._gl;
  7841. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7842. var magFilter = gl.NEAREST;
  7843. var minFilter = gl.NEAREST;
  7844. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7845. magFilter = gl.LINEAR;
  7846. minFilter = gl.LINEAR;
  7847. }
  7848. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7849. magFilter = gl.LINEAR;
  7850. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7851. }
  7852. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7853. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7854. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7855. texture.samplingMode = samplingMode;
  7856. };
  7857. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7858. var _this = this;
  7859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7860. if (onLoad === void 0) { onLoad = null; }
  7861. if (onError === void 0) { onError = null; }
  7862. if (buffer === void 0) { buffer = null; }
  7863. var texture = this._gl.createTexture();
  7864. var extension;
  7865. var fromData = false;
  7866. if (url.substr(0, 5) === "data:") {
  7867. fromData = true;
  7868. }
  7869. if (!fromData)
  7870. extension = url.substr(url.length - 4, 4).toLowerCase();
  7871. else {
  7872. var oldUrl = url;
  7873. fromData = oldUrl.split(':');
  7874. url = oldUrl;
  7875. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7876. }
  7877. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7878. var isTGA = (extension === ".tga");
  7879. scene._addPendingData(texture);
  7880. texture.url = url;
  7881. texture.noMipmap = noMipmap;
  7882. texture.references = 1;
  7883. texture.samplingMode = samplingMode;
  7884. texture.onLoadedCallbacks = [onLoad];
  7885. this._loadedTexturesCache.push(texture);
  7886. var onerror = function () {
  7887. scene._removePendingData(texture);
  7888. if (onError) {
  7889. onError();
  7890. }
  7891. };
  7892. var callback;
  7893. if (isTGA) {
  7894. callback = function (arrayBuffer) {
  7895. var data = new Uint8Array(arrayBuffer);
  7896. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7897. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7898. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7899. }, samplingMode);
  7900. };
  7901. if (!(fromData instanceof Array))
  7902. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7903. callback(arrayBuffer);
  7904. }, null, scene.database, true, onerror);
  7905. else
  7906. callback(buffer);
  7907. }
  7908. else if (isDDS) {
  7909. callback = function (data) {
  7910. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7911. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7912. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7913. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7914. }, samplingMode);
  7915. };
  7916. if (!(fromData instanceof Array))
  7917. BABYLON.Tools.LoadFile(url, function (data) {
  7918. callback(data);
  7919. }, null, scene.database, true, onerror);
  7920. else
  7921. callback(buffer);
  7922. }
  7923. else {
  7924. var onload = function (img) {
  7925. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7926. var isPot = (img.width === potWidth && img.height === potHeight);
  7927. if (!isPot) {
  7928. _this._prepareWorkingCanvas();
  7929. _this._workingCanvas.width = potWidth;
  7930. _this._workingCanvas.height = potHeight;
  7931. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7932. _this._workingContext.imageSmoothingEnabled = false;
  7933. _this._workingContext.mozImageSmoothingEnabled = false;
  7934. _this._workingContext.oImageSmoothingEnabled = false;
  7935. _this._workingContext.webkitImageSmoothingEnabled = false;
  7936. _this._workingContext.msImageSmoothingEnabled = false;
  7937. }
  7938. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7939. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7940. _this._workingContext.imageSmoothingEnabled = true;
  7941. _this._workingContext.mozImageSmoothingEnabled = true;
  7942. _this._workingContext.oImageSmoothingEnabled = true;
  7943. _this._workingContext.webkitImageSmoothingEnabled = true;
  7944. _this._workingContext.msImageSmoothingEnabled = true;
  7945. }
  7946. }
  7947. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7948. }, samplingMode);
  7949. };
  7950. if (!(fromData instanceof Array))
  7951. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7952. else
  7953. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7954. }
  7955. return texture;
  7956. };
  7957. Engine.prototype._getInternalFormat = function (format) {
  7958. var internalFormat = this._gl.RGBA;
  7959. switch (format) {
  7960. case Engine.TEXTUREFORMAT_ALPHA:
  7961. internalFormat = this._gl.ALPHA;
  7962. break;
  7963. case Engine.TEXTUREFORMAT_LUMINANCE:
  7964. internalFormat = this._gl.LUMINANCE;
  7965. break;
  7966. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7967. internalFormat = this._gl.LUMINANCE_ALPHA;
  7968. break;
  7969. case Engine.TEXTUREFORMAT_RGB:
  7970. internalFormat = this._gl.RGB;
  7971. break;
  7972. case Engine.TEXTUREFORMAT_RGBA:
  7973. internalFormat = this._gl.RGBA;
  7974. break;
  7975. }
  7976. return internalFormat;
  7977. };
  7978. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7979. if (compression === void 0) { compression = null; }
  7980. var internalFormat = this._getInternalFormat(format);
  7981. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7982. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7983. if (texture._width % 4 !== 0) {
  7984. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7985. }
  7986. if (compression) {
  7987. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7988. }
  7989. else {
  7990. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7991. }
  7992. if (texture.generateMipMaps) {
  7993. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7994. }
  7995. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7996. this.resetTextureCache();
  7997. texture.isReady = true;
  7998. };
  7999. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8000. if (compression === void 0) { compression = null; }
  8001. var texture = this._gl.createTexture();
  8002. texture._baseWidth = width;
  8003. texture._baseHeight = height;
  8004. texture._width = width;
  8005. texture._height = height;
  8006. texture.references = 1;
  8007. this.updateRawTexture(texture, data, format, invertY, compression);
  8008. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8009. // Filters
  8010. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8011. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8012. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8013. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8014. texture.samplingMode = samplingMode;
  8015. this._loadedTexturesCache.push(texture);
  8016. return texture;
  8017. };
  8018. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8019. var texture = this._gl.createTexture();
  8020. texture._baseWidth = width;
  8021. texture._baseHeight = height;
  8022. if (generateMipMaps) {
  8023. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8024. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8025. }
  8026. this.resetTextureCache();
  8027. texture._width = width;
  8028. texture._height = height;
  8029. texture.isReady = false;
  8030. texture.generateMipMaps = generateMipMaps;
  8031. texture.references = 1;
  8032. texture.samplingMode = samplingMode;
  8033. this.updateTextureSamplingMode(samplingMode, texture);
  8034. this._loadedTexturesCache.push(texture);
  8035. return texture;
  8036. };
  8037. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8038. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8039. if (texture.isCube) {
  8040. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8041. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8042. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8043. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8044. }
  8045. else {
  8046. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8047. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8048. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8049. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8050. }
  8051. };
  8052. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8053. if (premulAlpha === void 0) { premulAlpha = false; }
  8054. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8055. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8056. if (premulAlpha) {
  8057. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8058. }
  8059. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8060. if (texture.generateMipMaps) {
  8061. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8062. }
  8063. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8064. if (premulAlpha) {
  8065. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8066. }
  8067. this.resetTextureCache();
  8068. texture.isReady = true;
  8069. };
  8070. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8071. if (texture._isDisabled) {
  8072. return;
  8073. }
  8074. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8075. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8076. try {
  8077. // Testing video texture support
  8078. if (this._videoTextureSupported === undefined) {
  8079. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8080. if (this._gl.getError() !== 0) {
  8081. this._videoTextureSupported = false;
  8082. }
  8083. else {
  8084. this._videoTextureSupported = true;
  8085. }
  8086. }
  8087. // Copy video through the current working canvas if video texture is not supported
  8088. if (!this._videoTextureSupported) {
  8089. if (!texture._workingCanvas) {
  8090. texture._workingCanvas = document.createElement("canvas");
  8091. texture._workingContext = texture._workingCanvas.getContext("2d");
  8092. texture._workingCanvas.width = texture._width;
  8093. texture._workingCanvas.height = texture._height;
  8094. }
  8095. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8096. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8097. }
  8098. else {
  8099. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8100. }
  8101. if (texture.generateMipMaps) {
  8102. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8103. }
  8104. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8105. this.resetTextureCache();
  8106. texture.isReady = true;
  8107. }
  8108. catch (ex) {
  8109. // Something unexpected
  8110. // Let's disable the texture
  8111. texture._isDisabled = true;
  8112. }
  8113. };
  8114. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8115. // old version had a "generateMipMaps" arg instead of options.
  8116. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8117. // in the same way, generateDepthBuffer is defaulted to true
  8118. var generateMipMaps = false;
  8119. var generateDepthBuffer = true;
  8120. var generateStencilBuffer = false;
  8121. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8122. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8123. if (options !== undefined) {
  8124. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8125. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8126. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8127. type = options.type === undefined ? type : options.type;
  8128. if (options.samplingMode !== undefined) {
  8129. samplingMode = options.samplingMode;
  8130. }
  8131. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8132. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8133. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8134. }
  8135. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8136. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8137. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8138. }
  8139. }
  8140. var gl = this._gl;
  8141. var texture = gl.createTexture();
  8142. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8143. var width = size.width || size;
  8144. var height = size.height || size;
  8145. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8146. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8147. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8148. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8149. }
  8150. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8151. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8152. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8153. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8154. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8155. var depthStencilBuffer;
  8156. // Create the depth/stencil buffer
  8157. if (generateStencilBuffer) {
  8158. depthStencilBuffer = gl.createRenderbuffer();
  8159. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8160. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8161. }
  8162. else if (generateDepthBuffer) {
  8163. depthStencilBuffer = gl.createRenderbuffer();
  8164. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8165. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8166. }
  8167. // Create the framebuffer
  8168. var framebuffer = gl.createFramebuffer();
  8169. this.bindUnboundFramebuffer(framebuffer);
  8170. // Manage attachments
  8171. if (generateStencilBuffer) {
  8172. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8173. }
  8174. else if (generateDepthBuffer) {
  8175. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8176. }
  8177. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8178. if (generateMipMaps) {
  8179. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8180. }
  8181. // Unbind
  8182. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8183. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8184. this.bindUnboundFramebuffer(null);
  8185. texture._framebuffer = framebuffer;
  8186. if (generateDepthBuffer) {
  8187. texture._depthBuffer = depthStencilBuffer;
  8188. }
  8189. texture._baseWidth = width;
  8190. texture._baseHeight = height;
  8191. texture._width = width;
  8192. texture._height = height;
  8193. texture.isReady = true;
  8194. texture.generateMipMaps = generateMipMaps;
  8195. texture.references = 1;
  8196. texture.samplingMode = samplingMode;
  8197. texture.type = type;
  8198. this.resetTextureCache();
  8199. this._loadedTexturesCache.push(texture);
  8200. return texture;
  8201. };
  8202. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8203. var gl = this._gl;
  8204. var texture = gl.createTexture();
  8205. var generateMipMaps = true;
  8206. var generateDepthBuffer = true;
  8207. var generateStencilBuffer = false;
  8208. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8209. if (options !== undefined) {
  8210. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8211. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8212. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8213. if (options.samplingMode !== undefined) {
  8214. samplingMode = options.samplingMode;
  8215. }
  8216. }
  8217. texture.isCube = true;
  8218. texture.references = 1;
  8219. texture.generateMipMaps = generateMipMaps;
  8220. texture.references = 1;
  8221. texture.samplingMode = samplingMode;
  8222. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8223. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8224. for (var face = 0; face < 6; face++) {
  8225. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8226. }
  8227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8229. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8230. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8231. // Create the depth buffer
  8232. var depthStencilBuffer;
  8233. // Create the depth/stencil buffer
  8234. if (generateStencilBuffer) {
  8235. depthStencilBuffer = gl.createRenderbuffer();
  8236. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8237. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8238. }
  8239. else if (generateDepthBuffer) {
  8240. depthStencilBuffer = gl.createRenderbuffer();
  8241. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8242. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8243. }
  8244. // Create the framebuffer
  8245. var framebuffer = gl.createFramebuffer();
  8246. this.bindUnboundFramebuffer(framebuffer);
  8247. // Manage attachments
  8248. if (generateStencilBuffer) {
  8249. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8250. }
  8251. else if (generateDepthBuffer) {
  8252. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8253. }
  8254. // Mipmaps
  8255. if (texture.generateMipMaps) {
  8256. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8257. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8258. }
  8259. // Unbind
  8260. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8261. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8262. this.bindUnboundFramebuffer(null);
  8263. texture._framebuffer = framebuffer;
  8264. if (generateDepthBuffer) {
  8265. texture._depthBuffer = depthStencilBuffer;
  8266. }
  8267. texture._width = size;
  8268. texture._height = size;
  8269. texture.isReady = true;
  8270. this.resetTextureCache();
  8271. this._loadedTexturesCache.push(texture);
  8272. return texture;
  8273. };
  8274. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8275. var _this = this;
  8276. if (onLoad === void 0) { onLoad = null; }
  8277. if (onError === void 0) { onError = null; }
  8278. var gl = this._gl;
  8279. var texture = gl.createTexture();
  8280. texture.isCube = true;
  8281. texture.url = rootUrl;
  8282. texture.references = 1;
  8283. texture.onLoadedCallbacks = [];
  8284. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8285. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8286. if (isDDS) {
  8287. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8288. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8289. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8290. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8291. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8292. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8293. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8294. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8295. }
  8296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8299. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8300. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8301. _this.resetTextureCache();
  8302. texture._width = info.width;
  8303. texture._height = info.height;
  8304. texture.isReady = true;
  8305. }, null, null, true, onError);
  8306. }
  8307. else {
  8308. cascadeLoad(rootUrl, scene, function (imgs) {
  8309. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8310. var height = width;
  8311. _this._prepareWorkingCanvas();
  8312. _this._workingCanvas.width = width;
  8313. _this._workingCanvas.height = height;
  8314. var faces = [
  8315. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8316. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8317. ];
  8318. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8319. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8320. for (var index = 0; index < faces.length; index++) {
  8321. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8322. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8323. }
  8324. if (!noMipmap) {
  8325. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8326. }
  8327. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8328. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8329. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8330. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8331. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8332. _this.resetTextureCache();
  8333. texture._width = width;
  8334. texture._height = height;
  8335. texture.isReady = true;
  8336. texture.onLoadedCallbacks.forEach(function (callback) {
  8337. callback();
  8338. });
  8339. if (onLoad) {
  8340. onLoad();
  8341. }
  8342. }, files, onError);
  8343. }
  8344. this._loadedTexturesCache.push(texture);
  8345. return texture;
  8346. };
  8347. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8348. texture._width = width;
  8349. texture._height = height;
  8350. texture._size = width * height;
  8351. texture._baseWidth = width;
  8352. texture._baseHeight = height;
  8353. };
  8354. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8355. var _this = this;
  8356. var gl = this._gl;
  8357. var texture = gl.createTexture();
  8358. scene._addPendingData(texture);
  8359. texture.isCube = true;
  8360. texture.references = 1;
  8361. texture.url = url;
  8362. var internalFormat = this._getInternalFormat(format);
  8363. var textureType = gl.UNSIGNED_BYTE;
  8364. if (type === Engine.TEXTURETYPE_FLOAT) {
  8365. textureType = gl.FLOAT;
  8366. }
  8367. var width = size;
  8368. var height = width;
  8369. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8370. texture._width = width;
  8371. texture._height = height;
  8372. var onerror = function () {
  8373. scene._removePendingData(texture);
  8374. };
  8375. var internalCallback = function (data) {
  8376. var rgbeDataArrays = callback(data);
  8377. var facesIndex = [
  8378. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8379. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8380. ];
  8381. width = texture._width;
  8382. height = texture._height;
  8383. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8384. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8385. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8386. if (!noMipmap && isPot) {
  8387. if (mipmmapGenerator) {
  8388. var arrayTemp = [];
  8389. // Data are known to be in +X +Y +Z -X -Y -Z
  8390. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8391. arrayTemp.push(rgbeDataArrays[0]); // +X
  8392. arrayTemp.push(rgbeDataArrays[3]); // -X
  8393. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8394. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8395. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8396. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8397. var mipData = mipmmapGenerator(arrayTemp);
  8398. for (var level = 0; level < mipData.length; level++) {
  8399. var mipSize = width >> level;
  8400. // mipData is order in +X -X +Y -Y +Z -Z
  8401. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8402. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8403. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8404. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8405. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8406. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8407. }
  8408. }
  8409. else {
  8410. // Data are known to be in +X +Y +Z -X -Y -Z
  8411. for (var index = 0; index < facesIndex.length; index++) {
  8412. var faceData = rgbeDataArrays[index];
  8413. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8414. }
  8415. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8416. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8417. // By following the webgl standard changes from Revision 7, 2014/11/24
  8418. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8419. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8420. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8421. // Data are known to be in +X +Y +Z -X -Y -Z
  8422. for (var index = 0; index < facesIndex.length; index++) {
  8423. var faceData = rgbeDataArrays[index];
  8424. // Create a new RGBA Face.
  8425. var newFaceData = new Float32Array(width * height * 4);
  8426. for (var x = 0; x < width; x++) {
  8427. for (var y = 0; y < height; y++) {
  8428. var index_1 = (y * width + x) * 3;
  8429. var newIndex = (y * width + x) * 4;
  8430. // Map Old Value to new value.
  8431. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8432. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8433. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8434. // Add fully opaque alpha channel.
  8435. newFaceData[newIndex + 3] = 1;
  8436. }
  8437. }
  8438. // Reupload the face.
  8439. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8440. }
  8441. // Try to generate mipmap again.
  8442. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8443. }
  8444. }
  8445. }
  8446. else {
  8447. noMipmap = true;
  8448. }
  8449. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8450. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8451. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8452. }
  8453. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8454. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8455. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8456. }
  8457. else {
  8458. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8460. }
  8461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8462. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8463. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8464. texture.isReady = true;
  8465. _this.resetTextureCache();
  8466. scene._removePendingData(texture);
  8467. };
  8468. BABYLON.Tools.LoadFile(url, function (data) {
  8469. internalCallback(data);
  8470. }, onerror, scene.database, true);
  8471. return texture;
  8472. };
  8473. ;
  8474. Engine.prototype._releaseTexture = function (texture) {
  8475. var gl = this._gl;
  8476. if (texture._framebuffer) {
  8477. gl.deleteFramebuffer(texture._framebuffer);
  8478. }
  8479. if (texture._depthBuffer) {
  8480. gl.deleteRenderbuffer(texture._depthBuffer);
  8481. }
  8482. gl.deleteTexture(texture);
  8483. // Unbind channels
  8484. this.unbindAllTextures();
  8485. var index = this._loadedTexturesCache.indexOf(texture);
  8486. if (index !== -1) {
  8487. this._loadedTexturesCache.splice(index, 1);
  8488. }
  8489. };
  8490. Engine.prototype.setProgram = function (program) {
  8491. if (this._currentProgram !== program) {
  8492. this._gl.useProgram(program);
  8493. this._currentProgram = program;
  8494. }
  8495. };
  8496. Engine.prototype.bindSamplers = function (effect) {
  8497. this.setProgram(effect.getProgram());
  8498. var samplers = effect.getSamplers();
  8499. for (var index = 0; index < samplers.length; index++) {
  8500. var uniform = effect.getUniform(samplers[index]);
  8501. this._gl.uniform1i(uniform, index);
  8502. }
  8503. this._currentEffect = null;
  8504. };
  8505. Engine.prototype.activateTexture = function (texture) {
  8506. if (this._activeTexture !== texture) {
  8507. this._gl.activeTexture(texture);
  8508. this._activeTexture = texture;
  8509. }
  8510. };
  8511. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8512. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8513. this._gl.bindTexture(target, texture);
  8514. this._activeTexturesCache[this._activeTexture] = texture;
  8515. }
  8516. };
  8517. Engine.prototype._bindTexture = function (channel, texture) {
  8518. if (channel < 0) {
  8519. return;
  8520. }
  8521. this.activateTexture(this._gl["TEXTURE" + channel]);
  8522. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8523. };
  8524. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8525. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8526. };
  8527. Engine.prototype.unbindAllTextures = function () {
  8528. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8529. this.activateTexture(this._gl["TEXTURE" + channel]);
  8530. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8531. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8532. }
  8533. };
  8534. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8535. if (channel < 0) {
  8536. return;
  8537. }
  8538. this._gl.uniform1i(uniform, channel);
  8539. this._setTexture(channel, texture);
  8540. };
  8541. Engine.prototype._setTexture = function (channel, texture) {
  8542. // Not ready?
  8543. if (!texture || !texture.isReady()) {
  8544. if (this._activeTexturesCache[channel] != null) {
  8545. this.activateTexture(this._gl["TEXTURE" + channel]);
  8546. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8547. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8548. }
  8549. return;
  8550. }
  8551. // Video
  8552. var alreadyActivated = false;
  8553. if (texture instanceof BABYLON.VideoTexture) {
  8554. this.activateTexture(this._gl["TEXTURE" + channel]);
  8555. alreadyActivated = true;
  8556. texture.update();
  8557. }
  8558. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8559. texture.delayLoad();
  8560. return;
  8561. }
  8562. var internalTexture = texture.getInternalTexture();
  8563. if (this._activeTexturesCache[channel] === internalTexture) {
  8564. return;
  8565. }
  8566. if (!alreadyActivated) {
  8567. this.activateTexture(this._gl["TEXTURE" + channel]);
  8568. }
  8569. if (internalTexture.isCube) {
  8570. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8571. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8572. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8573. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8574. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8575. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8576. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8577. }
  8578. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8579. }
  8580. else {
  8581. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8582. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8583. internalTexture._cachedWrapU = texture.wrapU;
  8584. switch (texture.wrapU) {
  8585. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8586. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8587. break;
  8588. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8589. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8590. break;
  8591. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8592. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8593. break;
  8594. }
  8595. }
  8596. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8597. internalTexture._cachedWrapV = texture.wrapV;
  8598. switch (texture.wrapV) {
  8599. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8600. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8601. break;
  8602. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8603. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8604. break;
  8605. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8606. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8607. break;
  8608. }
  8609. }
  8610. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8611. }
  8612. };
  8613. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8614. if (channel < 0) {
  8615. return;
  8616. }
  8617. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8618. this._textureUnits = new Int32Array(textures.length);
  8619. }
  8620. for (var i = 0; i < textures.length; i++) {
  8621. this._textureUnits[i] = channel + i;
  8622. }
  8623. this._gl.uniform1iv(uniform, this._textureUnits);
  8624. for (var index = 0; index < textures.length; index++) {
  8625. this._setTexture(channel + index, textures[index]);
  8626. }
  8627. };
  8628. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8629. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8630. var value = texture.anisotropicFilteringLevel;
  8631. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8632. value = 1;
  8633. }
  8634. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8635. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8636. texture._cachedAnisotropicFilteringLevel = value;
  8637. }
  8638. };
  8639. Engine.prototype.readPixels = function (x, y, width, height) {
  8640. var data = new Uint8Array(height * width * 4);
  8641. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8642. return data;
  8643. };
  8644. /**
  8645. * Add an externaly attached data from its key.
  8646. * This method call will fail and return false, if such key already exists.
  8647. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8648. * @param key the unique key that identifies the data
  8649. * @param data the data object to associate to the key for this Engine instance
  8650. * @return true if no such key were already present and the data was added successfully, false otherwise
  8651. */
  8652. Engine.prototype.addExternalData = function (key, data) {
  8653. return this._externalData.add(key, data);
  8654. };
  8655. /**
  8656. * Get an externaly attached data from its key
  8657. * @param key the unique key that identifies the data
  8658. * @return the associated data, if present (can be null), or undefined if not present
  8659. */
  8660. Engine.prototype.getExternalData = function (key) {
  8661. return this._externalData.get(key);
  8662. };
  8663. /**
  8664. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8665. * @param key the unique key that identifies the data
  8666. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8667. * @return the associated data, can be null if the factory returned null.
  8668. */
  8669. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8670. return this._externalData.getOrAddWithFactory(key, factory);
  8671. };
  8672. /**
  8673. * Remove an externaly attached data from the Engine instance
  8674. * @param key the unique key that identifies the data
  8675. * @return true if the data was successfully removed, false if it doesn't exist
  8676. */
  8677. Engine.prototype.removeExternalData = function (key) {
  8678. return this._externalData.remove(key);
  8679. };
  8680. Engine.prototype.releaseInternalTexture = function (texture) {
  8681. if (!texture) {
  8682. return;
  8683. }
  8684. texture.references--;
  8685. // Final reference ?
  8686. if (texture.references === 0) {
  8687. var texturesCache = this.getLoadedTexturesCache();
  8688. var index = texturesCache.indexOf(texture);
  8689. if (index > -1) {
  8690. texturesCache.splice(index, 1);
  8691. }
  8692. this._releaseTexture(texture);
  8693. }
  8694. };
  8695. Engine.prototype.unbindAllAttributes = function () {
  8696. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8697. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8698. continue;
  8699. }
  8700. this._gl.disableVertexAttribArray(i);
  8701. this._vertexAttribArraysEnabled[i] = false;
  8702. }
  8703. };
  8704. // Dispose
  8705. Engine.prototype.dispose = function () {
  8706. this.hideLoadingUI();
  8707. this.stopRenderLoop();
  8708. // Release scenes
  8709. while (this.scenes.length) {
  8710. this.scenes[0].dispose();
  8711. }
  8712. // Release audio engine
  8713. Engine.audioEngine.dispose();
  8714. // Release effects
  8715. for (var name in this._compiledEffects) {
  8716. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8717. }
  8718. // Unbind
  8719. this.unbindAllAttributes();
  8720. this._gl = null;
  8721. //WebVR
  8722. this.disableVR();
  8723. // Events
  8724. window.removeEventListener("blur", this._onBlur);
  8725. window.removeEventListener("focus", this._onFocus);
  8726. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8727. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8728. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8729. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8730. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8731. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8732. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8733. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8734. };
  8735. // Loading screen
  8736. Engine.prototype.displayLoadingUI = function () {
  8737. this._loadingScreen.displayLoadingUI();
  8738. };
  8739. Engine.prototype.hideLoadingUI = function () {
  8740. this._loadingScreen.hideLoadingUI();
  8741. };
  8742. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8743. get: function () {
  8744. return this._loadingScreen;
  8745. },
  8746. set: function (loadingScreen) {
  8747. this._loadingScreen = loadingScreen;
  8748. },
  8749. enumerable: true,
  8750. configurable: true
  8751. });
  8752. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8753. set: function (text) {
  8754. this._loadingScreen.loadingUIText = text;
  8755. },
  8756. enumerable: true,
  8757. configurable: true
  8758. });
  8759. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8760. set: function (color) {
  8761. this._loadingScreen.loadingUIBackgroundColor = color;
  8762. },
  8763. enumerable: true,
  8764. configurable: true
  8765. });
  8766. Engine.prototype.attachContextLostEvent = function (callback) {
  8767. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8768. };
  8769. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8770. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8771. };
  8772. // FPS
  8773. Engine.prototype.getFps = function () {
  8774. return this.fps;
  8775. };
  8776. Engine.prototype.getDeltaTime = function () {
  8777. return this.deltaTime;
  8778. };
  8779. Engine.prototype._measureFps = function () {
  8780. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8781. var length = this.previousFramesDuration.length;
  8782. if (length >= 2) {
  8783. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8784. }
  8785. if (length >= this.fpsRange) {
  8786. if (length > this.fpsRange) {
  8787. this.previousFramesDuration.splice(0, 1);
  8788. length = this.previousFramesDuration.length;
  8789. }
  8790. var sum = 0;
  8791. for (var id = 0; id < length - 1; id++) {
  8792. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8793. }
  8794. this.fps = 1000.0 / (sum / (length - 1));
  8795. }
  8796. };
  8797. Engine.prototype._canRenderToFloatTexture = function () {
  8798. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8799. };
  8800. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8801. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8802. };
  8803. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8804. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8805. var tempcanvas = document.createElement("canvas");
  8806. tempcanvas.height = 16;
  8807. tempcanvas.width = 16;
  8808. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8809. // extension.
  8810. var ext = gl.getExtension(extension);
  8811. if (!ext) {
  8812. return false;
  8813. }
  8814. // setup GLSL program
  8815. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8816. 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 }";
  8817. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8818. gl.useProgram(program);
  8819. // look up where the vertex data needs to go.
  8820. var positionLocation = gl.getAttribLocation(program, "a_position");
  8821. var colorLoc = gl.getUniformLocation(program, "u_color");
  8822. // provide texture coordinates for the rectangle.
  8823. var positionBuffer = gl.createBuffer();
  8824. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8825. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8826. -1.0, -1.0,
  8827. 1.0, -1.0,
  8828. -1.0, 1.0,
  8829. -1.0, 1.0,
  8830. 1.0, -1.0,
  8831. 1.0, 1.0]), gl.STATIC_DRAW);
  8832. gl.enableVertexAttribArray(positionLocation);
  8833. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8834. var whiteTex = gl.createTexture();
  8835. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8836. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8837. var tex = gl.createTexture();
  8838. gl.bindTexture(gl.TEXTURE_2D, tex);
  8839. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8840. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8841. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8842. var fb = gl.createFramebuffer();
  8843. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8844. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8845. var cleanup = function () {
  8846. gl.deleteProgram(program);
  8847. gl.disableVertexAttribArray(positionLocation);
  8848. gl.deleteBuffer(positionBuffer);
  8849. gl.deleteFramebuffer(fb);
  8850. gl.deleteTexture(whiteTex);
  8851. gl.deleteTexture(tex);
  8852. };
  8853. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8854. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8855. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8856. cleanup();
  8857. return false;
  8858. }
  8859. // Draw the rectangle.
  8860. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8861. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8862. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8863. gl.bindTexture(gl.TEXTURE_2D, tex);
  8864. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8865. gl.clearColor(1, 0, 0, 1);
  8866. gl.clear(gl.COLOR_BUFFER_BIT);
  8867. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8868. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8869. var pixel = new Uint8Array(4);
  8870. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8871. if (pixel[0] !== 0 ||
  8872. pixel[1] < 248 ||
  8873. pixel[2] < 248 ||
  8874. pixel[3] < 254) {
  8875. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8876. cleanup();
  8877. return false;
  8878. }
  8879. // Succesfully rendered to "format" texture.
  8880. cleanup();
  8881. return true;
  8882. };
  8883. // Statics
  8884. Engine.isSupported = function () {
  8885. try {
  8886. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8887. if (navigator.isCocoonJS) {
  8888. return true;
  8889. }
  8890. var tempcanvas = document.createElement("canvas");
  8891. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8892. return gl != null && !!window.WebGLRenderingContext;
  8893. }
  8894. catch (e) {
  8895. return false;
  8896. }
  8897. };
  8898. // Const statics
  8899. Engine._ALPHA_DISABLE = 0;
  8900. Engine._ALPHA_ADD = 1;
  8901. Engine._ALPHA_COMBINE = 2;
  8902. Engine._ALPHA_SUBTRACT = 3;
  8903. Engine._ALPHA_MULTIPLY = 4;
  8904. Engine._ALPHA_MAXIMIZED = 5;
  8905. Engine._ALPHA_ONEONE = 6;
  8906. Engine._DELAYLOADSTATE_NONE = 0;
  8907. Engine._DELAYLOADSTATE_LOADED = 1;
  8908. Engine._DELAYLOADSTATE_LOADING = 2;
  8909. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8910. Engine._TEXTUREFORMAT_ALPHA = 0;
  8911. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8912. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8913. Engine._TEXTUREFORMAT_RGB = 4;
  8914. Engine._TEXTUREFORMAT_RGBA = 5;
  8915. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8916. Engine._TEXTURETYPE_FLOAT = 1;
  8917. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8918. // Depht or Stencil test Constants.
  8919. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  8920. 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.
  8921. 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.
  8922. 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.
  8923. 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.
  8924. 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.
  8925. 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.
  8926. 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.
  8927. // Stencil Actions Constants.
  8928. Engine._KEEP = 0x1E00;
  8929. Engine._REPLACE = 0x1E01;
  8930. Engine._INCR = 0x1E02;
  8931. Engine._DECR = 0x1E03;
  8932. Engine._INVERT = 0x150A;
  8933. Engine._INCR_WRAP = 0x8507;
  8934. Engine._DECR_WRAP = 0x8508;
  8935. // Updatable statics so stick with vars here
  8936. Engine.CollisionsEpsilon = 0.001;
  8937. Engine.CodeRepository = "src/";
  8938. Engine.ShadersRepository = "src/Shaders/";
  8939. return Engine;
  8940. }());
  8941. BABYLON.Engine = Engine;
  8942. })(BABYLON || (BABYLON = {}));
  8943. var BABYLON;
  8944. (function (BABYLON) {
  8945. /**
  8946. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8947. */
  8948. var Node = (function () {
  8949. /**
  8950. * @constructor
  8951. * @param {string} name - the name and id to be given to this node
  8952. * @param {BABYLON.Scene} the scene this node will be added to
  8953. */
  8954. function Node(name, scene) {
  8955. this.state = "";
  8956. this.animations = new Array();
  8957. this._ranges = {};
  8958. this._childrenFlag = -1;
  8959. this._isEnabled = true;
  8960. this._isReady = true;
  8961. this._currentRenderId = -1;
  8962. this._parentRenderId = -1;
  8963. this.name = name;
  8964. this.id = name;
  8965. this._scene = scene;
  8966. this._initCache();
  8967. }
  8968. Object.defineProperty(Node.prototype, "parent", {
  8969. get: function () {
  8970. return this._parentNode;
  8971. },
  8972. set: function (parent) {
  8973. if (this._parentNode === parent) {
  8974. return;
  8975. }
  8976. if (this._parentNode) {
  8977. var index = this._parentNode._children.indexOf(this);
  8978. if (index !== -1) {
  8979. this._parentNode._children.splice(index, 1);
  8980. }
  8981. }
  8982. this._parentNode = parent;
  8983. if (this._parentNode) {
  8984. if (!this._parentNode._children) {
  8985. this._parentNode._children = new Array();
  8986. }
  8987. this._parentNode._children.push(this);
  8988. }
  8989. },
  8990. enumerable: true,
  8991. configurable: true
  8992. });
  8993. Node.prototype.getScene = function () {
  8994. return this._scene;
  8995. };
  8996. Node.prototype.getEngine = function () {
  8997. return this._scene.getEngine();
  8998. };
  8999. // override it in derived class
  9000. Node.prototype.getWorldMatrix = function () {
  9001. return BABYLON.Matrix.Identity();
  9002. };
  9003. // override it in derived class if you add new variables to the cache
  9004. // and call the parent class method
  9005. Node.prototype._initCache = function () {
  9006. this._cache = {};
  9007. this._cache.parent = undefined;
  9008. };
  9009. Node.prototype.updateCache = function (force) {
  9010. if (!force && this.isSynchronized())
  9011. return;
  9012. this._cache.parent = this.parent;
  9013. this._updateCache();
  9014. };
  9015. // override it in derived class if you add new variables to the cache
  9016. // and call the parent class method if !ignoreParentClass
  9017. Node.prototype._updateCache = function (ignoreParentClass) {
  9018. };
  9019. // override it in derived class if you add new variables to the cache
  9020. Node.prototype._isSynchronized = function () {
  9021. return true;
  9022. };
  9023. Node.prototype._markSyncedWithParent = function () {
  9024. this._parentRenderId = this.parent._currentRenderId;
  9025. };
  9026. Node.prototype.isSynchronizedWithParent = function () {
  9027. if (!this.parent) {
  9028. return true;
  9029. }
  9030. if (this._parentRenderId !== this.parent._currentRenderId) {
  9031. return false;
  9032. }
  9033. return this.parent.isSynchronized();
  9034. };
  9035. Node.prototype.isSynchronized = function (updateCache) {
  9036. var check = this.hasNewParent();
  9037. check = check || !this.isSynchronizedWithParent();
  9038. check = check || !this._isSynchronized();
  9039. if (updateCache)
  9040. this.updateCache(true);
  9041. return !check;
  9042. };
  9043. Node.prototype.hasNewParent = function (update) {
  9044. if (this._cache.parent === this.parent)
  9045. return false;
  9046. if (update)
  9047. this._cache.parent = this.parent;
  9048. return true;
  9049. };
  9050. /**
  9051. * Is this node ready to be used/rendered
  9052. * @return {boolean} is it ready
  9053. */
  9054. Node.prototype.isReady = function () {
  9055. return this._isReady;
  9056. };
  9057. /**
  9058. * Is this node enabled.
  9059. * If the node has a parent and is enabled, the parent will be inspected as well.
  9060. * @return {boolean} whether this node (and its parent) is enabled.
  9061. * @see setEnabled
  9062. */
  9063. Node.prototype.isEnabled = function () {
  9064. if (!this._isEnabled) {
  9065. return false;
  9066. }
  9067. if (this.parent) {
  9068. return this.parent.isEnabled();
  9069. }
  9070. return true;
  9071. };
  9072. /**
  9073. * Set the enabled state of this node.
  9074. * @param {boolean} value - the new enabled state
  9075. * @see isEnabled
  9076. */
  9077. Node.prototype.setEnabled = function (value) {
  9078. this._isEnabled = value;
  9079. };
  9080. /**
  9081. * Is this node a descendant of the given node.
  9082. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9083. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9084. * @see parent
  9085. */
  9086. Node.prototype.isDescendantOf = function (ancestor) {
  9087. if (this.parent) {
  9088. if (this.parent === ancestor) {
  9089. return true;
  9090. }
  9091. return this.parent.isDescendantOf(ancestor);
  9092. }
  9093. return false;
  9094. };
  9095. /**
  9096. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9097. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9098. * @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.
  9099. * @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.
  9100. */
  9101. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9102. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9103. if (!this._children) {
  9104. return;
  9105. }
  9106. for (var index = 0; index < this._children.length; index++) {
  9107. var item = this._children[index];
  9108. if (!predicate || predicate(item)) {
  9109. results.push(item);
  9110. }
  9111. if (!directDescendantsOnly) {
  9112. item._getDescendants(results, false, predicate);
  9113. }
  9114. }
  9115. };
  9116. /**
  9117. * Will return all nodes that have this node as ascendant.
  9118. * @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.
  9119. * @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.
  9120. * @return {BABYLON.Node[]} all children nodes of all types.
  9121. */
  9122. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9123. var results = [];
  9124. this._getDescendants(results, directDescendantsOnly, predicate);
  9125. return results;
  9126. };
  9127. /**
  9128. * @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.
  9129. * @Deprecated, legacy support.
  9130. * use getDecendants instead.
  9131. */
  9132. Node.prototype.getChildren = function (predicate) {
  9133. return this.getDescendants(true, predicate);
  9134. };
  9135. /**
  9136. * Get all child-meshes of this node.
  9137. */
  9138. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9139. var results = [];
  9140. this._getDescendants(results, directDecendantsOnly, function (node) {
  9141. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9142. });
  9143. return results;
  9144. };
  9145. Node.prototype._setReady = function (state) {
  9146. if (state === this._isReady) {
  9147. return;
  9148. }
  9149. if (!state) {
  9150. this._isReady = false;
  9151. return;
  9152. }
  9153. this._isReady = true;
  9154. if (this.onReady) {
  9155. this.onReady(this);
  9156. }
  9157. };
  9158. Node.prototype.getAnimationByName = function (name) {
  9159. for (var i = 0; i < this.animations.length; i++) {
  9160. var animation = this.animations[i];
  9161. if (animation.name === name) {
  9162. return animation;
  9163. }
  9164. }
  9165. return null;
  9166. };
  9167. Node.prototype.createAnimationRange = function (name, from, to) {
  9168. // check name not already in use
  9169. if (!this._ranges[name]) {
  9170. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9171. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9172. if (this.animations[i]) {
  9173. this.animations[i].createRange(name, from, to);
  9174. }
  9175. }
  9176. }
  9177. };
  9178. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9179. if (deleteFrames === void 0) { deleteFrames = true; }
  9180. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9181. if (this.animations[i]) {
  9182. this.animations[i].deleteRange(name, deleteFrames);
  9183. }
  9184. }
  9185. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9186. };
  9187. Node.prototype.getAnimationRange = function (name) {
  9188. return this._ranges[name];
  9189. };
  9190. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9191. var range = this.getAnimationRange(name);
  9192. if (!range) {
  9193. return null;
  9194. }
  9195. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9196. };
  9197. Node.prototype.serializeAnimationRanges = function () {
  9198. var serializationRanges = [];
  9199. for (var name in this._ranges) {
  9200. var range = {};
  9201. range.name = name;
  9202. range.from = this._ranges[name].from;
  9203. range.to = this._ranges[name].to;
  9204. serializationRanges.push(range);
  9205. }
  9206. return serializationRanges;
  9207. };
  9208. Node.prototype.dispose = function () {
  9209. this.parent = null;
  9210. };
  9211. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9212. if (parsedNode.ranges) {
  9213. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9214. var data = parsedNode.ranges[index];
  9215. node.createAnimationRange(data.name, data.from, data.to);
  9216. }
  9217. }
  9218. };
  9219. __decorate([
  9220. BABYLON.serialize()
  9221. ], Node.prototype, "name", void 0);
  9222. __decorate([
  9223. BABYLON.serialize()
  9224. ], Node.prototype, "id", void 0);
  9225. __decorate([
  9226. BABYLON.serialize()
  9227. ], Node.prototype, "uniqueId", void 0);
  9228. __decorate([
  9229. BABYLON.serialize()
  9230. ], Node.prototype, "state", void 0);
  9231. return Node;
  9232. }());
  9233. BABYLON.Node = Node;
  9234. })(BABYLON || (BABYLON = {}));
  9235. var BABYLON;
  9236. (function (BABYLON) {
  9237. var FilesInput = (function () {
  9238. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9239. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9240. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9241. this._engine = p_engine;
  9242. this._canvas = p_canvas;
  9243. this._currentScene = p_scene;
  9244. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9245. this._progressCallback = p_progressCallback;
  9246. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9247. this._textureLoadingCallback = p_textureLoadingCallback;
  9248. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9249. }
  9250. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9251. var _this = this;
  9252. if (p_elementToMonitor) {
  9253. this._elementToMonitor = p_elementToMonitor;
  9254. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9255. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9256. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9257. }
  9258. };
  9259. FilesInput.prototype.renderFunction = function () {
  9260. if (this._additionnalRenderLoopLogicCallback) {
  9261. this._additionnalRenderLoopLogicCallback();
  9262. }
  9263. if (this._currentScene) {
  9264. if (this._textureLoadingCallback) {
  9265. var remaining = this._currentScene.getWaitingItemsCount();
  9266. if (remaining > 0) {
  9267. this._textureLoadingCallback(remaining);
  9268. }
  9269. }
  9270. this._currentScene.render();
  9271. }
  9272. };
  9273. FilesInput.prototype.drag = function (e) {
  9274. e.stopPropagation();
  9275. e.preventDefault();
  9276. };
  9277. FilesInput.prototype.drop = function (eventDrop) {
  9278. eventDrop.stopPropagation();
  9279. eventDrop.preventDefault();
  9280. this.loadFiles(eventDrop);
  9281. };
  9282. FilesInput.prototype.loadFiles = function (event) {
  9283. if (this._startingProcessingFilesCallback)
  9284. this._startingProcessingFilesCallback();
  9285. // Handling data transfer via drag'n'drop
  9286. if (event && event.dataTransfer && event.dataTransfer.files) {
  9287. this._filesToLoad = event.dataTransfer.files;
  9288. }
  9289. // Handling files from input files
  9290. if (event && event.target && event.target.files) {
  9291. this._filesToLoad = event.target.files;
  9292. }
  9293. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9294. for (var i = 0; i < this._filesToLoad.length; i++) {
  9295. switch (this._filesToLoad[i].type) {
  9296. case "image/jpeg":
  9297. case "image/png":
  9298. case "image/bmp":
  9299. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9300. break;
  9301. case "image/targa":
  9302. case "image/vnd.ms-dds":
  9303. case "audio/wav":
  9304. case "audio/x-wav":
  9305. case "audio/mp3":
  9306. case "audio/mpeg":
  9307. case "audio/mpeg3":
  9308. case "audio/x-mpeg-3":
  9309. case "audio/ogg":
  9310. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9311. break;
  9312. default:
  9313. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9314. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9315. }
  9316. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9317. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9318. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9319. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9320. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9321. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9322. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9323. this._sceneFileToLoad = this._filesToLoad[i];
  9324. }
  9325. break;
  9326. }
  9327. }
  9328. this.reload();
  9329. }
  9330. };
  9331. FilesInput.prototype.reload = function () {
  9332. var _this = this;
  9333. var that = this;
  9334. // If a ".babylon" file has been provided
  9335. if (this._sceneFileToLoad) {
  9336. if (this._currentScene) {
  9337. if (BABYLON.Tools.errorsCount > 0) {
  9338. BABYLON.Tools.ClearLogCache();
  9339. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9340. }
  9341. this._engine.stopRenderLoop();
  9342. this._currentScene.dispose();
  9343. }
  9344. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9345. that._currentScene = newScene;
  9346. // Wait for textures and shaders to be ready
  9347. that._currentScene.executeWhenReady(function () {
  9348. // Attach camera to canvas inputs
  9349. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9350. that._currentScene.createDefaultCameraOrLight();
  9351. }
  9352. that._currentScene.activeCamera.attachControl(that._canvas);
  9353. if (that._sceneLoadedCallback) {
  9354. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9355. }
  9356. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9357. });
  9358. }, function (progress) {
  9359. if (_this._progressCallback) {
  9360. _this._progressCallback(progress);
  9361. }
  9362. });
  9363. }
  9364. else {
  9365. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9366. }
  9367. };
  9368. FilesInput.FilesTextures = new Array();
  9369. FilesInput.FilesToLoad = new Array();
  9370. return FilesInput;
  9371. }());
  9372. BABYLON.FilesInput = FilesInput;
  9373. })(BABYLON || (BABYLON = {}));
  9374. var BABYLON;
  9375. (function (BABYLON) {
  9376. var IntersectionInfo = (function () {
  9377. function IntersectionInfo(bu, bv, distance) {
  9378. this.bu = bu;
  9379. this.bv = bv;
  9380. this.distance = distance;
  9381. this.faceId = 0;
  9382. this.subMeshId = 0;
  9383. }
  9384. return IntersectionInfo;
  9385. }());
  9386. BABYLON.IntersectionInfo = IntersectionInfo;
  9387. var PickingInfo = (function () {
  9388. function PickingInfo() {
  9389. this.hit = false;
  9390. this.distance = 0;
  9391. this.pickedPoint = null;
  9392. this.pickedMesh = null;
  9393. this.bu = 0;
  9394. this.bv = 0;
  9395. this.faceId = -1;
  9396. this.subMeshId = 0;
  9397. this.pickedSprite = null;
  9398. }
  9399. // Methods
  9400. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9401. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9402. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9403. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9404. return null;
  9405. }
  9406. var indices = this.pickedMesh.getIndices();
  9407. var result;
  9408. if (useVerticesNormals) {
  9409. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9410. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9411. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9412. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9413. normal0 = normal0.scale(this.bu);
  9414. normal1 = normal1.scale(this.bv);
  9415. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9416. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9417. }
  9418. else {
  9419. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9420. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9421. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9422. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9423. var p1p2 = vertex1.subtract(vertex2);
  9424. var p3p2 = vertex3.subtract(vertex2);
  9425. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9426. }
  9427. if (useWorldCoordinates) {
  9428. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9429. }
  9430. return BABYLON.Vector3.Normalize(result);
  9431. };
  9432. PickingInfo.prototype.getTextureCoordinates = function () {
  9433. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9434. return null;
  9435. }
  9436. var indices = this.pickedMesh.getIndices();
  9437. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9438. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9439. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9440. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9441. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9442. uv1 = uv1.scale(this.bu);
  9443. uv2 = uv2.scale(this.bv);
  9444. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9445. };
  9446. return PickingInfo;
  9447. }());
  9448. BABYLON.PickingInfo = PickingInfo;
  9449. })(BABYLON || (BABYLON = {}));
  9450. var BABYLON;
  9451. (function (BABYLON) {
  9452. var BoundingSphere = (function () {
  9453. function BoundingSphere(minimum, maximum) {
  9454. this.minimum = minimum;
  9455. this.maximum = maximum;
  9456. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9457. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9458. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9459. this.radius = distance * 0.5;
  9460. this.centerWorld = BABYLON.Vector3.Zero();
  9461. this._update(BABYLON.Matrix.Identity());
  9462. }
  9463. // Methods
  9464. BoundingSphere.prototype._update = function (world) {
  9465. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9466. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9467. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9468. };
  9469. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9470. for (var i = 0; i < 6; i++) {
  9471. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9472. return false;
  9473. }
  9474. return true;
  9475. };
  9476. BoundingSphere.prototype.intersectsPoint = function (point) {
  9477. var x = this.centerWorld.x - point.x;
  9478. var y = this.centerWorld.y - point.y;
  9479. var z = this.centerWorld.z - point.z;
  9480. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9481. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9482. return false;
  9483. return true;
  9484. };
  9485. // Statics
  9486. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9487. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9488. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9489. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9490. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9491. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9492. return false;
  9493. return true;
  9494. };
  9495. return BoundingSphere;
  9496. }());
  9497. BABYLON.BoundingSphere = BoundingSphere;
  9498. })(BABYLON || (BABYLON = {}));
  9499. var BABYLON;
  9500. (function (BABYLON) {
  9501. var BoundingBox = (function () {
  9502. function BoundingBox(minimum, maximum) {
  9503. this.minimum = minimum;
  9504. this.maximum = maximum;
  9505. this.vectors = new Array();
  9506. this.vectorsWorld = new Array();
  9507. // Bounding vectors
  9508. this.vectors.push(this.minimum.clone());
  9509. this.vectors.push(this.maximum.clone());
  9510. this.vectors.push(this.minimum.clone());
  9511. this.vectors[2].x = this.maximum.x;
  9512. this.vectors.push(this.minimum.clone());
  9513. this.vectors[3].y = this.maximum.y;
  9514. this.vectors.push(this.minimum.clone());
  9515. this.vectors[4].z = this.maximum.z;
  9516. this.vectors.push(this.maximum.clone());
  9517. this.vectors[5].z = this.minimum.z;
  9518. this.vectors.push(this.maximum.clone());
  9519. this.vectors[6].x = this.minimum.x;
  9520. this.vectors.push(this.maximum.clone());
  9521. this.vectors[7].y = this.minimum.y;
  9522. // OBB
  9523. this.center = this.maximum.add(this.minimum).scale(0.5);
  9524. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9525. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9526. // World
  9527. for (var index = 0; index < this.vectors.length; index++) {
  9528. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9529. }
  9530. this.minimumWorld = BABYLON.Vector3.Zero();
  9531. this.maximumWorld = BABYLON.Vector3.Zero();
  9532. this._update(BABYLON.Matrix.Identity());
  9533. }
  9534. // Methods
  9535. BoundingBox.prototype.getWorldMatrix = function () {
  9536. return this._worldMatrix;
  9537. };
  9538. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9539. this._worldMatrix.copyFrom(matrix);
  9540. return this;
  9541. };
  9542. BoundingBox.prototype._update = function (world) {
  9543. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9544. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9545. for (var index = 0; index < this.vectors.length; index++) {
  9546. var v = this.vectorsWorld[index];
  9547. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9548. if (v.x < this.minimumWorld.x)
  9549. this.minimumWorld.x = v.x;
  9550. if (v.y < this.minimumWorld.y)
  9551. this.minimumWorld.y = v.y;
  9552. if (v.z < this.minimumWorld.z)
  9553. this.minimumWorld.z = v.z;
  9554. if (v.x > this.maximumWorld.x)
  9555. this.maximumWorld.x = v.x;
  9556. if (v.y > this.maximumWorld.y)
  9557. this.maximumWorld.y = v.y;
  9558. if (v.z > this.maximumWorld.z)
  9559. this.maximumWorld.z = v.z;
  9560. }
  9561. // OBB
  9562. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9563. this.center.scaleInPlace(0.5);
  9564. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9565. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9566. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9567. this._worldMatrix = world;
  9568. };
  9569. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9570. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9571. };
  9572. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9573. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9574. };
  9575. BoundingBox.prototype.intersectsPoint = function (point) {
  9576. var delta = -BABYLON.Epsilon;
  9577. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9578. return false;
  9579. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9580. return false;
  9581. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9582. return false;
  9583. return true;
  9584. };
  9585. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9586. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9587. };
  9588. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9589. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9590. return false;
  9591. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9592. return false;
  9593. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9594. return false;
  9595. return true;
  9596. };
  9597. // Statics
  9598. BoundingBox.Intersects = function (box0, box1) {
  9599. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9600. return false;
  9601. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9602. return false;
  9603. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9604. return false;
  9605. return true;
  9606. };
  9607. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9608. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9609. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9610. return (num <= (sphereRadius * sphereRadius));
  9611. };
  9612. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9613. for (var p = 0; p < 6; p++) {
  9614. for (var i = 0; i < 8; i++) {
  9615. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9616. return false;
  9617. }
  9618. }
  9619. }
  9620. return true;
  9621. };
  9622. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9623. for (var p = 0; p < 6; p++) {
  9624. var inCount = 8;
  9625. for (var i = 0; i < 8; i++) {
  9626. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9627. --inCount;
  9628. }
  9629. else {
  9630. break;
  9631. }
  9632. }
  9633. if (inCount === 0)
  9634. return false;
  9635. }
  9636. return true;
  9637. };
  9638. return BoundingBox;
  9639. }());
  9640. BABYLON.BoundingBox = BoundingBox;
  9641. })(BABYLON || (BABYLON = {}));
  9642. var BABYLON;
  9643. (function (BABYLON) {
  9644. var computeBoxExtents = function (axis, box) {
  9645. var p = BABYLON.Vector3.Dot(box.center, axis);
  9646. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9647. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9648. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9649. var r = r0 + r1 + r2;
  9650. return {
  9651. min: p - r,
  9652. max: p + r
  9653. };
  9654. };
  9655. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9656. var axisOverlap = function (axis, box0, box1) {
  9657. var result0 = computeBoxExtents(axis, box0);
  9658. var result1 = computeBoxExtents(axis, box1);
  9659. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9660. };
  9661. var BoundingInfo = (function () {
  9662. function BoundingInfo(minimum, maximum) {
  9663. this.minimum = minimum;
  9664. this.maximum = maximum;
  9665. this._isLocked = false;
  9666. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9667. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9668. }
  9669. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9670. get: function () {
  9671. return this._isLocked;
  9672. },
  9673. set: function (value) {
  9674. this._isLocked = value;
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. // Methods
  9680. BoundingInfo.prototype.update = function (world) {
  9681. if (this._isLocked) {
  9682. return;
  9683. }
  9684. this.boundingBox._update(world);
  9685. this.boundingSphere._update(world);
  9686. };
  9687. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9688. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9689. return false;
  9690. return this.boundingBox.isInFrustum(frustumPlanes);
  9691. };
  9692. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9693. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9694. };
  9695. BoundingInfo.prototype._checkCollision = function (collider) {
  9696. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9697. };
  9698. BoundingInfo.prototype.intersectsPoint = function (point) {
  9699. if (!this.boundingSphere.centerWorld) {
  9700. return false;
  9701. }
  9702. if (!this.boundingSphere.intersectsPoint(point)) {
  9703. return false;
  9704. }
  9705. if (!this.boundingBox.intersectsPoint(point)) {
  9706. return false;
  9707. }
  9708. return true;
  9709. };
  9710. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9711. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9712. return false;
  9713. }
  9714. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9715. return false;
  9716. }
  9717. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9718. return false;
  9719. }
  9720. if (!precise) {
  9721. return true;
  9722. }
  9723. var box0 = this.boundingBox;
  9724. var box1 = boundingInfo.boundingBox;
  9725. if (!axisOverlap(box0.directions[0], box0, box1))
  9726. return false;
  9727. if (!axisOverlap(box0.directions[1], box0, box1))
  9728. return false;
  9729. if (!axisOverlap(box0.directions[2], box0, box1))
  9730. return false;
  9731. if (!axisOverlap(box1.directions[0], box0, box1))
  9732. return false;
  9733. if (!axisOverlap(box1.directions[1], box0, box1))
  9734. return false;
  9735. if (!axisOverlap(box1.directions[2], box0, box1))
  9736. return false;
  9737. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9738. return false;
  9739. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9740. return false;
  9741. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9742. return false;
  9743. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9744. return false;
  9745. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9746. return false;
  9747. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9748. return false;
  9749. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9750. return false;
  9751. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9752. return false;
  9753. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9754. return false;
  9755. return true;
  9756. };
  9757. return BoundingInfo;
  9758. }());
  9759. BABYLON.BoundingInfo = BoundingInfo;
  9760. })(BABYLON || (BABYLON = {}));
  9761. var BABYLON;
  9762. (function (BABYLON) {
  9763. var Ray = (function () {
  9764. function Ray(origin, direction, length) {
  9765. if (length === void 0) { length = Number.MAX_VALUE; }
  9766. this.origin = origin;
  9767. this.direction = direction;
  9768. this.length = length;
  9769. }
  9770. // Methods
  9771. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9772. var d = 0.0;
  9773. var maxValue = Number.MAX_VALUE;
  9774. var inv;
  9775. var min;
  9776. var max;
  9777. var temp;
  9778. if (Math.abs(this.direction.x) < 0.0000001) {
  9779. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9780. return false;
  9781. }
  9782. }
  9783. else {
  9784. inv = 1.0 / this.direction.x;
  9785. min = (minimum.x - this.origin.x) * inv;
  9786. max = (maximum.x - this.origin.x) * inv;
  9787. if (max === -Infinity) {
  9788. max = Infinity;
  9789. }
  9790. if (min > max) {
  9791. temp = min;
  9792. min = max;
  9793. max = temp;
  9794. }
  9795. d = Math.max(min, d);
  9796. maxValue = Math.min(max, maxValue);
  9797. if (d > maxValue) {
  9798. return false;
  9799. }
  9800. }
  9801. if (Math.abs(this.direction.y) < 0.0000001) {
  9802. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9803. return false;
  9804. }
  9805. }
  9806. else {
  9807. inv = 1.0 / this.direction.y;
  9808. min = (minimum.y - this.origin.y) * inv;
  9809. max = (maximum.y - this.origin.y) * inv;
  9810. if (max === -Infinity) {
  9811. max = Infinity;
  9812. }
  9813. if (min > max) {
  9814. temp = min;
  9815. min = max;
  9816. max = temp;
  9817. }
  9818. d = Math.max(min, d);
  9819. maxValue = Math.min(max, maxValue);
  9820. if (d > maxValue) {
  9821. return false;
  9822. }
  9823. }
  9824. if (Math.abs(this.direction.z) < 0.0000001) {
  9825. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9826. return false;
  9827. }
  9828. }
  9829. else {
  9830. inv = 1.0 / this.direction.z;
  9831. min = (minimum.z - this.origin.z) * inv;
  9832. max = (maximum.z - this.origin.z) * inv;
  9833. if (max === -Infinity) {
  9834. max = Infinity;
  9835. }
  9836. if (min > max) {
  9837. temp = min;
  9838. min = max;
  9839. max = temp;
  9840. }
  9841. d = Math.max(min, d);
  9842. maxValue = Math.min(max, maxValue);
  9843. if (d > maxValue) {
  9844. return false;
  9845. }
  9846. }
  9847. return true;
  9848. };
  9849. Ray.prototype.intersectsBox = function (box) {
  9850. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9851. };
  9852. Ray.prototype.intersectsSphere = function (sphere) {
  9853. var x = sphere.center.x - this.origin.x;
  9854. var y = sphere.center.y - this.origin.y;
  9855. var z = sphere.center.z - this.origin.z;
  9856. var pyth = (x * x) + (y * y) + (z * z);
  9857. var rr = sphere.radius * sphere.radius;
  9858. if (pyth <= rr) {
  9859. return true;
  9860. }
  9861. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9862. if (dot < 0.0) {
  9863. return false;
  9864. }
  9865. var temp = pyth - (dot * dot);
  9866. return temp <= rr;
  9867. };
  9868. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9869. if (!this._edge1) {
  9870. this._edge1 = BABYLON.Vector3.Zero();
  9871. this._edge2 = BABYLON.Vector3.Zero();
  9872. this._pvec = BABYLON.Vector3.Zero();
  9873. this._tvec = BABYLON.Vector3.Zero();
  9874. this._qvec = BABYLON.Vector3.Zero();
  9875. }
  9876. vertex1.subtractToRef(vertex0, this._edge1);
  9877. vertex2.subtractToRef(vertex0, this._edge2);
  9878. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9879. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9880. if (det === 0) {
  9881. return null;
  9882. }
  9883. var invdet = 1 / det;
  9884. this.origin.subtractToRef(vertex0, this._tvec);
  9885. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9886. if (bu < 0 || bu > 1.0) {
  9887. return null;
  9888. }
  9889. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9890. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9891. if (bv < 0 || bu + bv > 1.0) {
  9892. return null;
  9893. }
  9894. //check if the distance is longer than the predefined length.
  9895. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9896. if (distance > this.length) {
  9897. return null;
  9898. }
  9899. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9900. };
  9901. Ray.prototype.intersectsPlane = function (plane) {
  9902. var distance;
  9903. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9904. if (Math.abs(result1) < 9.99999997475243E-07) {
  9905. return null;
  9906. }
  9907. else {
  9908. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9909. distance = (-plane.d - result2) / result1;
  9910. if (distance < 0.0) {
  9911. if (distance < -9.99999997475243E-07) {
  9912. return null;
  9913. }
  9914. else {
  9915. return 0;
  9916. }
  9917. }
  9918. return distance;
  9919. }
  9920. };
  9921. /**
  9922. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9923. * @param sega the first point of the segment to test the intersection against
  9924. * @param segb the second point of the segment to test the intersection against
  9925. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9926. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9927. */
  9928. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9929. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9930. var u = segb.subtract(sega);
  9931. var v = rsegb.subtract(this.origin);
  9932. var w = sega.subtract(this.origin);
  9933. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9934. var b = BABYLON.Vector3.Dot(u, v);
  9935. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9936. var d = BABYLON.Vector3.Dot(u, w);
  9937. var e = BABYLON.Vector3.Dot(v, w);
  9938. var D = a * c - b * b; // always >= 0
  9939. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9940. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9941. // compute the line parameters of the two closest points
  9942. if (D < Ray.smallnum) {
  9943. sN = 0.0; // force using point P0 on segment S1
  9944. sD = 1.0; // to prevent possible division by 0.0 later
  9945. tN = e;
  9946. tD = c;
  9947. }
  9948. else {
  9949. sN = (b * e - c * d);
  9950. tN = (a * e - b * d);
  9951. if (sN < 0.0) {
  9952. sN = 0.0;
  9953. tN = e;
  9954. tD = c;
  9955. }
  9956. else if (sN > sD) {
  9957. sN = sD;
  9958. tN = e + b;
  9959. tD = c;
  9960. }
  9961. }
  9962. if (tN < 0.0) {
  9963. tN = 0.0;
  9964. // recompute sc for this edge
  9965. if (-d < 0.0) {
  9966. sN = 0.0;
  9967. }
  9968. else if (-d > a)
  9969. sN = sD;
  9970. else {
  9971. sN = -d;
  9972. sD = a;
  9973. }
  9974. }
  9975. else if (tN > tD) {
  9976. tN = tD;
  9977. // recompute sc for this edge
  9978. if ((-d + b) < 0.0) {
  9979. sN = 0;
  9980. }
  9981. else if ((-d + b) > a) {
  9982. sN = sD;
  9983. }
  9984. else {
  9985. sN = (-d + b);
  9986. sD = a;
  9987. }
  9988. }
  9989. // finally do the division to get sc and tc
  9990. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9991. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9992. // get the difference of the two closest points
  9993. var qtc = v.multiplyByFloats(tc, tc, tc);
  9994. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9995. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9996. if (isIntersected) {
  9997. return qtc.length();
  9998. }
  9999. return -1;
  10000. };
  10001. // Statics
  10002. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10003. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10004. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10005. var direction = end.subtract(start);
  10006. direction.normalize();
  10007. return new Ray(start, direction);
  10008. };
  10009. /**
  10010. * 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
  10011. * transformed to the given world matrix.
  10012. * @param origin The origin point
  10013. * @param end The end point
  10014. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10015. */
  10016. Ray.CreateNewFromTo = function (origin, end, world) {
  10017. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10018. var direction = end.subtract(origin);
  10019. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10020. direction.normalize();
  10021. return Ray.Transform(new Ray(origin, direction, length), world);
  10022. };
  10023. Ray.Transform = function (ray, matrix) {
  10024. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10025. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10026. newDirection.normalize();
  10027. return new Ray(newOrigin, newDirection, ray.length);
  10028. };
  10029. Ray.smallnum = 0.00000001;
  10030. Ray.rayl = 10e8;
  10031. return Ray;
  10032. }());
  10033. BABYLON.Ray = Ray;
  10034. })(BABYLON || (BABYLON = {}));
  10035. var BABYLON;
  10036. (function (BABYLON) {
  10037. var AbstractMesh = (function (_super) {
  10038. __extends(AbstractMesh, _super);
  10039. // Constructor
  10040. function AbstractMesh(name, scene) {
  10041. var _this = this;
  10042. _super.call(this, name, scene);
  10043. // Events
  10044. /**
  10045. * An event triggered when the mesh is disposed.
  10046. * @type {BABYLON.Observable}
  10047. */
  10048. this.onDisposeObservable = new BABYLON.Observable();
  10049. /**
  10050. * An event triggered when this mesh collides with another one
  10051. * @type {BABYLON.Observable}
  10052. */
  10053. this.onCollideObservable = new BABYLON.Observable();
  10054. /**
  10055. * An event triggered when the collision's position changes
  10056. * @type {BABYLON.Observable}
  10057. */
  10058. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10059. /**
  10060. * An event triggered after the world matrix is updated
  10061. * @type {BABYLON.Observable}
  10062. */
  10063. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10064. // Properties
  10065. this.definedFacingForward = true; // orientation for POV movement & rotation
  10066. this.position = new BABYLON.Vector3(0, 0, 0);
  10067. this._rotation = new BABYLON.Vector3(0, 0, 0);
  10068. this._scaling = new BABYLON.Vector3(1, 1, 1);
  10069. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10070. this.visibility = 1.0;
  10071. this.alphaIndex = Number.MAX_VALUE;
  10072. this.infiniteDistance = false;
  10073. this.isVisible = true;
  10074. this.isPickable = true;
  10075. this.showBoundingBox = false;
  10076. this.showSubMeshesBoundingBox = false;
  10077. this.isBlocker = false;
  10078. this.renderingGroupId = 0;
  10079. this.receiveShadows = false;
  10080. this.renderOutline = false;
  10081. this.outlineColor = BABYLON.Color3.Red();
  10082. this.outlineWidth = 0.02;
  10083. this.renderOverlay = false;
  10084. this.overlayColor = BABYLON.Color3.Red();
  10085. this.overlayAlpha = 0.5;
  10086. this.hasVertexAlpha = false;
  10087. this.useVertexColors = true;
  10088. this.applyFog = true;
  10089. this.computeBonesUsingShaders = true;
  10090. this.scalingDeterminant = 1;
  10091. this.numBoneInfluencers = 4;
  10092. this.useOctreeForRenderingSelection = true;
  10093. this.useOctreeForPicking = true;
  10094. this.useOctreeForCollisions = true;
  10095. this.layerMask = 0x0FFFFFFF;
  10096. this.alwaysSelectAsActiveMesh = false;
  10097. // Collisions
  10098. this._checkCollisions = false;
  10099. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10100. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10101. this._collider = new BABYLON.Collider();
  10102. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10103. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10104. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10105. // Edges
  10106. this.edgesWidth = 1;
  10107. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10108. // Cache
  10109. this._localWorld = BABYLON.Matrix.Zero();
  10110. this._worldMatrix = BABYLON.Matrix.Zero();
  10111. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10112. this._absolutePosition = BABYLON.Vector3.Zero();
  10113. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10114. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10115. this._isDirty = false;
  10116. this._pivotMatrix = BABYLON.Matrix.Identity();
  10117. this._isDisposed = false;
  10118. this._renderId = 0;
  10119. this._intersectionsInProgress = new Array();
  10120. this._isWorldMatrixFrozen = false;
  10121. this._unIndexed = false;
  10122. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10123. if (collidedMesh === void 0) { collidedMesh = null; }
  10124. //TODO move this to the collision coordinator!
  10125. if (_this.getScene().workerCollisions)
  10126. newPosition.multiplyInPlace(_this._collider.radius);
  10127. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10128. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10129. _this.position.addInPlace(_this._diffPositionForCollisions);
  10130. }
  10131. if (collidedMesh) {
  10132. _this.onCollideObservable.notifyObservers(collidedMesh);
  10133. }
  10134. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10135. };
  10136. scene.addMesh(this);
  10137. }
  10138. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10139. get: function () {
  10140. return AbstractMesh._BILLBOARDMODE_NONE;
  10141. },
  10142. enumerable: true,
  10143. configurable: true
  10144. });
  10145. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10146. get: function () {
  10147. return AbstractMesh._BILLBOARDMODE_X;
  10148. },
  10149. enumerable: true,
  10150. configurable: true
  10151. });
  10152. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10153. get: function () {
  10154. return AbstractMesh._BILLBOARDMODE_Y;
  10155. },
  10156. enumerable: true,
  10157. configurable: true
  10158. });
  10159. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10160. get: function () {
  10161. return AbstractMesh._BILLBOARDMODE_Z;
  10162. },
  10163. enumerable: true,
  10164. configurable: true
  10165. });
  10166. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10167. get: function () {
  10168. return AbstractMesh._BILLBOARDMODE_ALL;
  10169. },
  10170. enumerable: true,
  10171. configurable: true
  10172. });
  10173. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  10174. set: function (callback) {
  10175. if (this._onDisposeObserver) {
  10176. this.onDisposeObservable.remove(this._onDisposeObserver);
  10177. }
  10178. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10179. },
  10180. enumerable: true,
  10181. configurable: true
  10182. });
  10183. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10184. set: function (callback) {
  10185. if (this._onCollideObserver) {
  10186. this.onCollideObservable.remove(this._onCollideObserver);
  10187. }
  10188. this._onCollideObserver = this.onCollideObservable.add(callback);
  10189. },
  10190. enumerable: true,
  10191. configurable: true
  10192. });
  10193. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10194. set: function (callback) {
  10195. if (this._onCollisionPositionChangeObserver) {
  10196. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10197. }
  10198. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10199. },
  10200. enumerable: true,
  10201. configurable: true
  10202. });
  10203. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10204. get: function () {
  10205. return this._skeleton;
  10206. },
  10207. set: function (value) {
  10208. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10209. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10210. }
  10211. if (value && value.needInitialSkinMatrix) {
  10212. value._registerMeshWithPoseMatrix(this);
  10213. }
  10214. this._skeleton = value;
  10215. if (!this._skeleton) {
  10216. this._bonesTransformMatrices = null;
  10217. }
  10218. },
  10219. enumerable: true,
  10220. configurable: true
  10221. });
  10222. /**
  10223. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10224. */
  10225. AbstractMesh.prototype.toString = function (fullDetails) {
  10226. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10227. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10228. if (this._skeleton) {
  10229. ret += ", skeleton: " + this._skeleton.name;
  10230. }
  10231. if (fullDetails) {
  10232. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10233. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10234. }
  10235. return ret;
  10236. };
  10237. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10238. /**
  10239. * Getting the rotation object.
  10240. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10241. */
  10242. get: function () {
  10243. return this._rotation;
  10244. },
  10245. set: function (newRotation) {
  10246. this._rotation = newRotation;
  10247. },
  10248. enumerable: true,
  10249. configurable: true
  10250. });
  10251. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10252. get: function () {
  10253. return this._scaling;
  10254. },
  10255. set: function (newScaling) {
  10256. this._scaling = newScaling;
  10257. if (this.physicsImpostor) {
  10258. this.physicsImpostor.forceUpdate();
  10259. }
  10260. },
  10261. enumerable: true,
  10262. configurable: true
  10263. });
  10264. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10265. get: function () {
  10266. return this._rotationQuaternion;
  10267. },
  10268. set: function (quaternion) {
  10269. this._rotationQuaternion = quaternion;
  10270. //reset the rotation vector.
  10271. if (quaternion && this.rotation.length()) {
  10272. this.rotation.copyFromFloats(0, 0, 0);
  10273. }
  10274. },
  10275. enumerable: true,
  10276. configurable: true
  10277. });
  10278. // Methods
  10279. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10280. this._poseMatrix.copyFrom(matrix);
  10281. };
  10282. AbstractMesh.prototype.getPoseMatrix = function () {
  10283. return this._poseMatrix;
  10284. };
  10285. AbstractMesh.prototype.disableEdgesRendering = function () {
  10286. if (this._edgesRenderer !== undefined) {
  10287. this._edgesRenderer.dispose();
  10288. this._edgesRenderer = undefined;
  10289. }
  10290. };
  10291. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10292. if (epsilon === void 0) { epsilon = 0.95; }
  10293. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10294. this.disableEdgesRendering();
  10295. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10296. };
  10297. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10298. get: function () {
  10299. return false;
  10300. },
  10301. enumerable: true,
  10302. configurable: true
  10303. });
  10304. AbstractMesh.prototype.getLOD = function (camera) {
  10305. return this;
  10306. };
  10307. AbstractMesh.prototype.getTotalVertices = function () {
  10308. return 0;
  10309. };
  10310. AbstractMesh.prototype.getIndices = function () {
  10311. return null;
  10312. };
  10313. AbstractMesh.prototype.getVerticesData = function (kind) {
  10314. return null;
  10315. };
  10316. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10317. return false;
  10318. };
  10319. AbstractMesh.prototype.getBoundingInfo = function () {
  10320. if (this._masterMesh) {
  10321. return this._masterMesh.getBoundingInfo();
  10322. }
  10323. if (!this._boundingInfo) {
  10324. this._updateBoundingInfo();
  10325. }
  10326. return this._boundingInfo;
  10327. };
  10328. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10329. this._boundingInfo = boundingInfo;
  10330. };
  10331. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10332. get: function () {
  10333. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10334. },
  10335. enumerable: true,
  10336. configurable: true
  10337. });
  10338. AbstractMesh.prototype._preActivate = function () {
  10339. };
  10340. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10341. };
  10342. AbstractMesh.prototype._activate = function (renderId) {
  10343. this._renderId = renderId;
  10344. };
  10345. AbstractMesh.prototype.getWorldMatrix = function () {
  10346. if (this._masterMesh) {
  10347. return this._masterMesh.getWorldMatrix();
  10348. }
  10349. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10350. this.computeWorldMatrix();
  10351. }
  10352. return this._worldMatrix;
  10353. };
  10354. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10355. get: function () {
  10356. return this._worldMatrix;
  10357. },
  10358. enumerable: true,
  10359. configurable: true
  10360. });
  10361. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10362. get: function () {
  10363. return this._absolutePosition;
  10364. },
  10365. enumerable: true,
  10366. configurable: true
  10367. });
  10368. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10369. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10370. this.computeWorldMatrix(true);
  10371. this._isWorldMatrixFrozen = true;
  10372. };
  10373. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10374. this._isWorldMatrixFrozen = false;
  10375. this.computeWorldMatrix(true);
  10376. };
  10377. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10378. get: function () {
  10379. return this._isWorldMatrixFrozen;
  10380. },
  10381. enumerable: true,
  10382. configurable: true
  10383. });
  10384. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10385. axis.normalize();
  10386. if (!this.rotationQuaternion) {
  10387. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10388. this.rotation = BABYLON.Vector3.Zero();
  10389. }
  10390. var rotationQuaternion;
  10391. if (!space || space === BABYLON.Space.LOCAL) {
  10392. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10393. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10394. }
  10395. else {
  10396. if (this.parent) {
  10397. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10398. invertParentWorldMatrix.invert();
  10399. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10400. }
  10401. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10402. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10403. }
  10404. };
  10405. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10406. var displacementVector = axis.scale(distance);
  10407. if (!space || space === BABYLON.Space.LOCAL) {
  10408. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10409. this.setPositionWithLocalVector(tempV3);
  10410. }
  10411. else {
  10412. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10413. }
  10414. };
  10415. AbstractMesh.prototype.getAbsolutePosition = function () {
  10416. this.computeWorldMatrix();
  10417. return this._absolutePosition;
  10418. };
  10419. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10420. if (!absolutePosition) {
  10421. return;
  10422. }
  10423. var absolutePositionX;
  10424. var absolutePositionY;
  10425. var absolutePositionZ;
  10426. if (absolutePosition.x === undefined) {
  10427. if (arguments.length < 3) {
  10428. return;
  10429. }
  10430. absolutePositionX = arguments[0];
  10431. absolutePositionY = arguments[1];
  10432. absolutePositionZ = arguments[2];
  10433. }
  10434. else {
  10435. absolutePositionX = absolutePosition.x;
  10436. absolutePositionY = absolutePosition.y;
  10437. absolutePositionZ = absolutePosition.z;
  10438. }
  10439. if (this.parent) {
  10440. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10441. invertParentWorldMatrix.invert();
  10442. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10443. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10444. }
  10445. else {
  10446. this.position.x = absolutePositionX;
  10447. this.position.y = absolutePositionY;
  10448. this.position.z = absolutePositionZ;
  10449. }
  10450. };
  10451. // ================================== Point of View Movement =================================
  10452. /**
  10453. * Perform relative position change from the point of view of behind the front of the mesh.
  10454. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10455. * Supports definition of mesh facing forward or backward.
  10456. * @param {number} amountRight
  10457. * @param {number} amountUp
  10458. * @param {number} amountForward
  10459. */
  10460. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10461. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10462. };
  10463. /**
  10464. * Calculate relative position change from the point of view of behind the front of the mesh.
  10465. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10466. * Supports definition of mesh facing forward or backward.
  10467. * @param {number} amountRight
  10468. * @param {number} amountUp
  10469. * @param {number} amountForward
  10470. */
  10471. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10472. var rotMatrix = new BABYLON.Matrix();
  10473. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10474. rotQuaternion.toRotationMatrix(rotMatrix);
  10475. var translationDelta = BABYLON.Vector3.Zero();
  10476. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10477. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10478. return translationDelta;
  10479. };
  10480. // ================================== Point of View Rotation =================================
  10481. /**
  10482. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10483. * Supports definition of mesh facing forward or backward.
  10484. * @param {number} flipBack
  10485. * @param {number} twirlClockwise
  10486. * @param {number} tiltRight
  10487. */
  10488. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10489. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10490. };
  10491. /**
  10492. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10493. * Supports definition of mesh facing forward or backward.
  10494. * @param {number} flipBack
  10495. * @param {number} twirlClockwise
  10496. * @param {number} tiltRight
  10497. */
  10498. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10499. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10500. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10501. };
  10502. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10503. this._pivotMatrix = matrix;
  10504. this._cache.pivotMatrixUpdated = true;
  10505. };
  10506. AbstractMesh.prototype.getPivotMatrix = function () {
  10507. return this._pivotMatrix;
  10508. };
  10509. AbstractMesh.prototype._isSynchronized = function () {
  10510. if (this._isDirty) {
  10511. return false;
  10512. }
  10513. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10514. return false;
  10515. if (this._cache.pivotMatrixUpdated) {
  10516. return false;
  10517. }
  10518. if (this.infiniteDistance) {
  10519. return false;
  10520. }
  10521. if (!this._cache.position.equals(this.position))
  10522. return false;
  10523. if (this.rotationQuaternion) {
  10524. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10525. return false;
  10526. }
  10527. if (!this._cache.rotation.equals(this.rotation))
  10528. return false;
  10529. if (!this._cache.scaling.equals(this.scaling))
  10530. return false;
  10531. return true;
  10532. };
  10533. AbstractMesh.prototype._initCache = function () {
  10534. _super.prototype._initCache.call(this);
  10535. this._cache.localMatrixUpdated = false;
  10536. this._cache.position = BABYLON.Vector3.Zero();
  10537. this._cache.scaling = BABYLON.Vector3.Zero();
  10538. this._cache.rotation = BABYLON.Vector3.Zero();
  10539. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10540. this._cache.billboardMode = -1;
  10541. };
  10542. AbstractMesh.prototype.markAsDirty = function (property) {
  10543. if (property === "rotation") {
  10544. this.rotationQuaternion = null;
  10545. }
  10546. this._currentRenderId = Number.MAX_VALUE;
  10547. this._isDirty = true;
  10548. };
  10549. AbstractMesh.prototype._updateBoundingInfo = function () {
  10550. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10551. this._boundingInfo.update(this.worldMatrixFromCache);
  10552. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10553. };
  10554. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10555. if (!this.subMeshes) {
  10556. return;
  10557. }
  10558. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10559. var subMesh = this.subMeshes[subIndex];
  10560. if (!subMesh.IsGlobal) {
  10561. subMesh.updateBoundingInfo(matrix);
  10562. }
  10563. }
  10564. };
  10565. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10566. if (this._isWorldMatrixFrozen) {
  10567. return this._worldMatrix;
  10568. }
  10569. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10570. this._currentRenderId = this.getScene().getRenderId();
  10571. return this._worldMatrix;
  10572. }
  10573. this._cache.position.copyFrom(this.position);
  10574. this._cache.scaling.copyFrom(this.scaling);
  10575. this._cache.pivotMatrixUpdated = false;
  10576. this._cache.billboardMode = this.billboardMode;
  10577. this._currentRenderId = this.getScene().getRenderId();
  10578. this._isDirty = false;
  10579. // Scaling
  10580. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10581. // Rotation
  10582. //rotate, if quaternion is set and rotation was used
  10583. if (this.rotationQuaternion) {
  10584. var len = this.rotation.length();
  10585. if (len) {
  10586. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10587. this.rotation.copyFromFloats(0, 0, 0);
  10588. }
  10589. }
  10590. if (this.rotationQuaternion) {
  10591. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10592. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10593. }
  10594. else {
  10595. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10596. this._cache.rotation.copyFrom(this.rotation);
  10597. }
  10598. // Translation
  10599. if (this.infiniteDistance && !this.parent) {
  10600. var camera = this.getScene().activeCamera;
  10601. if (camera) {
  10602. var cameraWorldMatrix = camera.getWorldMatrix();
  10603. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10604. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10605. }
  10606. }
  10607. else {
  10608. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10609. }
  10610. // Composing transformations
  10611. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10612. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10613. // Billboarding
  10614. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10615. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10616. var localPosition = BABYLON.Tmp.Vector3[0];
  10617. if (this.parent && this.parent.getWorldMatrix) {
  10618. this._markSyncedWithParent();
  10619. var parentMatrix;
  10620. if (this._meshToBoneReferal) {
  10621. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10622. parentMatrix = BABYLON.Tmp.Matrix[6];
  10623. }
  10624. else {
  10625. parentMatrix = this.parent.getWorldMatrix();
  10626. }
  10627. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10628. localPosition = BABYLON.Tmp.Vector3[1];
  10629. }
  10630. var zero = this.getScene().activeCamera.globalPosition.clone();
  10631. if (this.parent && this.parent.position) {
  10632. localPosition.addInPlace(this.parent.position);
  10633. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10634. }
  10635. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10636. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10637. zero.x = localPosition.x + BABYLON.Epsilon;
  10638. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10639. zero.y = localPosition.y + BABYLON.Epsilon;
  10640. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10641. zero.z = localPosition.z + BABYLON.Epsilon;
  10642. }
  10643. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10644. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10645. BABYLON.Tmp.Matrix[3].invert();
  10646. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10647. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10648. }
  10649. // Local world
  10650. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10651. // Parent
  10652. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10653. this._markSyncedWithParent();
  10654. if (this._meshToBoneReferal) {
  10655. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10656. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10657. }
  10658. else {
  10659. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10660. }
  10661. }
  10662. else {
  10663. this._worldMatrix.copyFrom(this._localWorld);
  10664. }
  10665. // Bounding info
  10666. this._updateBoundingInfo();
  10667. // Absolute position
  10668. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10669. // Callbacks
  10670. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10671. if (!this._poseMatrix) {
  10672. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10673. }
  10674. return this._worldMatrix;
  10675. };
  10676. /**
  10677. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10678. * @param func: callback function to add
  10679. */
  10680. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10681. this.onAfterWorldMatrixUpdateObservable.add(func);
  10682. };
  10683. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10684. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10685. };
  10686. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10687. this.computeWorldMatrix();
  10688. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10689. };
  10690. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10691. this.computeWorldMatrix();
  10692. var invLocalWorldMatrix = this._localWorld.clone();
  10693. invLocalWorldMatrix.invert();
  10694. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10695. };
  10696. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10697. this.computeWorldMatrix(true);
  10698. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10699. };
  10700. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10701. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10702. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10703. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10704. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10705. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10706. /// <returns>Mesh oriented towards targetMesh</returns>
  10707. if (yawCor === void 0) { yawCor = 0; }
  10708. if (pitchCor === void 0) { pitchCor = 0; }
  10709. if (rollCor === void 0) { rollCor = 0; }
  10710. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10711. var dv = AbstractMesh._lookAtVectorCache;
  10712. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10713. targetPoint.subtractToRef(pos, dv);
  10714. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10715. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10716. var pitch = Math.atan2(dv.y, len);
  10717. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10718. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10719. };
  10720. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10721. this._meshToBoneReferal = affectedMesh;
  10722. this.parent = bone;
  10723. if (bone.getWorldMatrix().determinant() < 0) {
  10724. this.scalingDeterminant *= -1;
  10725. }
  10726. };
  10727. AbstractMesh.prototype.detachFromBone = function () {
  10728. if (this.parent.getWorldMatrix().determinant() < 0) {
  10729. this.scalingDeterminant *= -1;
  10730. }
  10731. this._meshToBoneReferal = null;
  10732. this.parent = null;
  10733. };
  10734. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10735. return this._boundingInfo.isInFrustum(frustumPlanes);
  10736. };
  10737. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10738. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10739. ;
  10740. };
  10741. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10742. if (!this._boundingInfo || !mesh._boundingInfo) {
  10743. return false;
  10744. }
  10745. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10746. };
  10747. AbstractMesh.prototype.intersectsPoint = function (point) {
  10748. if (!this._boundingInfo) {
  10749. return false;
  10750. }
  10751. return this._boundingInfo.intersectsPoint(point);
  10752. };
  10753. // Physics
  10754. /**
  10755. * @Deprecated. Use new PhysicsImpostor instead.
  10756. * */
  10757. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10758. //legacy support
  10759. if (impostor.impostor) {
  10760. options = impostor;
  10761. impostor = impostor.impostor;
  10762. }
  10763. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10764. return this.physicsImpostor.physicsBody;
  10765. };
  10766. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10767. return this.physicsImpostor;
  10768. };
  10769. /**
  10770. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10771. */
  10772. AbstractMesh.prototype.getPhysicsMass = function () {
  10773. return this.physicsImpostor.getParam("mass");
  10774. };
  10775. /**
  10776. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10777. */
  10778. AbstractMesh.prototype.getPhysicsFriction = function () {
  10779. return this.physicsImpostor.getParam("friction");
  10780. };
  10781. /**
  10782. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10783. */
  10784. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10785. return this.physicsImpostor.getParam("restitution");
  10786. };
  10787. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10788. if (!camera) {
  10789. camera = this.getScene().activeCamera;
  10790. }
  10791. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10792. };
  10793. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10794. if (!camera) {
  10795. camera = this.getScene().activeCamera;
  10796. }
  10797. return this.absolutePosition.subtract(camera.position).length();
  10798. };
  10799. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10800. if (!this.physicsImpostor) {
  10801. return;
  10802. }
  10803. this.physicsImpostor.applyImpulse(force, contactPoint);
  10804. };
  10805. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10806. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10807. return;
  10808. }
  10809. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10810. mainPivot: pivot1,
  10811. connectedPivot: pivot2,
  10812. nativeParams: options
  10813. });
  10814. };
  10815. /**
  10816. * @Deprecated
  10817. */
  10818. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10819. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10820. this.updatePhysicsBody();
  10821. };
  10822. /**
  10823. * @Deprecated
  10824. * Calling this function is not needed anymore.
  10825. * The physics engine takes care of transofmration automatically.
  10826. */
  10827. AbstractMesh.prototype.updatePhysicsBody = function () {
  10828. //Unneeded
  10829. };
  10830. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10831. // Collisions
  10832. get: function () {
  10833. return this._checkCollisions;
  10834. },
  10835. set: function (collisionEnabled) {
  10836. this._checkCollisions = collisionEnabled;
  10837. if (this.getScene().workerCollisions) {
  10838. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10839. }
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10845. var globalPosition = this.getAbsolutePosition();
  10846. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10847. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10848. this._collider.radius = this.ellipsoid;
  10849. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10850. };
  10851. // Submeshes octree
  10852. /**
  10853. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10854. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10855. */
  10856. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10857. if (maxCapacity === void 0) { maxCapacity = 64; }
  10858. if (maxDepth === void 0) { maxDepth = 2; }
  10859. if (!this._submeshesOctree) {
  10860. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10861. }
  10862. this.computeWorldMatrix(true);
  10863. // Update octree
  10864. var bbox = this.getBoundingInfo().boundingBox;
  10865. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10866. return this._submeshesOctree;
  10867. };
  10868. // Collisions
  10869. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10870. this._generatePointsArray();
  10871. // Transformation
  10872. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10873. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10874. subMesh._lastColliderWorldVertices = [];
  10875. subMesh._trianglePlanes = [];
  10876. var start = subMesh.verticesStart;
  10877. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10878. for (var i = start; i < end; i++) {
  10879. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10880. }
  10881. }
  10882. // Collide
  10883. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10884. if (collider.collisionFound) {
  10885. collider.collidedMesh = this;
  10886. }
  10887. };
  10888. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10889. var subMeshes;
  10890. var len;
  10891. // Octrees
  10892. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10893. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10894. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10895. len = intersections.length;
  10896. subMeshes = intersections.data;
  10897. }
  10898. else {
  10899. subMeshes = this.subMeshes;
  10900. len = subMeshes.length;
  10901. }
  10902. for (var index = 0; index < len; index++) {
  10903. var subMesh = subMeshes[index];
  10904. // Bounding test
  10905. if (len > 1 && !subMesh._checkCollision(collider))
  10906. continue;
  10907. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10908. }
  10909. };
  10910. AbstractMesh.prototype._checkCollision = function (collider) {
  10911. // Bounding box test
  10912. if (!this._boundingInfo._checkCollision(collider))
  10913. return;
  10914. // Transformation matrix
  10915. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10916. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10917. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10918. };
  10919. // Picking
  10920. AbstractMesh.prototype._generatePointsArray = function () {
  10921. return false;
  10922. };
  10923. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10924. var pickingInfo = new BABYLON.PickingInfo();
  10925. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10926. return pickingInfo;
  10927. }
  10928. if (!this._generatePointsArray()) {
  10929. return pickingInfo;
  10930. }
  10931. var intersectInfo = null;
  10932. // Octrees
  10933. var subMeshes;
  10934. var len;
  10935. if (this._submeshesOctree && this.useOctreeForPicking) {
  10936. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10937. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10938. len = intersections.length;
  10939. subMeshes = intersections.data;
  10940. }
  10941. else {
  10942. subMeshes = this.subMeshes;
  10943. len = subMeshes.length;
  10944. }
  10945. for (var index = 0; index < len; index++) {
  10946. var subMesh = subMeshes[index];
  10947. // Bounding test
  10948. if (len > 1 && !subMesh.canIntersects(ray))
  10949. continue;
  10950. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10951. if (currentIntersectInfo) {
  10952. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10953. intersectInfo = currentIntersectInfo;
  10954. intersectInfo.subMeshId = index;
  10955. if (fastCheck) {
  10956. break;
  10957. }
  10958. }
  10959. }
  10960. }
  10961. if (intersectInfo) {
  10962. // Get picked point
  10963. var world = this.getWorldMatrix();
  10964. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10965. var direction = ray.direction.clone();
  10966. direction = direction.scale(intersectInfo.distance);
  10967. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10968. var pickedPoint = worldOrigin.add(worldDirection);
  10969. // Return result
  10970. pickingInfo.hit = true;
  10971. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10972. pickingInfo.pickedPoint = pickedPoint;
  10973. pickingInfo.pickedMesh = this;
  10974. pickingInfo.bu = intersectInfo.bu;
  10975. pickingInfo.bv = intersectInfo.bv;
  10976. pickingInfo.faceId = intersectInfo.faceId;
  10977. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10978. return pickingInfo;
  10979. }
  10980. return pickingInfo;
  10981. };
  10982. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10983. return null;
  10984. };
  10985. AbstractMesh.prototype.releaseSubMeshes = function () {
  10986. if (this.subMeshes) {
  10987. while (this.subMeshes.length) {
  10988. this.subMeshes[0].dispose();
  10989. }
  10990. }
  10991. else {
  10992. this.subMeshes = new Array();
  10993. }
  10994. };
  10995. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10996. var _this = this;
  10997. var index;
  10998. // Action manager
  10999. if (this.actionManager) {
  11000. this.actionManager.dispose();
  11001. this.actionManager = null;
  11002. }
  11003. // Skeleton
  11004. this.skeleton = null;
  11005. // Animations
  11006. this.getScene().stopAnimation(this);
  11007. // Physics
  11008. if (this.physicsImpostor) {
  11009. this.physicsImpostor.dispose();
  11010. }
  11011. // Intersections in progress
  11012. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11013. var other = this._intersectionsInProgress[index];
  11014. var pos = other._intersectionsInProgress.indexOf(this);
  11015. other._intersectionsInProgress.splice(pos, 1);
  11016. }
  11017. this._intersectionsInProgress = [];
  11018. // Lights
  11019. var lights = this.getScene().lights;
  11020. lights.forEach(function (light) {
  11021. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11022. if (meshIndex !== -1) {
  11023. light.includedOnlyMeshes.splice(meshIndex, 1);
  11024. }
  11025. meshIndex = light.excludedMeshes.indexOf(_this);
  11026. if (meshIndex !== -1) {
  11027. light.excludedMeshes.splice(meshIndex, 1);
  11028. }
  11029. // Shadow generators
  11030. var generator = light.getShadowGenerator();
  11031. if (generator) {
  11032. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11033. if (meshIndex !== -1) {
  11034. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11035. }
  11036. }
  11037. });
  11038. // Edges
  11039. if (this._edgesRenderer) {
  11040. this._edgesRenderer.dispose();
  11041. this._edgesRenderer = null;
  11042. }
  11043. // SubMeshes
  11044. this.releaseSubMeshes();
  11045. // Engine
  11046. this.getScene().getEngine().unbindAllAttributes();
  11047. // Remove from scene
  11048. this.getScene().removeMesh(this);
  11049. if (!doNotRecurse) {
  11050. // Particles
  11051. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11052. if (this.getScene().particleSystems[index].emitter === this) {
  11053. this.getScene().particleSystems[index].dispose();
  11054. index--;
  11055. }
  11056. }
  11057. // Children
  11058. var objects = this.getDescendants(true);
  11059. for (index = 0; index < objects.length; index++) {
  11060. objects[index].dispose();
  11061. }
  11062. }
  11063. else {
  11064. var childMeshes = this.getChildMeshes(true);
  11065. for (index = 0; index < childMeshes.length; index++) {
  11066. var child = childMeshes[index];
  11067. child.parent = null;
  11068. child.computeWorldMatrix(true);
  11069. }
  11070. }
  11071. _super.prototype.dispose.call(this);
  11072. this.onAfterWorldMatrixUpdateObservable.clear();
  11073. this.onCollideObservable.clear();
  11074. this.onCollisionPositionChangeObservable.clear();
  11075. this._isDisposed = true;
  11076. // Callback
  11077. this.onDisposeObservable.notifyObservers(this);
  11078. this.onDisposeObservable.clear();
  11079. };
  11080. // Statics
  11081. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11082. AbstractMesh._BILLBOARDMODE_X = 1;
  11083. AbstractMesh._BILLBOARDMODE_Y = 2;
  11084. AbstractMesh._BILLBOARDMODE_Z = 4;
  11085. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11086. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11087. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11088. return AbstractMesh;
  11089. }(BABYLON.Node));
  11090. BABYLON.AbstractMesh = AbstractMesh;
  11091. })(BABYLON || (BABYLON = {}));
  11092. var BABYLON;
  11093. (function (BABYLON) {
  11094. var Light = (function (_super) {
  11095. __extends(Light, _super);
  11096. function Light(name, scene) {
  11097. _super.call(this, name, scene);
  11098. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11099. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11100. this.intensity = 1.0;
  11101. this.range = Number.MAX_VALUE;
  11102. this.includeOnlyWithLayerMask = 0;
  11103. this.includedOnlyMeshes = new Array();
  11104. this.excludedMeshes = new Array();
  11105. this.excludeWithLayerMask = 0;
  11106. this.lightmapMode = 0;
  11107. // PBR Properties.
  11108. this.radius = 0.00001;
  11109. this._excludedMeshesIds = new Array();
  11110. this._includedOnlyMeshesIds = new Array();
  11111. scene.addLight(this);
  11112. }
  11113. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11114. /**
  11115. * If every light affecting the material is in this lightmapMode,
  11116. * material.lightmapTexture adds or multiplies
  11117. * (depends on material.useLightmapAsShadowmap)
  11118. * after every other light calculations.
  11119. */
  11120. get: function () {
  11121. return Light._LIGHTMAP_DEFAULT;
  11122. },
  11123. enumerable: true,
  11124. configurable: true
  11125. });
  11126. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11127. /**
  11128. * material.lightmapTexture as only diffuse lighting from this light
  11129. * adds pnly specular lighting from this light
  11130. * adds dynamic shadows
  11131. */
  11132. get: function () {
  11133. return Light._LIGHTMAP_SPECULAR;
  11134. },
  11135. enumerable: true,
  11136. configurable: true
  11137. });
  11138. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11139. /**
  11140. * material.lightmapTexture as only lighting
  11141. * no light calculation from this light
  11142. * only adds dynamic shadows from this light
  11143. */
  11144. get: function () {
  11145. return Light._LIGHTMAP_SHADOWSONLY;
  11146. },
  11147. enumerable: true,
  11148. configurable: true
  11149. });
  11150. /**
  11151. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11152. */
  11153. Light.prototype.toString = function (fullDetails) {
  11154. var ret = "Name: " + this.name;
  11155. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11156. if (this.animations) {
  11157. for (var i = 0; i < this.animations.length; i++) {
  11158. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11159. }
  11160. }
  11161. if (fullDetails) {
  11162. }
  11163. return ret;
  11164. };
  11165. Light.prototype.getShadowGenerator = function () {
  11166. return this._shadowGenerator;
  11167. };
  11168. Light.prototype.getAbsolutePosition = function () {
  11169. return BABYLON.Vector3.Zero();
  11170. };
  11171. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11172. };
  11173. Light.prototype._getWorldMatrix = function () {
  11174. return BABYLON.Matrix.Identity();
  11175. };
  11176. Light.prototype.canAffectMesh = function (mesh) {
  11177. if (!mesh) {
  11178. return true;
  11179. }
  11180. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11181. return false;
  11182. }
  11183. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11184. return false;
  11185. }
  11186. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11187. return false;
  11188. }
  11189. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11190. return false;
  11191. }
  11192. return true;
  11193. };
  11194. Light.prototype.getWorldMatrix = function () {
  11195. this._currentRenderId = this.getScene().getRenderId();
  11196. var worldMatrix = this._getWorldMatrix();
  11197. if (this.parent && this.parent.getWorldMatrix) {
  11198. if (!this._parentedWorldMatrix) {
  11199. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11200. }
  11201. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11202. this._markSyncedWithParent();
  11203. return this._parentedWorldMatrix;
  11204. }
  11205. return worldMatrix;
  11206. };
  11207. Light.prototype.dispose = function () {
  11208. if (this._shadowGenerator) {
  11209. this._shadowGenerator.dispose();
  11210. this._shadowGenerator = null;
  11211. }
  11212. // Animations
  11213. this.getScene().stopAnimation(this);
  11214. // Remove from scene
  11215. this.getScene().removeLight(this);
  11216. _super.prototype.dispose.call(this);
  11217. };
  11218. Light.prototype.getTypeID = function () {
  11219. return 0;
  11220. };
  11221. Light.prototype.clone = function (name) {
  11222. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11223. };
  11224. Light.prototype.serialize = function () {
  11225. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11226. // Type
  11227. serializationObject.type = this.getTypeID();
  11228. // Parent
  11229. if (this.parent) {
  11230. serializationObject.parentId = this.parent.id;
  11231. }
  11232. // Inclusion / exclusions
  11233. if (this.excludedMeshes.length > 0) {
  11234. serializationObject.excludedMeshesIds = [];
  11235. this.excludedMeshes.forEach(function (mesh) {
  11236. serializationObject.excludedMeshesIds.push(mesh.id);
  11237. });
  11238. }
  11239. if (this.includedOnlyMeshes.length > 0) {
  11240. serializationObject.includedOnlyMeshesIds = [];
  11241. this.includedOnlyMeshes.forEach(function (mesh) {
  11242. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11243. });
  11244. }
  11245. // Animations
  11246. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11247. serializationObject.ranges = this.serializeAnimationRanges();
  11248. return serializationObject;
  11249. };
  11250. Light.GetConstructorFromName = function (type, name, scene) {
  11251. switch (type) {
  11252. case 0:
  11253. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11254. case 1:
  11255. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11256. case 2:
  11257. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11258. case 3:
  11259. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11260. }
  11261. };
  11262. Light.Parse = function (parsedLight, scene) {
  11263. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11264. // Inclusion / exclusions
  11265. if (parsedLight.excludedMeshesIds) {
  11266. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11267. }
  11268. if (parsedLight.includedOnlyMeshesIds) {
  11269. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11270. }
  11271. // Parent
  11272. if (parsedLight.parentId) {
  11273. light._waitingParentId = parsedLight.parentId;
  11274. }
  11275. // Animations
  11276. if (parsedLight.animations) {
  11277. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11278. var parsedAnimation = parsedLight.animations[animationIndex];
  11279. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11280. }
  11281. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11282. }
  11283. if (parsedLight.autoAnimate) {
  11284. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11285. }
  11286. return light;
  11287. };
  11288. //lightmapMode Consts
  11289. Light._LIGHTMAP_DEFAULT = 0;
  11290. Light._LIGHTMAP_SPECULAR = 1;
  11291. Light._LIGHTMAP_SHADOWSONLY = 2;
  11292. __decorate([
  11293. BABYLON.serializeAsColor3()
  11294. ], Light.prototype, "diffuse", void 0);
  11295. __decorate([
  11296. BABYLON.serializeAsColor3()
  11297. ], Light.prototype, "specular", void 0);
  11298. __decorate([
  11299. BABYLON.serialize()
  11300. ], Light.prototype, "intensity", void 0);
  11301. __decorate([
  11302. BABYLON.serialize()
  11303. ], Light.prototype, "range", void 0);
  11304. __decorate([
  11305. BABYLON.serialize()
  11306. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11307. __decorate([
  11308. BABYLON.serialize()
  11309. ], Light.prototype, "excludeWithLayerMask", void 0);
  11310. __decorate([
  11311. BABYLON.serialize()
  11312. ], Light.prototype, "lightmapMode", void 0);
  11313. __decorate([
  11314. BABYLON.serialize()
  11315. ], Light.prototype, "radius", void 0);
  11316. return Light;
  11317. }(BABYLON.Node));
  11318. BABYLON.Light = Light;
  11319. })(BABYLON || (BABYLON = {}));
  11320. var BABYLON;
  11321. (function (BABYLON) {
  11322. var PointLight = (function (_super) {
  11323. __extends(PointLight, _super);
  11324. function PointLight(name, position, scene) {
  11325. _super.call(this, name, scene);
  11326. this.position = position;
  11327. }
  11328. PointLight.prototype.getAbsolutePosition = function () {
  11329. return this.transformedPosition ? this.transformedPosition : this.position;
  11330. };
  11331. PointLight.prototype.computeTransformedPosition = function () {
  11332. if (this.parent && this.parent.getWorldMatrix) {
  11333. if (!this.transformedPosition) {
  11334. this.transformedPosition = BABYLON.Vector3.Zero();
  11335. }
  11336. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11337. return true;
  11338. }
  11339. return false;
  11340. };
  11341. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11342. if (this.parent && this.parent.getWorldMatrix) {
  11343. this.computeTransformedPosition();
  11344. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11345. return;
  11346. }
  11347. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11348. };
  11349. PointLight.prototype.needCube = function () {
  11350. return true;
  11351. };
  11352. PointLight.prototype.supportsVSM = function () {
  11353. return false;
  11354. };
  11355. PointLight.prototype.needRefreshPerFrame = function () {
  11356. return false;
  11357. };
  11358. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11359. switch (faceIndex) {
  11360. case 0:
  11361. return new BABYLON.Vector3(1, 0, 0);
  11362. case 1:
  11363. return new BABYLON.Vector3(-1, 0, 0);
  11364. case 2:
  11365. return new BABYLON.Vector3(0, -1, 0);
  11366. case 3:
  11367. return new BABYLON.Vector3(0, 1, 0);
  11368. case 4:
  11369. return new BABYLON.Vector3(0, 0, 1);
  11370. case 5:
  11371. return new BABYLON.Vector3(0, 0, -1);
  11372. }
  11373. return BABYLON.Vector3.Zero();
  11374. };
  11375. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11376. var activeCamera = this.getScene().activeCamera;
  11377. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11378. };
  11379. PointLight.prototype._getWorldMatrix = function () {
  11380. if (!this._worldMatrix) {
  11381. this._worldMatrix = BABYLON.Matrix.Identity();
  11382. }
  11383. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11384. return this._worldMatrix;
  11385. };
  11386. PointLight.prototype.getTypeID = function () {
  11387. return 0;
  11388. };
  11389. __decorate([
  11390. BABYLON.serializeAsVector3()
  11391. ], PointLight.prototype, "position", void 0);
  11392. return PointLight;
  11393. }(BABYLON.Light));
  11394. BABYLON.PointLight = PointLight;
  11395. })(BABYLON || (BABYLON = {}));
  11396. var BABYLON;
  11397. (function (BABYLON) {
  11398. var SpotLight = (function (_super) {
  11399. __extends(SpotLight, _super);
  11400. function SpotLight(name, position, direction, angle, exponent, scene) {
  11401. _super.call(this, name, scene);
  11402. this.position = position;
  11403. this.direction = direction;
  11404. this.angle = angle;
  11405. this.exponent = exponent;
  11406. }
  11407. SpotLight.prototype.getAbsolutePosition = function () {
  11408. return this.transformedPosition ? this.transformedPosition : this.position;
  11409. };
  11410. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11411. var activeCamera = this.getScene().activeCamera;
  11412. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11413. };
  11414. SpotLight.prototype.needCube = function () {
  11415. return false;
  11416. };
  11417. SpotLight.prototype.supportsVSM = function () {
  11418. return true;
  11419. };
  11420. SpotLight.prototype.needRefreshPerFrame = function () {
  11421. return false;
  11422. };
  11423. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11424. return this.direction;
  11425. };
  11426. SpotLight.prototype.setDirectionToTarget = function (target) {
  11427. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11428. return this.direction;
  11429. };
  11430. SpotLight.prototype.computeTransformedPosition = function () {
  11431. if (this.parent && this.parent.getWorldMatrix) {
  11432. if (!this.transformedPosition) {
  11433. this.transformedPosition = BABYLON.Vector3.Zero();
  11434. }
  11435. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11436. return true;
  11437. }
  11438. return false;
  11439. };
  11440. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11441. var normalizeDirection;
  11442. if (this.parent && this.parent.getWorldMatrix) {
  11443. if (!this._transformedDirection) {
  11444. this._transformedDirection = BABYLON.Vector3.Zero();
  11445. }
  11446. this.computeTransformedPosition();
  11447. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11448. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11449. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11450. }
  11451. else {
  11452. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11453. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11454. }
  11455. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11456. };
  11457. SpotLight.prototype._getWorldMatrix = function () {
  11458. if (!this._worldMatrix) {
  11459. this._worldMatrix = BABYLON.Matrix.Identity();
  11460. }
  11461. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11462. return this._worldMatrix;
  11463. };
  11464. SpotLight.prototype.getTypeID = function () {
  11465. return 2;
  11466. };
  11467. __decorate([
  11468. BABYLON.serializeAsVector3()
  11469. ], SpotLight.prototype, "position", void 0);
  11470. __decorate([
  11471. BABYLON.serializeAsVector3()
  11472. ], SpotLight.prototype, "direction", void 0);
  11473. __decorate([
  11474. BABYLON.serialize()
  11475. ], SpotLight.prototype, "angle", void 0);
  11476. __decorate([
  11477. BABYLON.serialize()
  11478. ], SpotLight.prototype, "exponent", void 0);
  11479. return SpotLight;
  11480. }(BABYLON.Light));
  11481. BABYLON.SpotLight = SpotLight;
  11482. })(BABYLON || (BABYLON = {}));
  11483. var BABYLON;
  11484. (function (BABYLON) {
  11485. var HemisphericLight = (function (_super) {
  11486. __extends(HemisphericLight, _super);
  11487. function HemisphericLight(name, direction, scene) {
  11488. _super.call(this, name, scene);
  11489. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11490. this.direction = direction;
  11491. }
  11492. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11493. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11494. return this.direction;
  11495. };
  11496. HemisphericLight.prototype.getShadowGenerator = function () {
  11497. return null;
  11498. };
  11499. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11500. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11501. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11502. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11503. };
  11504. HemisphericLight.prototype._getWorldMatrix = function () {
  11505. if (!this._worldMatrix) {
  11506. this._worldMatrix = BABYLON.Matrix.Identity();
  11507. }
  11508. return this._worldMatrix;
  11509. };
  11510. HemisphericLight.prototype.getTypeID = function () {
  11511. return 3;
  11512. };
  11513. __decorate([
  11514. BABYLON.serializeAsColor3()
  11515. ], HemisphericLight.prototype, "groundColor", void 0);
  11516. __decorate([
  11517. BABYLON.serializeAsVector3()
  11518. ], HemisphericLight.prototype, "direction", void 0);
  11519. return HemisphericLight;
  11520. }(BABYLON.Light));
  11521. BABYLON.HemisphericLight = HemisphericLight;
  11522. })(BABYLON || (BABYLON = {}));
  11523. var BABYLON;
  11524. (function (BABYLON) {
  11525. var DirectionalLight = (function (_super) {
  11526. __extends(DirectionalLight, _super);
  11527. function DirectionalLight(name, direction, scene) {
  11528. _super.call(this, name, scene);
  11529. this.shadowOrthoScale = 0.5;
  11530. this.autoUpdateExtends = true;
  11531. // Cache
  11532. this._orthoLeft = Number.MAX_VALUE;
  11533. this._orthoRight = Number.MIN_VALUE;
  11534. this._orthoTop = Number.MIN_VALUE;
  11535. this._orthoBottom = Number.MAX_VALUE;
  11536. this.position = direction.scale(-1);
  11537. this.direction = direction;
  11538. }
  11539. DirectionalLight.prototype.getAbsolutePosition = function () {
  11540. return this.transformedPosition ? this.transformedPosition : this.position;
  11541. };
  11542. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11543. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11544. return this.direction;
  11545. };
  11546. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11547. var activeCamera = this.getScene().activeCamera;
  11548. // Check extends
  11549. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11550. var tempVector3 = BABYLON.Vector3.Zero();
  11551. this._orthoLeft = Number.MAX_VALUE;
  11552. this._orthoRight = Number.MIN_VALUE;
  11553. this._orthoTop = Number.MIN_VALUE;
  11554. this._orthoBottom = Number.MAX_VALUE;
  11555. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11556. var mesh = renderList[meshIndex];
  11557. if (!mesh) {
  11558. continue;
  11559. }
  11560. var boundingInfo = mesh.getBoundingInfo();
  11561. if (!boundingInfo) {
  11562. continue;
  11563. }
  11564. var boundingBox = boundingInfo.boundingBox;
  11565. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11566. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11567. if (tempVector3.x < this._orthoLeft)
  11568. this._orthoLeft = tempVector3.x;
  11569. if (tempVector3.y < this._orthoBottom)
  11570. this._orthoBottom = tempVector3.y;
  11571. if (tempVector3.x > this._orthoRight)
  11572. this._orthoRight = tempVector3.x;
  11573. if (tempVector3.y > this._orthoTop)
  11574. this._orthoTop = tempVector3.y;
  11575. }
  11576. }
  11577. }
  11578. var xOffset = this._orthoRight - this._orthoLeft;
  11579. var yOffset = this._orthoTop - this._orthoBottom;
  11580. 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);
  11581. };
  11582. DirectionalLight.prototype.supportsVSM = function () {
  11583. return true;
  11584. };
  11585. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11586. return true;
  11587. };
  11588. DirectionalLight.prototype.needCube = function () {
  11589. return false;
  11590. };
  11591. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11592. return this.direction;
  11593. };
  11594. DirectionalLight.prototype.computeTransformedPosition = function () {
  11595. if (this.parent && this.parent.getWorldMatrix) {
  11596. if (!this.transformedPosition) {
  11597. this.transformedPosition = BABYLON.Vector3.Zero();
  11598. }
  11599. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11600. return true;
  11601. }
  11602. return false;
  11603. };
  11604. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11605. if (this.parent && this.parent.getWorldMatrix) {
  11606. if (!this._transformedDirection) {
  11607. this._transformedDirection = BABYLON.Vector3.Zero();
  11608. }
  11609. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11610. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11611. return;
  11612. }
  11613. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11614. };
  11615. DirectionalLight.prototype._getWorldMatrix = function () {
  11616. if (!this._worldMatrix) {
  11617. this._worldMatrix = BABYLON.Matrix.Identity();
  11618. }
  11619. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11620. return this._worldMatrix;
  11621. };
  11622. DirectionalLight.prototype.getTypeID = function () {
  11623. return 1;
  11624. };
  11625. __decorate([
  11626. BABYLON.serializeAsVector3()
  11627. ], DirectionalLight.prototype, "position", void 0);
  11628. __decorate([
  11629. BABYLON.serializeAsVector3()
  11630. ], DirectionalLight.prototype, "direction", void 0);
  11631. __decorate([
  11632. BABYLON.serialize()
  11633. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11634. __decorate([
  11635. BABYLON.serialize()
  11636. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11637. return DirectionalLight;
  11638. }(BABYLON.Light));
  11639. BABYLON.DirectionalLight = DirectionalLight;
  11640. })(BABYLON || (BABYLON = {}));
  11641. var BABYLON;
  11642. (function (BABYLON) {
  11643. var ShadowGenerator = (function () {
  11644. function ShadowGenerator(mapSize, light) {
  11645. var _this = this;
  11646. // Members
  11647. this._filter = ShadowGenerator.FILTER_NONE;
  11648. this.blurScale = 2;
  11649. this._blurBoxOffset = 0;
  11650. this._bias = 0.00005;
  11651. this._lightDirection = BABYLON.Vector3.Zero();
  11652. this.forceBackFacesOnly = false;
  11653. this._darkness = 0;
  11654. this._transparencyShadow = false;
  11655. this._viewMatrix = BABYLON.Matrix.Zero();
  11656. this._projectionMatrix = BABYLON.Matrix.Zero();
  11657. this._transformMatrix = BABYLON.Matrix.Zero();
  11658. this._worldViewProjection = BABYLON.Matrix.Zero();
  11659. this._currentFaceIndex = 0;
  11660. this._currentFaceIndexCache = 0;
  11661. this._useFullFloat = true;
  11662. this._light = light;
  11663. this._scene = light.getScene();
  11664. this._mapSize = mapSize;
  11665. light._shadowGenerator = this;
  11666. // Texture type fallback from float to int if not supported.
  11667. var textureType;
  11668. var caps = this._scene.getEngine().getCaps();
  11669. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11670. this._useFullFloat = true;
  11671. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11672. }
  11673. else {
  11674. this._useFullFloat = false;
  11675. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11676. }
  11677. // Render target
  11678. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11679. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11680. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11681. this._shadowMap.anisotropicFilteringLevel = 1;
  11682. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11683. this._shadowMap.renderParticles = false;
  11684. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11685. _this._currentFaceIndex = faceIndex;
  11686. });
  11687. this._shadowMap.onAfterUnbindObservable.add(function () {
  11688. if (!_this.useBlurVarianceShadowMap) {
  11689. return;
  11690. }
  11691. if (!_this._shadowMap2) {
  11692. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11693. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11694. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11695. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11696. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11697. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11698. effect.setTexture("textureSampler", _this._shadowMap);
  11699. });
  11700. _this.blurBoxOffset = 1;
  11701. }
  11702. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11703. });
  11704. // Custom render function
  11705. var renderSubMesh = function (subMesh) {
  11706. var mesh = subMesh.getRenderingMesh();
  11707. var scene = _this._scene;
  11708. var engine = scene.getEngine();
  11709. // Culling
  11710. engine.setState(subMesh.getMaterial().backFaceCulling);
  11711. // Managing instances
  11712. var batch = mesh._getInstancesRenderList(subMesh._id);
  11713. if (batch.mustReturn) {
  11714. return;
  11715. }
  11716. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11717. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11718. engine.enableEffect(_this._effect);
  11719. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11720. var material = subMesh.getMaterial();
  11721. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11722. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11723. if (_this.getLight().needCube()) {
  11724. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11725. }
  11726. // Alpha test
  11727. if (material && material.needAlphaTesting()) {
  11728. var alphaTexture = material.getAlphaTestTexture();
  11729. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11730. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11731. }
  11732. // Bones
  11733. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11734. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11735. }
  11736. if (_this.forceBackFacesOnly) {
  11737. engine.setState(true, 0, false, true);
  11738. }
  11739. // Draw
  11740. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11741. if (_this.forceBackFacesOnly) {
  11742. engine.setState(true, 0, false, false);
  11743. }
  11744. }
  11745. else {
  11746. // Need to reset refresh rate of the shadowMap
  11747. _this._shadowMap.resetRefreshCounter();
  11748. }
  11749. };
  11750. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11751. var index;
  11752. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11753. renderSubMesh(opaqueSubMeshes.data[index]);
  11754. }
  11755. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11756. renderSubMesh(alphaTestSubMeshes.data[index]);
  11757. }
  11758. if (_this._transparencyShadow) {
  11759. for (index = 0; index < transparentSubMeshes.length; index++) {
  11760. renderSubMesh(transparentSubMeshes.data[index]);
  11761. }
  11762. }
  11763. };
  11764. this._shadowMap.onClearObservable.add(function (engine) {
  11765. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11766. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11767. }
  11768. else {
  11769. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11770. }
  11771. });
  11772. }
  11773. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11774. // Static
  11775. get: function () {
  11776. return ShadowGenerator._FILTER_NONE;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11782. get: function () {
  11783. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11789. get: function () {
  11790. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11796. get: function () {
  11797. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11803. get: function () {
  11804. return this._bias;
  11805. },
  11806. set: function (bias) {
  11807. this._bias = bias;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11813. get: function () {
  11814. return this._blurBoxOffset;
  11815. },
  11816. set: function (value) {
  11817. var _this = this;
  11818. if (this._blurBoxOffset === value) {
  11819. return;
  11820. }
  11821. this._blurBoxOffset = value;
  11822. if (this._boxBlurPostprocess) {
  11823. this._boxBlurPostprocess.dispose();
  11824. }
  11825. 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);
  11826. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11827. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11828. });
  11829. },
  11830. enumerable: true,
  11831. configurable: true
  11832. });
  11833. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11834. get: function () {
  11835. return this._filter;
  11836. },
  11837. set: function (value) {
  11838. if (this._filter === value) {
  11839. return;
  11840. }
  11841. this._filter = value;
  11842. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11843. this._shadowMap.anisotropicFilteringLevel = 16;
  11844. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11845. }
  11846. else {
  11847. this._shadowMap.anisotropicFilteringLevel = 1;
  11848. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11849. }
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11855. get: function () {
  11856. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11857. },
  11858. set: function (value) {
  11859. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11865. get: function () {
  11866. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11867. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11868. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11869. },
  11870. set: function (value) {
  11871. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11877. get: function () {
  11878. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11879. },
  11880. set: function (value) {
  11881. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11882. },
  11883. enumerable: true,
  11884. configurable: true
  11885. });
  11886. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11887. var defines = [];
  11888. if (this._useFullFloat) {
  11889. defines.push("#define FULLFLOAT");
  11890. }
  11891. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11892. defines.push("#define VSM");
  11893. }
  11894. if (this.getLight().needCube()) {
  11895. defines.push("#define CUBEMAP");
  11896. }
  11897. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11898. var mesh = subMesh.getMesh();
  11899. var material = subMesh.getMaterial();
  11900. // Alpha test
  11901. if (material && material.needAlphaTesting()) {
  11902. defines.push("#define ALPHATEST");
  11903. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11904. attribs.push(BABYLON.VertexBuffer.UVKind);
  11905. defines.push("#define UV1");
  11906. }
  11907. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11908. var alphaTexture = material.getAlphaTestTexture();
  11909. if (alphaTexture.coordinatesIndex === 1) {
  11910. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11911. defines.push("#define UV2");
  11912. }
  11913. }
  11914. }
  11915. // Bones
  11916. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11917. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11918. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11919. if (mesh.numBoneInfluencers > 4) {
  11920. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11921. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11922. }
  11923. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11924. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11925. }
  11926. else {
  11927. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11928. }
  11929. // Instances
  11930. if (useInstances) {
  11931. defines.push("#define INSTANCES");
  11932. attribs.push("world0");
  11933. attribs.push("world1");
  11934. attribs.push("world2");
  11935. attribs.push("world3");
  11936. }
  11937. // Get correct effect
  11938. var join = defines.join("\n");
  11939. if (this._cachedDefines !== join) {
  11940. this._cachedDefines = join;
  11941. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11942. }
  11943. return this._effect.isReady();
  11944. };
  11945. ShadowGenerator.prototype.getShadowMap = function () {
  11946. return this._shadowMap;
  11947. };
  11948. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11949. if (this._shadowMap2) {
  11950. return this._shadowMap2;
  11951. }
  11952. return this._shadowMap;
  11953. };
  11954. ShadowGenerator.prototype.getLight = function () {
  11955. return this._light;
  11956. };
  11957. // Methods
  11958. ShadowGenerator.prototype.getTransformMatrix = function () {
  11959. var scene = this._scene;
  11960. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11961. return this._transformMatrix;
  11962. }
  11963. this._currentRenderID = scene.getRenderId();
  11964. this._currentFaceIndexCache = this._currentFaceIndex;
  11965. var lightPosition = this._light.position;
  11966. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11967. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11968. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11969. }
  11970. if (this._light.computeTransformedPosition()) {
  11971. lightPosition = this._light.transformedPosition;
  11972. }
  11973. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11974. this._cachedPosition = lightPosition.clone();
  11975. this._cachedDirection = this._lightDirection.clone();
  11976. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11977. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11978. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11979. }
  11980. return this._transformMatrix;
  11981. };
  11982. ShadowGenerator.prototype.getDarkness = function () {
  11983. return this._darkness;
  11984. };
  11985. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11986. if (darkness >= 1.0)
  11987. this._darkness = 1.0;
  11988. else if (darkness <= 0.0)
  11989. this._darkness = 0.0;
  11990. else
  11991. this._darkness = darkness;
  11992. };
  11993. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11994. this._transparencyShadow = hasShadow;
  11995. };
  11996. ShadowGenerator.prototype._packHalf = function (depth) {
  11997. var scale = depth * 255.0;
  11998. var fract = scale - Math.floor(scale);
  11999. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12000. };
  12001. ShadowGenerator.prototype.dispose = function () {
  12002. this._shadowMap.dispose();
  12003. if (this._shadowMap2) {
  12004. this._shadowMap2.dispose();
  12005. }
  12006. if (this._downSamplePostprocess) {
  12007. this._downSamplePostprocess.dispose();
  12008. }
  12009. if (this._boxBlurPostprocess) {
  12010. this._boxBlurPostprocess.dispose();
  12011. }
  12012. };
  12013. ShadowGenerator.prototype.serialize = function () {
  12014. var serializationObject = {};
  12015. serializationObject.lightId = this._light.id;
  12016. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12017. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12018. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12019. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12020. serializationObject.renderList = [];
  12021. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12022. var mesh = this.getShadowMap().renderList[meshIndex];
  12023. serializationObject.renderList.push(mesh.id);
  12024. }
  12025. return serializationObject;
  12026. };
  12027. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12028. //casting to point light, as light is missing the position attr and typescript complains.
  12029. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12030. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12031. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12032. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12033. meshes.forEach(function (mesh) {
  12034. shadowGenerator.getShadowMap().renderList.push(mesh);
  12035. });
  12036. }
  12037. if (parsedShadowGenerator.usePoissonSampling) {
  12038. shadowGenerator.usePoissonSampling = true;
  12039. }
  12040. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12041. shadowGenerator.useVarianceShadowMap = true;
  12042. }
  12043. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12044. shadowGenerator.useBlurVarianceShadowMap = true;
  12045. if (parsedShadowGenerator.blurScale) {
  12046. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12047. }
  12048. if (parsedShadowGenerator.blurBoxOffset) {
  12049. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12050. }
  12051. }
  12052. if (parsedShadowGenerator.bias !== undefined) {
  12053. shadowGenerator.bias = parsedShadowGenerator.bias;
  12054. }
  12055. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12056. return shadowGenerator;
  12057. };
  12058. ShadowGenerator._FILTER_NONE = 0;
  12059. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12060. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12061. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12062. return ShadowGenerator;
  12063. }());
  12064. BABYLON.ShadowGenerator = ShadowGenerator;
  12065. })(BABYLON || (BABYLON = {}));
  12066. var BABYLON;
  12067. (function (BABYLON) {
  12068. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12069. if (boxMin.x > sphereCenter.x + sphereRadius)
  12070. return false;
  12071. if (sphereCenter.x - sphereRadius > boxMax.x)
  12072. return false;
  12073. if (boxMin.y > sphereCenter.y + sphereRadius)
  12074. return false;
  12075. if (sphereCenter.y - sphereRadius > boxMax.y)
  12076. return false;
  12077. if (boxMin.z > sphereCenter.z + sphereRadius)
  12078. return false;
  12079. if (sphereCenter.z - sphereRadius > boxMax.z)
  12080. return false;
  12081. return true;
  12082. };
  12083. var getLowestRoot = (function () {
  12084. var result = { root: 0, found: false };
  12085. return function (a, b, c, maxR) {
  12086. result.root = 0;
  12087. result.found = false;
  12088. var determinant = b * b - 4.0 * a * c;
  12089. if (determinant < 0)
  12090. return result;
  12091. var sqrtD = Math.sqrt(determinant);
  12092. var r1 = (-b - sqrtD) / (2.0 * a);
  12093. var r2 = (-b + sqrtD) / (2.0 * a);
  12094. if (r1 > r2) {
  12095. var temp = r2;
  12096. r2 = r1;
  12097. r1 = temp;
  12098. }
  12099. if (r1 > 0 && r1 < maxR) {
  12100. result.root = r1;
  12101. result.found = true;
  12102. return result;
  12103. }
  12104. if (r2 > 0 && r2 < maxR) {
  12105. result.root = r2;
  12106. result.found = true;
  12107. return result;
  12108. }
  12109. return result;
  12110. };
  12111. })();
  12112. var Collider = (function () {
  12113. function Collider() {
  12114. this.radius = new BABYLON.Vector3(1, 1, 1);
  12115. this.retry = 0;
  12116. this.basePointWorld = BABYLON.Vector3.Zero();
  12117. this.velocityWorld = BABYLON.Vector3.Zero();
  12118. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12119. this._collisionPoint = BABYLON.Vector3.Zero();
  12120. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12121. this._tempVector = BABYLON.Vector3.Zero();
  12122. this._tempVector2 = BABYLON.Vector3.Zero();
  12123. this._tempVector3 = BABYLON.Vector3.Zero();
  12124. this._tempVector4 = BABYLON.Vector3.Zero();
  12125. this._edge = BABYLON.Vector3.Zero();
  12126. this._baseToVertex = BABYLON.Vector3.Zero();
  12127. this._destinationPoint = BABYLON.Vector3.Zero();
  12128. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12129. this._displacementVector = BABYLON.Vector3.Zero();
  12130. }
  12131. // Methods
  12132. Collider.prototype._initialize = function (source, dir, e) {
  12133. this.velocity = dir;
  12134. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12135. this.basePoint = source;
  12136. source.multiplyToRef(this.radius, this.basePointWorld);
  12137. dir.multiplyToRef(this.radius, this.velocityWorld);
  12138. this.velocityWorldLength = this.velocityWorld.length();
  12139. this.epsilon = e;
  12140. this.collisionFound = false;
  12141. };
  12142. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12143. pa.subtractToRef(point, this._tempVector);
  12144. pb.subtractToRef(point, this._tempVector2);
  12145. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12146. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12147. if (d < 0)
  12148. return false;
  12149. pc.subtractToRef(point, this._tempVector3);
  12150. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12151. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12152. if (d < 0)
  12153. return false;
  12154. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12155. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12156. return d >= 0;
  12157. };
  12158. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12159. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12160. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12161. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12162. return false;
  12163. }
  12164. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12165. return false;
  12166. return true;
  12167. };
  12168. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12169. var t0;
  12170. var embeddedInPlane = false;
  12171. //defensive programming, actually not needed.
  12172. if (!trianglePlaneArray) {
  12173. trianglePlaneArray = [];
  12174. }
  12175. if (!trianglePlaneArray[faceIndex]) {
  12176. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12177. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12178. }
  12179. var trianglePlane = trianglePlaneArray[faceIndex];
  12180. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12181. return;
  12182. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12183. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12184. if (normalDotVelocity == 0) {
  12185. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12186. return;
  12187. embeddedInPlane = true;
  12188. t0 = 0;
  12189. }
  12190. else {
  12191. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12192. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12193. if (t0 > t1) {
  12194. var temp = t1;
  12195. t1 = t0;
  12196. t0 = temp;
  12197. }
  12198. if (t0 > 1.0 || t1 < 0.0)
  12199. return;
  12200. if (t0 < 0)
  12201. t0 = 0;
  12202. if (t0 > 1.0)
  12203. t0 = 1.0;
  12204. }
  12205. this._collisionPoint.copyFromFloats(0, 0, 0);
  12206. var found = false;
  12207. var t = 1.0;
  12208. if (!embeddedInPlane) {
  12209. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12210. this.velocity.scaleToRef(t0, this._tempVector);
  12211. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12212. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12213. found = true;
  12214. t = t0;
  12215. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12216. }
  12217. }
  12218. if (!found) {
  12219. var velocitySquaredLength = this.velocity.lengthSquared();
  12220. var a = velocitySquaredLength;
  12221. this.basePoint.subtractToRef(p1, this._tempVector);
  12222. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12223. var c = this._tempVector.lengthSquared() - 1.0;
  12224. var lowestRoot = getLowestRoot(a, b, c, t);
  12225. if (lowestRoot.found) {
  12226. t = lowestRoot.root;
  12227. found = true;
  12228. this._collisionPoint.copyFrom(p1);
  12229. }
  12230. this.basePoint.subtractToRef(p2, this._tempVector);
  12231. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12232. c = this._tempVector.lengthSquared() - 1.0;
  12233. lowestRoot = getLowestRoot(a, b, c, t);
  12234. if (lowestRoot.found) {
  12235. t = lowestRoot.root;
  12236. found = true;
  12237. this._collisionPoint.copyFrom(p2);
  12238. }
  12239. this.basePoint.subtractToRef(p3, this._tempVector);
  12240. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12241. c = this._tempVector.lengthSquared() - 1.0;
  12242. lowestRoot = getLowestRoot(a, b, c, t);
  12243. if (lowestRoot.found) {
  12244. t = lowestRoot.root;
  12245. found = true;
  12246. this._collisionPoint.copyFrom(p3);
  12247. }
  12248. p2.subtractToRef(p1, this._edge);
  12249. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12250. var edgeSquaredLength = this._edge.lengthSquared();
  12251. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12252. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12253. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12254. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12255. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12256. lowestRoot = getLowestRoot(a, b, c, t);
  12257. if (lowestRoot.found) {
  12258. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12259. if (f >= 0.0 && f <= 1.0) {
  12260. t = lowestRoot.root;
  12261. found = true;
  12262. this._edge.scaleInPlace(f);
  12263. p1.addToRef(this._edge, this._collisionPoint);
  12264. }
  12265. }
  12266. p3.subtractToRef(p2, this._edge);
  12267. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12268. edgeSquaredLength = this._edge.lengthSquared();
  12269. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12270. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12271. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12272. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12273. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12274. lowestRoot = getLowestRoot(a, b, c, t);
  12275. if (lowestRoot.found) {
  12276. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12277. if (f >= 0.0 && f <= 1.0) {
  12278. t = lowestRoot.root;
  12279. found = true;
  12280. this._edge.scaleInPlace(f);
  12281. p2.addToRef(this._edge, this._collisionPoint);
  12282. }
  12283. }
  12284. p1.subtractToRef(p3, this._edge);
  12285. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12286. edgeSquaredLength = this._edge.lengthSquared();
  12287. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12288. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12289. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12290. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12291. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12292. lowestRoot = getLowestRoot(a, b, c, t);
  12293. if (lowestRoot.found) {
  12294. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12295. if (f >= 0.0 && f <= 1.0) {
  12296. t = lowestRoot.root;
  12297. found = true;
  12298. this._edge.scaleInPlace(f);
  12299. p3.addToRef(this._edge, this._collisionPoint);
  12300. }
  12301. }
  12302. }
  12303. if (found) {
  12304. var distToCollision = t * this.velocity.length();
  12305. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12306. if (!this.intersectionPoint) {
  12307. this.intersectionPoint = this._collisionPoint.clone();
  12308. }
  12309. else {
  12310. this.intersectionPoint.copyFrom(this._collisionPoint);
  12311. }
  12312. this.nearestDistance = distToCollision;
  12313. this.collisionFound = true;
  12314. }
  12315. }
  12316. };
  12317. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12318. for (var i = indexStart; i < indexEnd; i += 3) {
  12319. var p1 = pts[indices[i] - decal];
  12320. var p2 = pts[indices[i + 1] - decal];
  12321. var p3 = pts[indices[i + 2] - decal];
  12322. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12323. }
  12324. };
  12325. Collider.prototype._getResponse = function (pos, vel) {
  12326. pos.addToRef(vel, this._destinationPoint);
  12327. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12328. this.basePoint.addToRef(vel, pos);
  12329. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12330. this._slidePlaneNormal.normalize();
  12331. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12332. pos.addInPlace(this._displacementVector);
  12333. this.intersectionPoint.addInPlace(this._displacementVector);
  12334. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12335. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12336. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12337. };
  12338. return Collider;
  12339. }());
  12340. BABYLON.Collider = Collider;
  12341. })(BABYLON || (BABYLON = {}));
  12342. var BABYLON;
  12343. (function (BABYLON) {
  12344. //WebWorker code will be inserted to this variable.
  12345. BABYLON.CollisionWorker = "";
  12346. (function (WorkerTaskType) {
  12347. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12348. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12349. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12350. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12351. var WorkerTaskType = BABYLON.WorkerTaskType;
  12352. (function (WorkerReplyType) {
  12353. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12354. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12355. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12356. var WorkerReplyType = BABYLON.WorkerReplyType;
  12357. var CollisionCoordinatorWorker = (function () {
  12358. function CollisionCoordinatorWorker() {
  12359. var _this = this;
  12360. this._scaledPosition = BABYLON.Vector3.Zero();
  12361. this._scaledVelocity = BABYLON.Vector3.Zero();
  12362. this.onMeshUpdated = function (mesh) {
  12363. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12364. };
  12365. this.onGeometryUpdated = function (geometry) {
  12366. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12367. };
  12368. this._afterRender = function () {
  12369. if (!_this._init)
  12370. return;
  12371. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12372. return;
  12373. }
  12374. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12375. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12376. if (_this._runningUpdated > 4) {
  12377. return;
  12378. }
  12379. ++_this._runningUpdated;
  12380. var payload = {
  12381. updatedMeshes: _this._addUpdateMeshesList,
  12382. updatedGeometries: _this._addUpdateGeometriesList,
  12383. removedGeometries: _this._toRemoveGeometryArray,
  12384. removedMeshes: _this._toRemoveMeshesArray
  12385. };
  12386. var message = {
  12387. payload: payload,
  12388. taskType: WorkerTaskType.UPDATE
  12389. };
  12390. var serializable = [];
  12391. for (var id in payload.updatedGeometries) {
  12392. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12393. //prepare transferables
  12394. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12395. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12396. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12397. }
  12398. }
  12399. _this._worker.postMessage(message, serializable);
  12400. _this._addUpdateMeshesList = {};
  12401. _this._addUpdateGeometriesList = {};
  12402. _this._toRemoveGeometryArray = [];
  12403. _this._toRemoveMeshesArray = [];
  12404. };
  12405. this._onMessageFromWorker = function (e) {
  12406. var returnData = e.data;
  12407. if (returnData.error != WorkerReplyType.SUCCESS) {
  12408. //TODO what errors can be returned from the worker?
  12409. BABYLON.Tools.Warn("error returned from worker!");
  12410. return;
  12411. }
  12412. switch (returnData.taskType) {
  12413. case WorkerTaskType.INIT:
  12414. _this._init = true;
  12415. //Update the worked with ALL of the scene's current state
  12416. _this._scene.meshes.forEach(function (mesh) {
  12417. _this.onMeshAdded(mesh);
  12418. });
  12419. _this._scene.getGeometries().forEach(function (geometry) {
  12420. _this.onGeometryAdded(geometry);
  12421. });
  12422. break;
  12423. case WorkerTaskType.UPDATE:
  12424. _this._runningUpdated--;
  12425. break;
  12426. case WorkerTaskType.COLLIDE:
  12427. _this._runningCollisionTask = false;
  12428. var returnPayload = returnData.payload;
  12429. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12430. return;
  12431. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12432. //cleanup
  12433. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12434. break;
  12435. }
  12436. };
  12437. this._collisionsCallbackArray = [];
  12438. this._init = false;
  12439. this._runningUpdated = 0;
  12440. this._runningCollisionTask = false;
  12441. this._addUpdateMeshesList = {};
  12442. this._addUpdateGeometriesList = {};
  12443. this._toRemoveGeometryArray = [];
  12444. this._toRemoveMeshesArray = [];
  12445. }
  12446. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12447. if (!this._init)
  12448. return;
  12449. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12450. return;
  12451. position.divideToRef(collider.radius, this._scaledPosition);
  12452. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12453. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12454. var payload = {
  12455. collider: {
  12456. position: this._scaledPosition.asArray(),
  12457. velocity: this._scaledVelocity.asArray(),
  12458. radius: collider.radius.asArray()
  12459. },
  12460. collisionId: collisionIndex,
  12461. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12462. maximumRetry: maximumRetry
  12463. };
  12464. var message = {
  12465. payload: payload,
  12466. taskType: WorkerTaskType.COLLIDE
  12467. };
  12468. this._worker.postMessage(message);
  12469. };
  12470. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12471. this._scene = scene;
  12472. this._scene.registerAfterRender(this._afterRender);
  12473. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12474. this._worker = new Worker(workerUrl);
  12475. this._worker.onmessage = this._onMessageFromWorker;
  12476. var message = {
  12477. payload: {},
  12478. taskType: WorkerTaskType.INIT
  12479. };
  12480. this._worker.postMessage(message);
  12481. };
  12482. CollisionCoordinatorWorker.prototype.destroy = function () {
  12483. this._scene.unregisterAfterRender(this._afterRender);
  12484. this._worker.terminate();
  12485. };
  12486. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12487. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12488. this.onMeshUpdated(mesh);
  12489. };
  12490. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12491. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12492. };
  12493. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12494. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12495. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12496. this.onGeometryUpdated(geometry);
  12497. };
  12498. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12499. this._toRemoveGeometryArray.push(geometry.id);
  12500. };
  12501. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12502. var submeshes = [];
  12503. if (mesh.subMeshes) {
  12504. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12505. return {
  12506. position: idx,
  12507. verticesStart: sm.verticesStart,
  12508. verticesCount: sm.verticesCount,
  12509. indexStart: sm.indexStart,
  12510. indexCount: sm.indexCount,
  12511. hasMaterial: !!sm.getMaterial(),
  12512. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12513. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12514. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12515. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12516. };
  12517. });
  12518. }
  12519. var geometryId = null;
  12520. if (mesh instanceof BABYLON.Mesh) {
  12521. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12522. }
  12523. else if (mesh instanceof BABYLON.InstancedMesh) {
  12524. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12525. }
  12526. return {
  12527. uniqueId: mesh.uniqueId,
  12528. id: mesh.id,
  12529. name: mesh.name,
  12530. geometryId: geometryId,
  12531. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12532. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12533. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12534. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12535. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12536. subMeshes: submeshes,
  12537. checkCollisions: mesh.checkCollisions
  12538. };
  12539. };
  12540. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12541. return {
  12542. id: geometry.id,
  12543. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12544. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12545. indices: new Int32Array(geometry.getIndices() || []),
  12546. };
  12547. };
  12548. return CollisionCoordinatorWorker;
  12549. }());
  12550. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12551. var CollisionCoordinatorLegacy = (function () {
  12552. function CollisionCoordinatorLegacy() {
  12553. this._scaledPosition = BABYLON.Vector3.Zero();
  12554. this._scaledVelocity = BABYLON.Vector3.Zero();
  12555. this._finalPosition = BABYLON.Vector3.Zero();
  12556. }
  12557. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12558. position.divideToRef(collider.radius, this._scaledPosition);
  12559. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12560. collider.collidedMesh = null;
  12561. collider.retry = 0;
  12562. collider.initialVelocity = this._scaledVelocity;
  12563. collider.initialPosition = this._scaledPosition;
  12564. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12565. this._finalPosition.multiplyInPlace(collider.radius);
  12566. //run the callback
  12567. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12568. };
  12569. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12570. this._scene = scene;
  12571. };
  12572. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12573. //Legacy need no destruction method.
  12574. };
  12575. //No update in legacy mode
  12576. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12577. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12578. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12579. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12580. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12581. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12582. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12583. if (excludedMesh === void 0) { excludedMesh = null; }
  12584. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12585. if (collider.retry >= maximumRetry) {
  12586. finalPosition.copyFrom(position);
  12587. return;
  12588. }
  12589. collider._initialize(position, velocity, closeDistance);
  12590. // Check all meshes
  12591. for (var index = 0; index < this._scene.meshes.length; index++) {
  12592. var mesh = this._scene.meshes[index];
  12593. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12594. mesh._checkCollision(collider);
  12595. }
  12596. }
  12597. if (!collider.collisionFound) {
  12598. position.addToRef(velocity, finalPosition);
  12599. return;
  12600. }
  12601. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12602. collider._getResponse(position, velocity);
  12603. }
  12604. if (velocity.length() <= closeDistance) {
  12605. finalPosition.copyFrom(position);
  12606. return;
  12607. }
  12608. collider.retry++;
  12609. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12610. };
  12611. return CollisionCoordinatorLegacy;
  12612. }());
  12613. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12614. })(BABYLON || (BABYLON = {}));
  12615. var BABYLON;
  12616. (function (BABYLON) {
  12617. var Camera = (function (_super) {
  12618. __extends(Camera, _super);
  12619. function Camera(name, position, scene) {
  12620. _super.call(this, name, scene);
  12621. this.upVector = BABYLON.Vector3.Up();
  12622. this.orthoLeft = null;
  12623. this.orthoRight = null;
  12624. this.orthoBottom = null;
  12625. this.orthoTop = null;
  12626. this.fov = 0.8;
  12627. this.minZ = 1.0;
  12628. this.maxZ = 10000.0;
  12629. this.inertia = 0.9;
  12630. this.mode = Camera.PERSPECTIVE_CAMERA;
  12631. this.isIntermediate = false;
  12632. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12633. this.layerMask = 0x0FFFFFFF;
  12634. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12635. // Camera rig members
  12636. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12637. this._rigCameras = new Array();
  12638. // Cache
  12639. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12640. this._projectionMatrix = new BABYLON.Matrix();
  12641. this._postProcesses = new Array();
  12642. this._transformMatrix = BABYLON.Matrix.Zero();
  12643. this._activeMeshes = new BABYLON.SmartArray(256);
  12644. this._globalPosition = BABYLON.Vector3.Zero();
  12645. this._refreshFrustumPlanes = true;
  12646. scene.addCamera(this);
  12647. if (!scene.activeCamera) {
  12648. scene.activeCamera = this;
  12649. }
  12650. this.position = position;
  12651. }
  12652. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12653. get: function () {
  12654. return Camera._PERSPECTIVE_CAMERA;
  12655. },
  12656. enumerable: true,
  12657. configurable: true
  12658. });
  12659. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12660. get: function () {
  12661. return Camera._ORTHOGRAPHIC_CAMERA;
  12662. },
  12663. enumerable: true,
  12664. configurable: true
  12665. });
  12666. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12667. get: function () {
  12668. return Camera._FOVMODE_VERTICAL_FIXED;
  12669. },
  12670. enumerable: true,
  12671. configurable: true
  12672. });
  12673. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12674. get: function () {
  12675. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12676. },
  12677. enumerable: true,
  12678. configurable: true
  12679. });
  12680. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12681. get: function () {
  12682. return Camera._RIG_MODE_NONE;
  12683. },
  12684. enumerable: true,
  12685. configurable: true
  12686. });
  12687. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12688. get: function () {
  12689. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12690. },
  12691. enumerable: true,
  12692. configurable: true
  12693. });
  12694. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12695. get: function () {
  12696. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12697. },
  12698. enumerable: true,
  12699. configurable: true
  12700. });
  12701. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12702. get: function () {
  12703. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12704. },
  12705. enumerable: true,
  12706. configurable: true
  12707. });
  12708. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12709. get: function () {
  12710. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12711. },
  12712. enumerable: true,
  12713. configurable: true
  12714. });
  12715. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12716. get: function () {
  12717. return Camera._RIG_MODE_VR;
  12718. },
  12719. enumerable: true,
  12720. configurable: true
  12721. });
  12722. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12723. get: function () {
  12724. return Camera._RIG_MODE_WEBVR;
  12725. },
  12726. enumerable: true,
  12727. configurable: true
  12728. });
  12729. /**
  12730. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12731. */
  12732. Camera.prototype.toString = function (fullDetails) {
  12733. var ret = "Name: " + this.name;
  12734. ret += ", type: " + this.getTypeName();
  12735. if (this.animations) {
  12736. for (var i = 0; i < this.animations.length; i++) {
  12737. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12738. }
  12739. }
  12740. if (fullDetails) {
  12741. }
  12742. return ret;
  12743. };
  12744. Object.defineProperty(Camera.prototype, "globalPosition", {
  12745. get: function () {
  12746. return this._globalPosition;
  12747. },
  12748. enumerable: true,
  12749. configurable: true
  12750. });
  12751. Camera.prototype.getActiveMeshes = function () {
  12752. return this._activeMeshes;
  12753. };
  12754. Camera.prototype.isActiveMesh = function (mesh) {
  12755. return (this._activeMeshes.indexOf(mesh) !== -1);
  12756. };
  12757. //Cache
  12758. Camera.prototype._initCache = function () {
  12759. _super.prototype._initCache.call(this);
  12760. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12761. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12762. this._cache.mode = undefined;
  12763. this._cache.minZ = undefined;
  12764. this._cache.maxZ = undefined;
  12765. this._cache.fov = undefined;
  12766. this._cache.fovMode = undefined;
  12767. this._cache.aspectRatio = undefined;
  12768. this._cache.orthoLeft = undefined;
  12769. this._cache.orthoRight = undefined;
  12770. this._cache.orthoBottom = undefined;
  12771. this._cache.orthoTop = undefined;
  12772. this._cache.renderWidth = undefined;
  12773. this._cache.renderHeight = undefined;
  12774. };
  12775. Camera.prototype._updateCache = function (ignoreParentClass) {
  12776. if (!ignoreParentClass) {
  12777. _super.prototype._updateCache.call(this);
  12778. }
  12779. var engine = this.getEngine();
  12780. this._cache.position.copyFrom(this.position);
  12781. this._cache.upVector.copyFrom(this.upVector);
  12782. this._cache.mode = this.mode;
  12783. this._cache.minZ = this.minZ;
  12784. this._cache.maxZ = this.maxZ;
  12785. this._cache.fov = this.fov;
  12786. this._cache.fovMode = this.fovMode;
  12787. this._cache.aspectRatio = engine.getAspectRatio(this);
  12788. this._cache.orthoLeft = this.orthoLeft;
  12789. this._cache.orthoRight = this.orthoRight;
  12790. this._cache.orthoBottom = this.orthoBottom;
  12791. this._cache.orthoTop = this.orthoTop;
  12792. this._cache.renderWidth = engine.getRenderWidth();
  12793. this._cache.renderHeight = engine.getRenderHeight();
  12794. };
  12795. Camera.prototype._updateFromScene = function () {
  12796. this.updateCache();
  12797. this.update();
  12798. };
  12799. // Synchronized
  12800. Camera.prototype._isSynchronized = function () {
  12801. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12802. };
  12803. Camera.prototype._isSynchronizedViewMatrix = function () {
  12804. if (!_super.prototype._isSynchronized.call(this))
  12805. return false;
  12806. return this._cache.position.equals(this.position)
  12807. && this._cache.upVector.equals(this.upVector)
  12808. && this.isSynchronizedWithParent();
  12809. };
  12810. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12811. var check = this._cache.mode === this.mode
  12812. && this._cache.minZ === this.minZ
  12813. && this._cache.maxZ === this.maxZ;
  12814. if (!check) {
  12815. return false;
  12816. }
  12817. var engine = this.getEngine();
  12818. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12819. check = this._cache.fov === this.fov
  12820. && this._cache.fovMode === this.fovMode
  12821. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12822. }
  12823. else {
  12824. check = this._cache.orthoLeft === this.orthoLeft
  12825. && this._cache.orthoRight === this.orthoRight
  12826. && this._cache.orthoBottom === this.orthoBottom
  12827. && this._cache.orthoTop === this.orthoTop
  12828. && this._cache.renderWidth === engine.getRenderWidth()
  12829. && this._cache.renderHeight === engine.getRenderHeight();
  12830. }
  12831. return check;
  12832. };
  12833. // Controls
  12834. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12835. };
  12836. Camera.prototype.detachControl = function (element) {
  12837. };
  12838. Camera.prototype.update = function () {
  12839. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12840. this._updateRigCameras();
  12841. }
  12842. this._checkInputs();
  12843. };
  12844. Camera.prototype._checkInputs = function () {
  12845. };
  12846. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12847. // invalidate framebuffer
  12848. if (this._postProcesses.length > 0) {
  12849. this._postProcesses[0].markTextureDirty();
  12850. }
  12851. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12852. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12853. var cam = this._rigCameras[i];
  12854. var rigPostProcess = cam._rigPostProcess;
  12855. // for VR rig, there does not have to be a post process
  12856. if (rigPostProcess) {
  12857. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12858. if (isPass) {
  12859. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12860. cam.isIntermediate = this._postProcesses.length === 0;
  12861. }
  12862. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12863. rigPostProcess.markTextureDirty();
  12864. }
  12865. else {
  12866. cam._postProcesses = this._postProcesses.slice(0);
  12867. }
  12868. }
  12869. };
  12870. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12871. if (insertAt === void 0) { insertAt = null; }
  12872. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12873. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12874. return 0;
  12875. }
  12876. if (insertAt == null || insertAt < 0) {
  12877. this._postProcesses.push(postProcess);
  12878. }
  12879. else {
  12880. this._postProcesses.splice(insertAt, 0, postProcess);
  12881. }
  12882. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12883. return this._postProcesses.indexOf(postProcess);
  12884. };
  12885. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12886. if (atIndices === void 0) { atIndices = null; }
  12887. var result = [];
  12888. var i;
  12889. var index;
  12890. if (!atIndices) {
  12891. var idx = this._postProcesses.indexOf(postProcess);
  12892. if (idx !== -1) {
  12893. this._postProcesses.splice(idx, 1);
  12894. }
  12895. }
  12896. else {
  12897. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12898. // iterate descending, so can just splice as we go
  12899. for (i = atIndices.length - 1; i >= 0; i--) {
  12900. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12901. result.push(i);
  12902. continue;
  12903. }
  12904. this._postProcesses.splice(index, 1);
  12905. }
  12906. }
  12907. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12908. return result;
  12909. };
  12910. Camera.prototype.getWorldMatrix = function () {
  12911. if (!this._worldMatrix) {
  12912. this._worldMatrix = BABYLON.Matrix.Identity();
  12913. }
  12914. var viewMatrix = this.getViewMatrix();
  12915. viewMatrix.invertToRef(this._worldMatrix);
  12916. return this._worldMatrix;
  12917. };
  12918. Camera.prototype._getViewMatrix = function () {
  12919. return BABYLON.Matrix.Identity();
  12920. };
  12921. Camera.prototype.getViewMatrix = function (force) {
  12922. this._computedViewMatrix = this._computeViewMatrix(force);
  12923. if (!force && this._isSynchronizedViewMatrix()) {
  12924. return this._computedViewMatrix;
  12925. }
  12926. this._refreshFrustumPlanes = true;
  12927. if (!this.parent || !this.parent.getWorldMatrix) {
  12928. this._globalPosition.copyFrom(this.position);
  12929. }
  12930. else {
  12931. if (!this._worldMatrix) {
  12932. this._worldMatrix = BABYLON.Matrix.Identity();
  12933. }
  12934. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12935. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12936. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12937. this._computedViewMatrix.invert();
  12938. this._markSyncedWithParent();
  12939. }
  12940. this._currentRenderId = this.getScene().getRenderId();
  12941. return this._computedViewMatrix;
  12942. };
  12943. Camera.prototype._computeViewMatrix = function (force) {
  12944. if (!force && this._isSynchronizedViewMatrix()) {
  12945. return this._computedViewMatrix;
  12946. }
  12947. this._computedViewMatrix = this._getViewMatrix();
  12948. this._currentRenderId = this.getScene().getRenderId();
  12949. return this._computedViewMatrix;
  12950. };
  12951. Camera.prototype.getProjectionMatrix = function (force) {
  12952. if (!force && this._isSynchronizedProjectionMatrix()) {
  12953. return this._projectionMatrix;
  12954. }
  12955. this._refreshFrustumPlanes = true;
  12956. var engine = this.getEngine();
  12957. var scene = this.getScene();
  12958. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12959. if (this.minZ <= 0) {
  12960. this.minZ = 0.1;
  12961. }
  12962. if (scene.useRightHandedSystem) {
  12963. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12964. }
  12965. else {
  12966. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12967. }
  12968. return this._projectionMatrix;
  12969. }
  12970. var halfWidth = engine.getRenderWidth() / 2.0;
  12971. var halfHeight = engine.getRenderHeight() / 2.0;
  12972. if (scene.useRightHandedSystem) {
  12973. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12974. }
  12975. else {
  12976. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12977. }
  12978. return this._projectionMatrix;
  12979. };
  12980. Camera.prototype.getTranformationMatrix = function () {
  12981. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12982. return this._transformMatrix;
  12983. };
  12984. Camera.prototype.updateFrustumPlanes = function () {
  12985. if (!this._refreshFrustumPlanes) {
  12986. return;
  12987. }
  12988. this.getTranformationMatrix();
  12989. if (!this._frustumPlanes) {
  12990. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12991. }
  12992. else {
  12993. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12994. }
  12995. this._refreshFrustumPlanes = false;
  12996. };
  12997. Camera.prototype.isInFrustum = function (target) {
  12998. this.updateFrustumPlanes();
  12999. return target.isInFrustum(this._frustumPlanes);
  13000. };
  13001. Camera.prototype.isCompletelyInFrustum = function (target) {
  13002. this.updateFrustumPlanes();
  13003. return target.isCompletelyInFrustum(this._frustumPlanes);
  13004. };
  13005. Camera.prototype.dispose = function () {
  13006. // Animations
  13007. this.getScene().stopAnimation(this);
  13008. // Remove from scene
  13009. this.getScene().removeCamera(this);
  13010. while (this._rigCameras.length > 0) {
  13011. this._rigCameras.pop().dispose();
  13012. }
  13013. // Postprocesses
  13014. for (var i = 0; i < this._postProcesses.length; ++i) {
  13015. this._postProcesses[i].dispose(this);
  13016. }
  13017. _super.prototype.dispose.call(this);
  13018. };
  13019. // ---- Camera rigs section ----
  13020. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13021. while (this._rigCameras.length > 0) {
  13022. this._rigCameras.pop().dispose();
  13023. }
  13024. this.cameraRigMode = mode;
  13025. this._cameraRigParams = {};
  13026. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13027. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13028. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13029. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13030. // create the rig cameras, unless none
  13031. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13032. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13033. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13034. }
  13035. switch (this.cameraRigMode) {
  13036. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13037. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13038. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13039. break;
  13040. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13041. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13042. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13043. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13044. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13045. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13046. break;
  13047. case Camera.RIG_MODE_VR:
  13048. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13049. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13050. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13051. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13052. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13053. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13054. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13055. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13056. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13057. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13058. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13059. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13060. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13061. if (metrics.compensateDistortion) {
  13062. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13063. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13064. }
  13065. break;
  13066. case Camera.RIG_MODE_WEBVR:
  13067. if (rigParams.vrDisplay) {
  13068. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13069. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13070. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13071. this._rigCameras[0].setCameraRigParameter("vrFieldOfView", leftEye.fieldOfView);
  13072. this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13073. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13074. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13075. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13076. this._rigCameras[1].setCameraRigParameter("vrFieldOfView", rightEye.fieldOfView);
  13077. this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13078. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13079. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13080. }
  13081. break;
  13082. }
  13083. this._cascadePostProcessesToRigCams();
  13084. this.
  13085. update();
  13086. };
  13087. Camera.prototype._getVRProjectionMatrix = function () {
  13088. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13089. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13090. return this._projectionMatrix;
  13091. };
  13092. Camera.prototype._getWebVRProjectionMatrix = function () {
  13093. BABYLON.Matrix.PerspectiveFovWebVRToRef(this._cameraRigParams['vrFieldOfView'], this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13094. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams['vrOffsetMatrix'], this._projectionMatrix);
  13095. return this._projectionMatrix;
  13096. };
  13097. Camera.prototype.setCameraRigParameter = function (name, value) {
  13098. if (!this._cameraRigParams) {
  13099. this._cameraRigParams = {};
  13100. }
  13101. this._cameraRigParams[name] = value;
  13102. //provisionnally:
  13103. if (name === "interaxialDistance") {
  13104. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13105. }
  13106. };
  13107. /**
  13108. * needs to be overridden by children so sub has required properties to be copied
  13109. */
  13110. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13111. return null;
  13112. };
  13113. /**
  13114. * May need to be overridden by children
  13115. */
  13116. Camera.prototype._updateRigCameras = function () {
  13117. for (var i = 0; i < this._rigCameras.length; i++) {
  13118. this._rigCameras[i].minZ = this.minZ;
  13119. this._rigCameras[i].maxZ = this.maxZ;
  13120. this._rigCameras[i].fov = this.fov;
  13121. }
  13122. // only update viewport when ANAGLYPH
  13123. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13124. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13125. }
  13126. };
  13127. Camera.prototype._setupInputs = function () {
  13128. };
  13129. Camera.prototype.serialize = function () {
  13130. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13131. // Type
  13132. serializationObject.type = this.getTypeName();
  13133. // Parent
  13134. if (this.parent) {
  13135. serializationObject.parentId = this.parent.id;
  13136. }
  13137. if (this.inputs) {
  13138. this.inputs.serialize(serializationObject);
  13139. }
  13140. // Animations
  13141. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13142. serializationObject.ranges = this.serializeAnimationRanges();
  13143. return serializationObject;
  13144. };
  13145. Camera.prototype.getTypeName = function () {
  13146. return "Camera";
  13147. };
  13148. Camera.prototype.clone = function (name) {
  13149. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13150. };
  13151. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13152. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13153. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13154. switch (type) {
  13155. case "ArcRotateCamera":
  13156. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13157. case "DeviceOrientationCamera":
  13158. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13159. case "FollowCamera":
  13160. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13161. case "ArcFollowCamera":
  13162. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13163. case "GamepadCamera":
  13164. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13165. case "TouchCamera":
  13166. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13167. case "VirtualJoysticksCamera":
  13168. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13169. case "WebVRFreeCamera":
  13170. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13171. case "VRDeviceOrientationFreeCamera":
  13172. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13173. case "AnaglyphArcRotateCamera":
  13174. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13175. case "AnaglyphFreeCamera":
  13176. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13177. case "AnaglyphGamepadCamera":
  13178. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13179. case "AnaglyphUniversalCamera":
  13180. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13181. case "StereoscopicArcRotateCamera":
  13182. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13183. case "StereoscopicFreeCamera":
  13184. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13185. case "StereoscopicGamepadCamera":
  13186. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13187. case "StereoscopicUniversalCamera":
  13188. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13189. case "FreeCamera":
  13190. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13191. default:
  13192. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13193. }
  13194. };
  13195. Camera.Parse = function (parsedCamera, scene) {
  13196. var type = parsedCamera.type;
  13197. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13198. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13199. // Parent
  13200. if (parsedCamera.parentId) {
  13201. camera._waitingParentId = parsedCamera.parentId;
  13202. }
  13203. //If camera has an input manager, let it parse inputs settings
  13204. if (camera.inputs) {
  13205. camera.inputs.parse(parsedCamera);
  13206. camera._setupInputs();
  13207. }
  13208. // Target
  13209. if (parsedCamera.target) {
  13210. if (camera.setTarget) {
  13211. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13212. }
  13213. }
  13214. // Apply 3d rig, when found
  13215. if (parsedCamera.cameraRigMode) {
  13216. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13217. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13218. }
  13219. // Animations
  13220. if (parsedCamera.animations) {
  13221. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13222. var parsedAnimation = parsedCamera.animations[animationIndex];
  13223. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13224. }
  13225. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13226. }
  13227. if (parsedCamera.autoAnimate) {
  13228. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13229. }
  13230. return camera;
  13231. };
  13232. // Statics
  13233. Camera._PERSPECTIVE_CAMERA = 0;
  13234. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13235. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13236. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13237. Camera._RIG_MODE_NONE = 0;
  13238. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13239. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13240. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13241. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13242. Camera._RIG_MODE_VR = 20;
  13243. Camera._RIG_MODE_WEBVR = 21;
  13244. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13245. __decorate([
  13246. BABYLON.serializeAsVector3()
  13247. ], Camera.prototype, "position", void 0);
  13248. __decorate([
  13249. BABYLON.serializeAsVector3()
  13250. ], Camera.prototype, "upVector", void 0);
  13251. __decorate([
  13252. BABYLON.serialize()
  13253. ], Camera.prototype, "orthoLeft", void 0);
  13254. __decorate([
  13255. BABYLON.serialize()
  13256. ], Camera.prototype, "orthoRight", void 0);
  13257. __decorate([
  13258. BABYLON.serialize()
  13259. ], Camera.prototype, "orthoBottom", void 0);
  13260. __decorate([
  13261. BABYLON.serialize()
  13262. ], Camera.prototype, "orthoTop", void 0);
  13263. __decorate([
  13264. BABYLON.serialize()
  13265. ], Camera.prototype, "fov", void 0);
  13266. __decorate([
  13267. BABYLON.serialize()
  13268. ], Camera.prototype, "minZ", void 0);
  13269. __decorate([
  13270. BABYLON.serialize()
  13271. ], Camera.prototype, "maxZ", void 0);
  13272. __decorate([
  13273. BABYLON.serialize()
  13274. ], Camera.prototype, "inertia", void 0);
  13275. __decorate([
  13276. BABYLON.serialize()
  13277. ], Camera.prototype, "mode", void 0);
  13278. __decorate([
  13279. BABYLON.serialize()
  13280. ], Camera.prototype, "layerMask", void 0);
  13281. __decorate([
  13282. BABYLON.serialize()
  13283. ], Camera.prototype, "fovMode", void 0);
  13284. __decorate([
  13285. BABYLON.serialize()
  13286. ], Camera.prototype, "cameraRigMode", void 0);
  13287. __decorate([
  13288. BABYLON.serialize()
  13289. ], Camera.prototype, "interaxialDistance", void 0);
  13290. __decorate([
  13291. BABYLON.serialize()
  13292. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13293. return Camera;
  13294. }(BABYLON.Node));
  13295. BABYLON.Camera = Camera;
  13296. })(BABYLON || (BABYLON = {}));
  13297. var BABYLON;
  13298. (function (BABYLON) {
  13299. BABYLON.CameraInputTypes = {};
  13300. var CameraInputsManager = (function () {
  13301. function CameraInputsManager(camera) {
  13302. this.attached = {};
  13303. this.camera = camera;
  13304. this.checkInputs = function () { };
  13305. }
  13306. CameraInputsManager.prototype.add = function (input) {
  13307. var type = input.getSimpleName();
  13308. if (this.attached[type]) {
  13309. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13310. return;
  13311. }
  13312. this.attached[type] = input;
  13313. input.camera = this.camera;
  13314. //for checkInputs, we are dynamically creating a function
  13315. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13316. if (input.checkInputs) {
  13317. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13318. }
  13319. if (this.attachedElement) {
  13320. input.attachControl(this.attachedElement);
  13321. }
  13322. };
  13323. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13324. for (var cam in this.attached) {
  13325. var input = this.attached[cam];
  13326. if (input === inputToRemove) {
  13327. input.detachControl(this.attachedElement);
  13328. delete this.attached[cam];
  13329. this.rebuildInputCheck();
  13330. }
  13331. }
  13332. };
  13333. CameraInputsManager.prototype.removeByType = function (inputType) {
  13334. for (var cam in this.attached) {
  13335. var input = this.attached[cam];
  13336. if (input.getTypeName() === inputType) {
  13337. input.detachControl(this.attachedElement);
  13338. delete this.attached[cam];
  13339. this.rebuildInputCheck();
  13340. }
  13341. }
  13342. };
  13343. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13344. var current = this.checkInputs;
  13345. return function () {
  13346. current();
  13347. fn();
  13348. };
  13349. };
  13350. CameraInputsManager.prototype.attachInput = function (input) {
  13351. input.attachControl(this.attachedElement, this.noPreventDefault);
  13352. };
  13353. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13354. if (this.attachedElement) {
  13355. return;
  13356. }
  13357. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13358. this.attachedElement = element;
  13359. this.noPreventDefault = noPreventDefault;
  13360. for (var cam in this.attached) {
  13361. var input = this.attached[cam];
  13362. this.attached[cam].attachControl(element, noPreventDefault);
  13363. }
  13364. };
  13365. CameraInputsManager.prototype.detachElement = function (element) {
  13366. if (this.attachedElement !== element) {
  13367. return;
  13368. }
  13369. for (var cam in this.attached) {
  13370. var input = this.attached[cam];
  13371. this.attached[cam].detachControl(element);
  13372. }
  13373. this.attachedElement = null;
  13374. };
  13375. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13376. this.checkInputs = function () { };
  13377. for (var cam in this.attached) {
  13378. var input = this.attached[cam];
  13379. if (input.checkInputs) {
  13380. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13381. }
  13382. }
  13383. };
  13384. CameraInputsManager.prototype.clear = function () {
  13385. if (this.attachedElement) {
  13386. this.detachElement(this.attachedElement);
  13387. }
  13388. this.attached = {};
  13389. this.attachedElement = null;
  13390. this.checkInputs = function () { };
  13391. };
  13392. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13393. var inputs = {};
  13394. for (var cam in this.attached) {
  13395. var input = this.attached[cam];
  13396. var res = BABYLON.SerializationHelper.Serialize(input);
  13397. inputs[input.getTypeName()] = res;
  13398. }
  13399. serializedCamera.inputsmgr = inputs;
  13400. };
  13401. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13402. var parsedInputs = parsedCamera.inputsmgr;
  13403. if (parsedInputs) {
  13404. this.clear();
  13405. for (var n in parsedInputs) {
  13406. var construct = BABYLON.CameraInputTypes[n];
  13407. if (construct) {
  13408. var parsedinput = parsedInputs[n];
  13409. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13410. this.add(input);
  13411. }
  13412. }
  13413. }
  13414. else {
  13415. //2016-03-08 this part is for managing backward compatibility
  13416. for (var n in this.attached) {
  13417. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13418. if (construct) {
  13419. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13420. this.remove(this.attached[n]);
  13421. this.add(input);
  13422. }
  13423. }
  13424. }
  13425. };
  13426. return CameraInputsManager;
  13427. }());
  13428. BABYLON.CameraInputsManager = CameraInputsManager;
  13429. })(BABYLON || (BABYLON = {}));
  13430. var BABYLON;
  13431. (function (BABYLON) {
  13432. var FreeCameraMouseInput = (function () {
  13433. function FreeCameraMouseInput(touchEnabled) {
  13434. if (touchEnabled === void 0) { touchEnabled = true; }
  13435. this.touchEnabled = touchEnabled;
  13436. this.angularSensibility = 2000.0;
  13437. }
  13438. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13439. var _this = this;
  13440. var engine = this.camera.getEngine();
  13441. if (!this._pointerInput) {
  13442. this._pointerInput = function (p, s) {
  13443. var evt = p.event;
  13444. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13445. return;
  13446. }
  13447. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13448. try {
  13449. evt.srcElement.setPointerCapture(evt.pointerId);
  13450. }
  13451. catch (e) {
  13452. }
  13453. _this.previousPosition = {
  13454. x: evt.clientX,
  13455. y: evt.clientY
  13456. };
  13457. if (!noPreventDefault) {
  13458. evt.preventDefault();
  13459. element.focus();
  13460. }
  13461. }
  13462. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13463. try {
  13464. evt.srcElement.releasePointerCapture(evt.pointerId);
  13465. }
  13466. catch (e) {
  13467. }
  13468. _this.previousPosition = null;
  13469. if (!noPreventDefault) {
  13470. evt.preventDefault();
  13471. }
  13472. }
  13473. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13474. if (!_this.previousPosition || engine.isPointerLock) {
  13475. return;
  13476. }
  13477. var offsetX = evt.clientX - _this.previousPosition.x;
  13478. var offsetY = evt.clientY - _this.previousPosition.y;
  13479. if (_this.camera.getScene().useRightHandedSystem) {
  13480. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13481. }
  13482. else {
  13483. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13484. }
  13485. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13486. _this.previousPosition = {
  13487. x: evt.clientX,
  13488. y: evt.clientY
  13489. };
  13490. if (!noPreventDefault) {
  13491. evt.preventDefault();
  13492. }
  13493. }
  13494. };
  13495. }
  13496. this._onMouseMove = function (evt) {
  13497. if (!engine.isPointerLock) {
  13498. return;
  13499. }
  13500. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13501. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13502. if (_this.camera.getScene().useRightHandedSystem) {
  13503. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13504. }
  13505. else {
  13506. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13507. }
  13508. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13509. _this.previousPosition = null;
  13510. if (!noPreventDefault) {
  13511. evt.preventDefault();
  13512. }
  13513. };
  13514. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13515. element.addEventListener("mousemove", this._onMouseMove, false);
  13516. };
  13517. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13518. if (this._observer && element) {
  13519. this.camera.getScene().onPointerObservable.remove(this._observer);
  13520. element.removeEventListener("mousemove", this._onMouseMove);
  13521. this._observer = null;
  13522. this._onMouseMove = null;
  13523. this.previousPosition = null;
  13524. }
  13525. };
  13526. FreeCameraMouseInput.prototype.getTypeName = function () {
  13527. return "FreeCameraMouseInput";
  13528. };
  13529. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13530. return "mouse";
  13531. };
  13532. __decorate([
  13533. BABYLON.serialize()
  13534. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13535. return FreeCameraMouseInput;
  13536. }());
  13537. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13538. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13539. })(BABYLON || (BABYLON = {}));
  13540. var BABYLON;
  13541. (function (BABYLON) {
  13542. var FreeCameraKeyboardMoveInput = (function () {
  13543. function FreeCameraKeyboardMoveInput() {
  13544. this._keys = [];
  13545. this.keysUp = [38];
  13546. this.keysDown = [40];
  13547. this.keysLeft = [37];
  13548. this.keysRight = [39];
  13549. }
  13550. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13551. var _this = this;
  13552. if (!this._onKeyDown) {
  13553. element.tabIndex = 1;
  13554. this._onKeyDown = function (evt) {
  13555. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13556. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13557. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13558. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13559. var index = _this._keys.indexOf(evt.keyCode);
  13560. if (index === -1) {
  13561. _this._keys.push(evt.keyCode);
  13562. }
  13563. if (!noPreventDefault) {
  13564. evt.preventDefault();
  13565. }
  13566. }
  13567. };
  13568. this._onKeyUp = function (evt) {
  13569. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13570. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13571. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13572. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13573. var index = _this._keys.indexOf(evt.keyCode);
  13574. if (index >= 0) {
  13575. _this._keys.splice(index, 1);
  13576. }
  13577. if (!noPreventDefault) {
  13578. evt.preventDefault();
  13579. }
  13580. }
  13581. };
  13582. element.addEventListener("keydown", this._onKeyDown, false);
  13583. element.addEventListener("keyup", this._onKeyUp, false);
  13584. BABYLON.Tools.RegisterTopRootEvents([
  13585. { name: "blur", handler: this._onLostFocus }
  13586. ]);
  13587. }
  13588. };
  13589. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13590. if (this._onKeyDown) {
  13591. element.removeEventListener("keydown", this._onKeyDown);
  13592. element.removeEventListener("keyup", this._onKeyUp);
  13593. BABYLON.Tools.UnregisterTopRootEvents([
  13594. { name: "blur", handler: this._onLostFocus }
  13595. ]);
  13596. this._keys = [];
  13597. this._onKeyDown = null;
  13598. this._onKeyUp = null;
  13599. }
  13600. };
  13601. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13602. if (this._onKeyDown) {
  13603. var camera = this.camera;
  13604. // Keyboard
  13605. for (var index = 0; index < this._keys.length; index++) {
  13606. var keyCode = this._keys[index];
  13607. var speed = camera._computeLocalCameraSpeed();
  13608. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13609. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13610. }
  13611. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13612. camera._localDirection.copyFromFloats(0, 0, speed);
  13613. }
  13614. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13615. camera._localDirection.copyFromFloats(speed, 0, 0);
  13616. }
  13617. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13618. camera._localDirection.copyFromFloats(0, 0, -speed);
  13619. }
  13620. if (camera.getScene().useRightHandedSystem) {
  13621. camera._localDirection.z *= -1;
  13622. }
  13623. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13624. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13625. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13626. }
  13627. }
  13628. };
  13629. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13630. return "FreeCameraKeyboardMoveInput";
  13631. };
  13632. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13633. this._keys = [];
  13634. };
  13635. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13636. return "keyboard";
  13637. };
  13638. __decorate([
  13639. BABYLON.serialize()
  13640. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13641. __decorate([
  13642. BABYLON.serialize()
  13643. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13644. __decorate([
  13645. BABYLON.serialize()
  13646. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13647. __decorate([
  13648. BABYLON.serialize()
  13649. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13650. return FreeCameraKeyboardMoveInput;
  13651. }());
  13652. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13653. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13654. })(BABYLON || (BABYLON = {}));
  13655. var BABYLON;
  13656. (function (BABYLON) {
  13657. var FreeCameraTouchInput = (function () {
  13658. function FreeCameraTouchInput() {
  13659. this._offsetX = null;
  13660. this._offsetY = null;
  13661. this._pointerCount = 0;
  13662. this._pointerPressed = [];
  13663. this.touchAngularSensibility = 200000.0;
  13664. this.touchMoveSensibility = 250.0;
  13665. }
  13666. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13667. var _this = this;
  13668. var previousPosition;
  13669. if (this._pointerInput === undefined) {
  13670. this._onLostFocus = function (evt) {
  13671. _this._offsetX = null;
  13672. _this._offsetY = null;
  13673. };
  13674. this._pointerInput = function (p, s) {
  13675. var evt = p.event;
  13676. if (evt.pointerType === "mouse") {
  13677. return;
  13678. }
  13679. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13680. if (!noPreventDefault) {
  13681. evt.preventDefault();
  13682. }
  13683. _this._pointerPressed.push(evt.pointerId);
  13684. if (_this._pointerPressed.length !== 1) {
  13685. return;
  13686. }
  13687. previousPosition = {
  13688. x: evt.clientX,
  13689. y: evt.clientY
  13690. };
  13691. }
  13692. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13693. if (!noPreventDefault) {
  13694. evt.preventDefault();
  13695. }
  13696. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13697. if (index === -1) {
  13698. return;
  13699. }
  13700. _this._pointerPressed.splice(index, 1);
  13701. if (index != 0) {
  13702. return;
  13703. }
  13704. previousPosition = null;
  13705. _this._offsetX = null;
  13706. _this._offsetY = null;
  13707. }
  13708. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13709. if (!noPreventDefault) {
  13710. evt.preventDefault();
  13711. }
  13712. if (!previousPosition) {
  13713. return;
  13714. }
  13715. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13716. if (index != 0) {
  13717. return;
  13718. }
  13719. _this._offsetX = evt.clientX - previousPosition.x;
  13720. _this._offsetY = -(evt.clientY - previousPosition.y);
  13721. }
  13722. };
  13723. }
  13724. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13725. element.addEventListener("blur", this._onLostFocus);
  13726. };
  13727. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13728. if (this._pointerInput && element) {
  13729. this.camera.getScene().onPointerObservable.remove(this._observer);
  13730. this._observer = null;
  13731. element.removeEventListener("blur", this._onLostFocus);
  13732. this._onLostFocus = null;
  13733. this._pointerPressed = [];
  13734. this._offsetX = null;
  13735. this._offsetY = null;
  13736. this._pointerCount = 0;
  13737. }
  13738. };
  13739. FreeCameraTouchInput.prototype.checkInputs = function () {
  13740. if (this._offsetX) {
  13741. var camera = this.camera;
  13742. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13743. if (this._pointerPressed.length > 1) {
  13744. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13745. }
  13746. else {
  13747. var speed = camera._computeLocalCameraSpeed();
  13748. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13749. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13750. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13751. }
  13752. }
  13753. };
  13754. FreeCameraTouchInput.prototype.getTypeName = function () {
  13755. return "FreeCameraTouchInput";
  13756. };
  13757. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13758. return "touch";
  13759. };
  13760. __decorate([
  13761. BABYLON.serialize()
  13762. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13763. __decorate([
  13764. BABYLON.serialize()
  13765. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13766. return FreeCameraTouchInput;
  13767. }());
  13768. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13769. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13770. })(BABYLON || (BABYLON = {}));
  13771. var BABYLON;
  13772. (function (BABYLON) {
  13773. var FreeCameraDeviceOrientationInput = (function () {
  13774. function FreeCameraDeviceOrientationInput() {
  13775. var _this = this;
  13776. this._screenOrientationAngle = 0;
  13777. this._screenQuaternion = new BABYLON.Quaternion();
  13778. this._alpha = 0;
  13779. this._beta = 0;
  13780. this._gamma = 0;
  13781. this._orientationChanged = function () {
  13782. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13783. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13784. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13785. };
  13786. this._deviceOrientation = function (evt) {
  13787. _this._alpha = evt.alpha;
  13788. _this._beta = evt.beta;
  13789. _this._gamma = evt.gamma;
  13790. };
  13791. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13792. this._orientationChanged();
  13793. }
  13794. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13795. get: function () {
  13796. return this._camera;
  13797. },
  13798. set: function (camera) {
  13799. this._camera = camera;
  13800. if (!this._camera.rotationQuaternion)
  13801. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13802. },
  13803. enumerable: true,
  13804. configurable: true
  13805. });
  13806. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13807. window.addEventListener("orientationchange", this._orientationChanged);
  13808. window.addEventListener("deviceorientation", this._deviceOrientation);
  13809. //In certain cases, the attach control is called AFTER orientation was changed,
  13810. //So this is needed.
  13811. this._orientationChanged();
  13812. };
  13813. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13814. window.removeEventListener("orientationchange", this._orientationChanged);
  13815. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13816. };
  13817. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13818. //if no device orientation provided, don't update the rotation.
  13819. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  13820. if (!this._alpha)
  13821. return;
  13822. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13823. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13824. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13825. //Mirror on XY Plane
  13826. this._camera.rotationQuaternion.z *= -1;
  13827. this._camera.rotationQuaternion.w *= -1;
  13828. };
  13829. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13830. return "FreeCameraDeviceOrientationInput";
  13831. };
  13832. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13833. return "deviceOrientation";
  13834. };
  13835. return FreeCameraDeviceOrientationInput;
  13836. }());
  13837. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13838. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13839. })(BABYLON || (BABYLON = {}));
  13840. var BABYLON;
  13841. (function (BABYLON) {
  13842. var FreeCameraGamepadInput = (function () {
  13843. function FreeCameraGamepadInput() {
  13844. this.gamepadAngularSensibility = 200;
  13845. this.gamepadMoveSensibility = 40;
  13846. }
  13847. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13848. var _this = this;
  13849. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13850. };
  13851. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13852. if (this._gamepads) {
  13853. this._gamepads.dispose();
  13854. }
  13855. this.gamepad = null;
  13856. };
  13857. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13858. if (this.gamepad) {
  13859. var camera = this.camera;
  13860. var LSValues = this.gamepad.leftStick;
  13861. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13862. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13863. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13864. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13865. var RSValues = this.gamepad.rightStick;
  13866. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13867. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13868. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13869. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13870. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13871. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13872. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13873. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13874. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13875. }
  13876. };
  13877. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13878. // Only the first gamepad can control the camera
  13879. if (gamepad.index === 0) {
  13880. this.gamepad = gamepad;
  13881. }
  13882. };
  13883. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13884. return "FreeCameraGamepadInput";
  13885. };
  13886. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13887. return "gamepad";
  13888. };
  13889. __decorate([
  13890. BABYLON.serialize()
  13891. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13892. __decorate([
  13893. BABYLON.serialize()
  13894. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13895. return FreeCameraGamepadInput;
  13896. }());
  13897. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13898. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13899. })(BABYLON || (BABYLON = {}));
  13900. var BABYLON;
  13901. (function (BABYLON) {
  13902. var ArcRotateCameraKeyboardMoveInput = (function () {
  13903. function ArcRotateCameraKeyboardMoveInput() {
  13904. this._keys = [];
  13905. this.keysUp = [38];
  13906. this.keysDown = [40];
  13907. this.keysLeft = [37];
  13908. this.keysRight = [39];
  13909. }
  13910. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13911. var _this = this;
  13912. element.tabIndex = 1;
  13913. this._onKeyDown = function (evt) {
  13914. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13915. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13916. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13917. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13918. var index = _this._keys.indexOf(evt.keyCode);
  13919. if (index === -1) {
  13920. _this._keys.push(evt.keyCode);
  13921. }
  13922. if (evt.preventDefault) {
  13923. if (!noPreventDefault) {
  13924. evt.preventDefault();
  13925. }
  13926. }
  13927. }
  13928. };
  13929. this._onKeyUp = function (evt) {
  13930. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13931. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13932. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13933. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13934. var index = _this._keys.indexOf(evt.keyCode);
  13935. if (index >= 0) {
  13936. _this._keys.splice(index, 1);
  13937. }
  13938. if (evt.preventDefault) {
  13939. if (!noPreventDefault) {
  13940. evt.preventDefault();
  13941. }
  13942. }
  13943. }
  13944. };
  13945. this._onLostFocus = function () {
  13946. _this._keys = [];
  13947. };
  13948. element.addEventListener("keydown", this._onKeyDown, false);
  13949. element.addEventListener("keyup", this._onKeyUp, false);
  13950. BABYLON.Tools.RegisterTopRootEvents([
  13951. { name: "blur", handler: this._onLostFocus }
  13952. ]);
  13953. };
  13954. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13955. if (element) {
  13956. element.removeEventListener("keydown", this._onKeyDown);
  13957. element.removeEventListener("keyup", this._onKeyUp);
  13958. }
  13959. BABYLON.Tools.UnregisterTopRootEvents([
  13960. { name: "blur", handler: this._onLostFocus }
  13961. ]);
  13962. this._keys = [];
  13963. this._onKeyDown = null;
  13964. this._onKeyUp = null;
  13965. this._onLostFocus = null;
  13966. };
  13967. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13968. if (this._onKeyDown) {
  13969. var camera = this.camera;
  13970. for (var index = 0; index < this._keys.length; index++) {
  13971. var keyCode = this._keys[index];
  13972. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13973. camera.inertialAlphaOffset -= 0.01;
  13974. }
  13975. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13976. camera.inertialBetaOffset -= 0.01;
  13977. }
  13978. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13979. camera.inertialAlphaOffset += 0.01;
  13980. }
  13981. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13982. camera.inertialBetaOffset += 0.01;
  13983. }
  13984. }
  13985. }
  13986. };
  13987. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13988. return "ArcRotateCameraKeyboardMoveInput";
  13989. };
  13990. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13991. return "keyboard";
  13992. };
  13993. __decorate([
  13994. BABYLON.serialize()
  13995. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13996. __decorate([
  13997. BABYLON.serialize()
  13998. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13999. __decorate([
  14000. BABYLON.serialize()
  14001. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14002. __decorate([
  14003. BABYLON.serialize()
  14004. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14005. return ArcRotateCameraKeyboardMoveInput;
  14006. }());
  14007. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14008. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14009. })(BABYLON || (BABYLON = {}));
  14010. var BABYLON;
  14011. (function (BABYLON) {
  14012. var ArcRotateCameraMouseWheelInput = (function () {
  14013. function ArcRotateCameraMouseWheelInput() {
  14014. this.wheelPrecision = 3.0;
  14015. }
  14016. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14017. var _this = this;
  14018. this._wheel = function (p, s) {
  14019. //sanity check - this should be a PointerWheel event.
  14020. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14021. return;
  14022. var event = p.event;
  14023. var delta = 0;
  14024. if (event.wheelDelta) {
  14025. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14026. }
  14027. else if (event.detail) {
  14028. delta = -event.detail / _this.wheelPrecision;
  14029. }
  14030. if (delta)
  14031. _this.camera.inertialRadiusOffset += delta;
  14032. if (event.preventDefault) {
  14033. if (!noPreventDefault) {
  14034. event.preventDefault();
  14035. }
  14036. }
  14037. };
  14038. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14039. };
  14040. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14041. if (this._observer && element) {
  14042. this.camera.getScene().onPointerObservable.remove(this._observer);
  14043. this._observer = null;
  14044. this._wheel = null;
  14045. }
  14046. };
  14047. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14048. return "ArcRotateCameraMouseWheelInput";
  14049. };
  14050. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14051. return "mousewheel";
  14052. };
  14053. __decorate([
  14054. BABYLON.serialize()
  14055. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14056. return ArcRotateCameraMouseWheelInput;
  14057. }());
  14058. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14059. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14060. })(BABYLON || (BABYLON = {}));
  14061. var BABYLON;
  14062. (function (BABYLON) {
  14063. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14064. var ArcRotateCameraPointersInput = (function () {
  14065. function ArcRotateCameraPointersInput() {
  14066. this.angularSensibilityX = 1000.0;
  14067. this.angularSensibilityY = 1000.0;
  14068. this.pinchPrecision = 6.0;
  14069. this.panningSensibility = 50.0;
  14070. this._isPanClick = false;
  14071. this.pinchInwards = true;
  14072. }
  14073. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14074. var _this = this;
  14075. var engine = this.camera.getEngine();
  14076. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14077. var pointA, pointB;
  14078. var previousPinchDistance = 0;
  14079. this._pointerInput = function (p, s) {
  14080. var evt = p.event;
  14081. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14082. try {
  14083. evt.srcElement.setPointerCapture(evt.pointerId);
  14084. }
  14085. catch (e) {
  14086. }
  14087. // Manage panning with pan button click
  14088. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14089. // manage pointers
  14090. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14091. if (pointA === undefined) {
  14092. pointA = cacheSoloPointer;
  14093. }
  14094. else if (pointB === undefined) {
  14095. pointB = cacheSoloPointer;
  14096. }
  14097. if (!noPreventDefault) {
  14098. evt.preventDefault();
  14099. element.focus();
  14100. }
  14101. }
  14102. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14103. try {
  14104. evt.srcElement.releasePointerCapture(evt.pointerId);
  14105. }
  14106. catch (e) {
  14107. }
  14108. cacheSoloPointer = null;
  14109. previousPinchDistance = 0;
  14110. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14111. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14112. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14113. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14114. pointA = pointB = undefined;
  14115. if (!noPreventDefault) {
  14116. evt.preventDefault();
  14117. }
  14118. }
  14119. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14120. if (!noPreventDefault) {
  14121. evt.preventDefault();
  14122. }
  14123. // One button down
  14124. if (pointA && pointB === undefined) {
  14125. if (_this.panningSensibility !== 0 &&
  14126. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14127. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14128. _this.camera
  14129. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14130. _this.camera
  14131. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14132. }
  14133. else {
  14134. var offsetX = evt.clientX - cacheSoloPointer.x;
  14135. var offsetY = evt.clientY - cacheSoloPointer.y;
  14136. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14137. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14138. }
  14139. cacheSoloPointer.x = evt.clientX;
  14140. cacheSoloPointer.y = evt.clientY;
  14141. }
  14142. else if (pointA && pointB) {
  14143. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14144. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14145. ed.x = evt.clientX;
  14146. ed.y = evt.clientY;
  14147. var direction = _this.pinchInwards ? 1 : -1;
  14148. var distX = pointA.x - pointB.x;
  14149. var distY = pointA.y - pointB.y;
  14150. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14151. if (previousPinchDistance === 0) {
  14152. previousPinchDistance = pinchSquaredDistance;
  14153. return;
  14154. }
  14155. if (pinchSquaredDistance !== previousPinchDistance) {
  14156. _this.camera
  14157. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14158. (_this.pinchPrecision *
  14159. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14160. direction);
  14161. previousPinchDistance = pinchSquaredDistance;
  14162. }
  14163. }
  14164. }
  14165. };
  14166. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14167. this._onContextMenu = function (evt) {
  14168. evt.preventDefault();
  14169. };
  14170. if (!this.camera._useCtrlForPanning) {
  14171. element.addEventListener("contextmenu", this._onContextMenu, false);
  14172. }
  14173. this._onLostFocus = function () {
  14174. //this._keys = [];
  14175. pointA = pointB = undefined;
  14176. previousPinchDistance = 0;
  14177. cacheSoloPointer = null;
  14178. };
  14179. this._onMouseMove = function (evt) {
  14180. if (!engine.isPointerLock) {
  14181. return;
  14182. }
  14183. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14184. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14185. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14186. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14187. if (!noPreventDefault) {
  14188. evt.preventDefault();
  14189. }
  14190. };
  14191. this._onGestureStart = function (e) {
  14192. if (window.MSGesture === undefined) {
  14193. return;
  14194. }
  14195. if (!_this._MSGestureHandler) {
  14196. _this._MSGestureHandler = new MSGesture();
  14197. _this._MSGestureHandler.target = element;
  14198. }
  14199. _this._MSGestureHandler.addPointer(e.pointerId);
  14200. };
  14201. this._onGesture = function (e) {
  14202. _this.camera.radius *= e.scale;
  14203. if (e.preventDefault) {
  14204. if (!noPreventDefault) {
  14205. e.stopPropagation();
  14206. e.preventDefault();
  14207. }
  14208. }
  14209. };
  14210. element.addEventListener("mousemove", this._onMouseMove, false);
  14211. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14212. element.addEventListener("MSGestureChange", this._onGesture, false);
  14213. element.addEventListener("keydown", this._onKeyDown, false);
  14214. element.addEventListener("keyup", this._onKeyUp, false);
  14215. BABYLON.Tools.RegisterTopRootEvents([
  14216. { name: "blur", handler: this._onLostFocus }
  14217. ]);
  14218. };
  14219. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14220. if (element && this._observer) {
  14221. this.camera.getScene().onPointerObservable.remove(this._observer);
  14222. this._observer = null;
  14223. element.removeEventListener("contextmenu", this._onContextMenu);
  14224. element.removeEventListener("mousemove", this._onMouseMove);
  14225. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14226. element.removeEventListener("MSGestureChange", this._onGesture);
  14227. element.removeEventListener("keydown", this._onKeyDown);
  14228. element.removeEventListener("keyup", this._onKeyUp);
  14229. this._isPanClick = false;
  14230. this.pinchInwards = true;
  14231. this._onKeyDown = null;
  14232. this._onKeyUp = null;
  14233. this._onMouseMove = null;
  14234. this._onGestureStart = null;
  14235. this._onGesture = null;
  14236. this._MSGestureHandler = null;
  14237. this._onLostFocus = null;
  14238. this._onContextMenu = null;
  14239. }
  14240. BABYLON.Tools.UnregisterTopRootEvents([
  14241. { name: "blur", handler: this._onLostFocus }
  14242. ]);
  14243. };
  14244. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14245. return "ArcRotateCameraPointersInput";
  14246. };
  14247. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14248. return "pointers";
  14249. };
  14250. __decorate([
  14251. BABYLON.serialize()
  14252. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14253. __decorate([
  14254. BABYLON.serialize()
  14255. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14256. __decorate([
  14257. BABYLON.serialize()
  14258. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14259. __decorate([
  14260. BABYLON.serialize()
  14261. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14262. return ArcRotateCameraPointersInput;
  14263. }());
  14264. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14265. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14266. })(BABYLON || (BABYLON = {}));
  14267. var BABYLON;
  14268. (function (BABYLON) {
  14269. var ArcRotateCameraGamepadInput = (function () {
  14270. function ArcRotateCameraGamepadInput() {
  14271. this.gamepadRotationSensibility = 80;
  14272. this.gamepadMoveSensibility = 40;
  14273. }
  14274. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14275. var _this = this;
  14276. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14277. };
  14278. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14279. if (this._gamepads) {
  14280. this._gamepads.dispose();
  14281. }
  14282. this.gamepad = null;
  14283. };
  14284. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14285. if (this.gamepad) {
  14286. var camera = this.camera;
  14287. var RSValues = this.gamepad.rightStick;
  14288. if (RSValues.x != 0) {
  14289. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14290. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14291. camera.inertialAlphaOffset += normalizedRX;
  14292. }
  14293. }
  14294. if (RSValues.y != 0) {
  14295. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14296. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14297. camera.inertialBetaOffset += normalizedRY;
  14298. }
  14299. }
  14300. var LSValues = this.gamepad.leftStick;
  14301. if (LSValues.y != 0) {
  14302. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14303. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14304. this.camera.inertialRadiusOffset -= normalizedLY;
  14305. }
  14306. }
  14307. }
  14308. };
  14309. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14310. // Only the first gamepad can control the camera
  14311. if (gamepad.index === 0) {
  14312. this.gamepad = gamepad;
  14313. }
  14314. };
  14315. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14316. return "ArcRotateCameraGamepadInput";
  14317. };
  14318. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14319. return "gamepad";
  14320. };
  14321. __decorate([
  14322. BABYLON.serialize()
  14323. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14324. __decorate([
  14325. BABYLON.serialize()
  14326. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14327. return ArcRotateCameraGamepadInput;
  14328. }());
  14329. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14330. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14331. })(BABYLON || (BABYLON = {}));
  14332. var BABYLON;
  14333. (function (BABYLON) {
  14334. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14335. function ArcRotateCameraVRDeviceOrientationInput() {
  14336. this.alphaCorrection = 1;
  14337. this.betaCorrection = 1;
  14338. this.gammaCorrection = 1;
  14339. this._alpha = 0;
  14340. this._beta = 0;
  14341. this._gamma = 0;
  14342. this._dirty = false;
  14343. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14344. }
  14345. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14346. this.camera.attachControl(element, noPreventDefault);
  14347. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14348. };
  14349. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14350. var camera = this.camera;
  14351. this._alpha = +evt.alpha | 0;
  14352. this._beta = +evt.beta | 0;
  14353. this._gamma = +evt.gamma | 0;
  14354. this._dirty = true;
  14355. };
  14356. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14357. if (this._dirty) {
  14358. this._dirty = false;
  14359. if (this._gamma < 0) {
  14360. this._gamma = 180 + this._gamma;
  14361. }
  14362. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14363. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14364. }
  14365. };
  14366. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14367. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14368. };
  14369. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14370. return "ArcRotateCameraVRDeviceOrientationInput";
  14371. };
  14372. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14373. return "VRDeviceOrientation";
  14374. };
  14375. return ArcRotateCameraVRDeviceOrientationInput;
  14376. }());
  14377. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14378. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14379. })(BABYLON || (BABYLON = {}));
  14380. var BABYLON;
  14381. (function (BABYLON) {
  14382. var TargetCamera = (function (_super) {
  14383. __extends(TargetCamera, _super);
  14384. function TargetCamera(name, position, scene) {
  14385. _super.call(this, name, position, scene);
  14386. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14387. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14388. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14389. this.speed = 2.0;
  14390. this.noRotationConstraint = false;
  14391. this.lockedTarget = null;
  14392. this._currentTarget = BABYLON.Vector3.Zero();
  14393. this._viewMatrix = BABYLON.Matrix.Zero();
  14394. this._camMatrix = BABYLON.Matrix.Zero();
  14395. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14396. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14397. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14398. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14399. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14400. this._lookAtTemp = BABYLON.Matrix.Zero();
  14401. this._tempMatrix = BABYLON.Matrix.Zero();
  14402. }
  14403. TargetCamera.prototype.getFrontPosition = function (distance) {
  14404. var direction = this.getTarget().subtract(this.position);
  14405. direction.normalize();
  14406. direction.scaleInPlace(distance);
  14407. return this.globalPosition.add(direction);
  14408. };
  14409. TargetCamera.prototype._getLockedTargetPosition = function () {
  14410. if (!this.lockedTarget) {
  14411. return null;
  14412. }
  14413. return this.lockedTarget.position || this.lockedTarget;
  14414. };
  14415. // Cache
  14416. TargetCamera.prototype._initCache = function () {
  14417. _super.prototype._initCache.call(this);
  14418. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14419. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14420. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14421. };
  14422. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14423. if (!ignoreParentClass) {
  14424. _super.prototype._updateCache.call(this);
  14425. }
  14426. var lockedTargetPosition = this._getLockedTargetPosition();
  14427. if (!lockedTargetPosition) {
  14428. this._cache.lockedTarget = null;
  14429. }
  14430. else {
  14431. if (!this._cache.lockedTarget) {
  14432. this._cache.lockedTarget = lockedTargetPosition.clone();
  14433. }
  14434. else {
  14435. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14436. }
  14437. }
  14438. this._cache.rotation.copyFrom(this.rotation);
  14439. if (this.rotationQuaternion)
  14440. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14441. };
  14442. // Synchronized
  14443. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14444. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14445. return false;
  14446. }
  14447. var lockedTargetPosition = this._getLockedTargetPosition();
  14448. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14449. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14450. };
  14451. // Methods
  14452. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14453. var engine = this.getEngine();
  14454. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14455. };
  14456. // Target
  14457. TargetCamera.prototype.setTarget = function (target) {
  14458. this.upVector.normalize();
  14459. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14460. this._camMatrix.invert();
  14461. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14462. var vDir = target.subtract(this.position);
  14463. if (vDir.x >= 0.0) {
  14464. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14465. }
  14466. else {
  14467. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14468. }
  14469. this.rotation.z = 0;
  14470. if (isNaN(this.rotation.x)) {
  14471. this.rotation.x = 0;
  14472. }
  14473. if (isNaN(this.rotation.y)) {
  14474. this.rotation.y = 0;
  14475. }
  14476. if (isNaN(this.rotation.z)) {
  14477. this.rotation.z = 0;
  14478. }
  14479. if (this.rotationQuaternion) {
  14480. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14481. }
  14482. };
  14483. TargetCamera.prototype.getTarget = function () {
  14484. return this._currentTarget;
  14485. };
  14486. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14487. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14488. };
  14489. TargetCamera.prototype._updatePosition = function () {
  14490. this.position.addInPlace(this.cameraDirection);
  14491. };
  14492. TargetCamera.prototype._checkInputs = function () {
  14493. var needToMove = this._decideIfNeedsToMove();
  14494. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14495. // Move
  14496. if (needToMove) {
  14497. this._updatePosition();
  14498. }
  14499. // Rotate
  14500. if (needToRotate) {
  14501. this.rotation.x += this.cameraRotation.x;
  14502. this.rotation.y += this.cameraRotation.y;
  14503. if (!this.noRotationConstraint) {
  14504. var limit = (Math.PI / 2) * 0.95;
  14505. if (this.rotation.x > limit)
  14506. this.rotation.x = limit;
  14507. if (this.rotation.x < -limit)
  14508. this.rotation.x = -limit;
  14509. }
  14510. }
  14511. // Inertia
  14512. if (needToMove) {
  14513. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14514. this.cameraDirection.x = 0;
  14515. }
  14516. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14517. this.cameraDirection.y = 0;
  14518. }
  14519. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14520. this.cameraDirection.z = 0;
  14521. }
  14522. this.cameraDirection.scaleInPlace(this.inertia);
  14523. }
  14524. if (needToRotate) {
  14525. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14526. this.cameraRotation.x = 0;
  14527. }
  14528. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14529. this.cameraRotation.y = 0;
  14530. }
  14531. this.cameraRotation.scaleInPlace(this.inertia);
  14532. }
  14533. _super.prototype._checkInputs.call(this);
  14534. };
  14535. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14536. if (this.rotationQuaternion) {
  14537. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14538. //update the up vector!
  14539. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14540. }
  14541. else {
  14542. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14543. }
  14544. };
  14545. TargetCamera.prototype._getViewMatrix = function () {
  14546. if (!this.lockedTarget) {
  14547. // Compute
  14548. this._updateCameraRotationMatrix();
  14549. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14550. // Computing target and final matrix
  14551. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14552. }
  14553. else {
  14554. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14555. }
  14556. if (this.getScene().useRightHandedSystem) {
  14557. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14558. }
  14559. else {
  14560. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14561. }
  14562. return this._viewMatrix;
  14563. };
  14564. /**
  14565. * @override
  14566. * Override Camera.createRigCamera
  14567. */
  14568. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14569. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14570. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14571. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14572. if (!this.rotationQuaternion) {
  14573. this.rotationQuaternion = new BABYLON.Quaternion();
  14574. }
  14575. rigCamera._cameraRigParams = {};
  14576. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14577. }
  14578. return rigCamera;
  14579. }
  14580. return null;
  14581. };
  14582. /**
  14583. * @override
  14584. * Override Camera._updateRigCameras
  14585. */
  14586. TargetCamera.prototype._updateRigCameras = function () {
  14587. var camLeft = this._rigCameras[0];
  14588. var camRight = this._rigCameras[1];
  14589. switch (this.cameraRigMode) {
  14590. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14591. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14592. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14593. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14594. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14595. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14596. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14597. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14598. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14599. camLeft.setTarget(this.getTarget());
  14600. camRight.setTarget(this.getTarget());
  14601. break;
  14602. case BABYLON.Camera.RIG_MODE_VR:
  14603. case BABYLON.Camera.RIG_MODE_WEBVR:
  14604. if (camLeft.rotationQuaternion) {
  14605. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14606. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14607. }
  14608. else {
  14609. camLeft.rotation.copyFrom(this.rotation);
  14610. camRight.rotation.copyFrom(this.rotation);
  14611. }
  14612. camLeft.position.copyFrom(this.position);
  14613. camRight.position.copyFrom(this.position);
  14614. break;
  14615. }
  14616. _super.prototype._updateRigCameras.call(this);
  14617. };
  14618. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14619. if (!this._rigCamTransformMatrix) {
  14620. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14621. }
  14622. var target = this.getTarget();
  14623. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14624. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14625. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14626. };
  14627. TargetCamera.prototype.getTypeName = function () {
  14628. return "TargetCamera";
  14629. };
  14630. __decorate([
  14631. BABYLON.serializeAsVector3()
  14632. ], TargetCamera.prototype, "rotation", void 0);
  14633. __decorate([
  14634. BABYLON.serialize()
  14635. ], TargetCamera.prototype, "speed", void 0);
  14636. __decorate([
  14637. BABYLON.serializeAsMeshReference("lockedTargetId")
  14638. ], TargetCamera.prototype, "lockedTarget", void 0);
  14639. return TargetCamera;
  14640. }(BABYLON.Camera));
  14641. BABYLON.TargetCamera = TargetCamera;
  14642. })(BABYLON || (BABYLON = {}));
  14643. var BABYLON;
  14644. (function (BABYLON) {
  14645. var FreeCamera = (function (_super) {
  14646. __extends(FreeCamera, _super);
  14647. function FreeCamera(name, position, scene) {
  14648. var _this = this;
  14649. _super.call(this, name, position, scene);
  14650. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14651. this.checkCollisions = false;
  14652. this.applyGravity = false;
  14653. this._collider = new BABYLON.Collider();
  14654. this._needMoveForGravity = false;
  14655. this._oldPosition = BABYLON.Vector3.Zero();
  14656. this._diffPosition = BABYLON.Vector3.Zero();
  14657. this._newPosition = BABYLON.Vector3.Zero();
  14658. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14659. if (collidedMesh === void 0) { collidedMesh = null; }
  14660. //TODO move this to the collision coordinator!
  14661. if (_this.getScene().workerCollisions)
  14662. newPosition.multiplyInPlace(_this._collider.radius);
  14663. var updatePosition = function (newPos) {
  14664. _this._newPosition.copyFrom(newPos);
  14665. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14666. var oldPosition = _this.position.clone();
  14667. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14668. _this.position.addInPlace(_this._diffPosition);
  14669. if (_this.onCollide && collidedMesh) {
  14670. _this.onCollide(collidedMesh);
  14671. }
  14672. }
  14673. };
  14674. updatePosition(newPosition);
  14675. };
  14676. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14677. this.inputs.addKeyboard().addMouse();
  14678. }
  14679. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14680. //-- begin properties for backward compatibility for inputs
  14681. get: function () {
  14682. var mouse = this.inputs.attached["mouse"];
  14683. if (mouse)
  14684. return mouse.angularSensibility;
  14685. },
  14686. set: function (value) {
  14687. var mouse = this.inputs.attached["mouse"];
  14688. if (mouse)
  14689. mouse.angularSensibility = value;
  14690. },
  14691. enumerable: true,
  14692. configurable: true
  14693. });
  14694. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14695. get: function () {
  14696. var keyboard = this.inputs.attached["keyboard"];
  14697. if (keyboard)
  14698. return keyboard.keysUp;
  14699. },
  14700. set: function (value) {
  14701. var keyboard = this.inputs.attached["keyboard"];
  14702. if (keyboard)
  14703. keyboard.keysUp = value;
  14704. },
  14705. enumerable: true,
  14706. configurable: true
  14707. });
  14708. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14709. get: function () {
  14710. var keyboard = this.inputs.attached["keyboard"];
  14711. if (keyboard)
  14712. return keyboard.keysDown;
  14713. },
  14714. set: function (value) {
  14715. var keyboard = this.inputs.attached["keyboard"];
  14716. if (keyboard)
  14717. keyboard.keysDown = value;
  14718. },
  14719. enumerable: true,
  14720. configurable: true
  14721. });
  14722. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14723. get: function () {
  14724. var keyboard = this.inputs.attached["keyboard"];
  14725. if (keyboard)
  14726. return keyboard.keysLeft;
  14727. },
  14728. set: function (value) {
  14729. var keyboard = this.inputs.attached["keyboard"];
  14730. if (keyboard)
  14731. keyboard.keysLeft = value;
  14732. },
  14733. enumerable: true,
  14734. configurable: true
  14735. });
  14736. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14737. get: function () {
  14738. var keyboard = this.inputs.attached["keyboard"];
  14739. if (keyboard)
  14740. return keyboard.keysRight;
  14741. },
  14742. set: function (value) {
  14743. var keyboard = this.inputs.attached["keyboard"];
  14744. if (keyboard)
  14745. keyboard.keysRight = value;
  14746. },
  14747. enumerable: true,
  14748. configurable: true
  14749. });
  14750. // Controls
  14751. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14752. this.inputs.attachElement(element, noPreventDefault);
  14753. };
  14754. FreeCamera.prototype.detachControl = function (element) {
  14755. this.inputs.detachElement(element);
  14756. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14757. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14758. };
  14759. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14760. var globalPosition;
  14761. if (this.parent) {
  14762. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14763. }
  14764. else {
  14765. globalPosition = this.position;
  14766. }
  14767. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14768. this._collider.radius = this.ellipsoid;
  14769. //no need for clone, as long as gravity is not on.
  14770. var actualVelocity = velocity;
  14771. //add gravity to the velocity to prevent the dual-collision checking
  14772. if (this.applyGravity) {
  14773. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14774. actualVelocity = velocity.add(this.getScene().gravity);
  14775. }
  14776. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14777. };
  14778. FreeCamera.prototype._checkInputs = function () {
  14779. if (!this._localDirection) {
  14780. this._localDirection = BABYLON.Vector3.Zero();
  14781. this._transformedDirection = BABYLON.Vector3.Zero();
  14782. }
  14783. this.inputs.checkInputs();
  14784. _super.prototype._checkInputs.call(this);
  14785. };
  14786. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14787. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14788. };
  14789. FreeCamera.prototype._updatePosition = function () {
  14790. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14791. this._collideWithWorld(this.cameraDirection);
  14792. }
  14793. else {
  14794. this.position.addInPlace(this.cameraDirection);
  14795. }
  14796. };
  14797. FreeCamera.prototype.dispose = function () {
  14798. this.inputs.clear();
  14799. _super.prototype.dispose.call(this);
  14800. };
  14801. FreeCamera.prototype.getTypeName = function () {
  14802. return "FreeCamera";
  14803. };
  14804. __decorate([
  14805. BABYLON.serializeAsVector3()
  14806. ], FreeCamera.prototype, "ellipsoid", void 0);
  14807. __decorate([
  14808. BABYLON.serialize()
  14809. ], FreeCamera.prototype, "checkCollisions", void 0);
  14810. __decorate([
  14811. BABYLON.serialize()
  14812. ], FreeCamera.prototype, "applyGravity", void 0);
  14813. return FreeCamera;
  14814. }(BABYLON.TargetCamera));
  14815. BABYLON.FreeCamera = FreeCamera;
  14816. })(BABYLON || (BABYLON = {}));
  14817. var BABYLON;
  14818. (function (BABYLON) {
  14819. var FreeCameraInputsManager = (function (_super) {
  14820. __extends(FreeCameraInputsManager, _super);
  14821. function FreeCameraInputsManager(camera) {
  14822. _super.call(this, camera);
  14823. }
  14824. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14825. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14826. return this;
  14827. };
  14828. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14829. if (touchEnabled === void 0) { touchEnabled = true; }
  14830. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14831. return this;
  14832. };
  14833. FreeCameraInputsManager.prototype.addGamepad = function () {
  14834. this.add(new BABYLON.FreeCameraGamepadInput());
  14835. return this;
  14836. };
  14837. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14838. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14839. return this;
  14840. };
  14841. FreeCameraInputsManager.prototype.addTouch = function () {
  14842. this.add(new BABYLON.FreeCameraTouchInput());
  14843. return this;
  14844. };
  14845. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14846. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14847. return this;
  14848. };
  14849. return FreeCameraInputsManager;
  14850. }(BABYLON.CameraInputsManager));
  14851. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14852. })(BABYLON || (BABYLON = {}));
  14853. var BABYLON;
  14854. (function (BABYLON) {
  14855. var FollowCamera = (function (_super) {
  14856. __extends(FollowCamera, _super);
  14857. function FollowCamera(name, position, scene, target) {
  14858. _super.call(this, name, position, scene);
  14859. this.radius = 12;
  14860. this.rotationOffset = 0;
  14861. this.heightOffset = 4;
  14862. this.cameraAcceleration = 0.05;
  14863. this.maxCameraSpeed = 20;
  14864. this.target = target;
  14865. }
  14866. FollowCamera.prototype.getRadians = function (degrees) {
  14867. return degrees * Math.PI / 180;
  14868. };
  14869. FollowCamera.prototype.follow = function (cameraTarget) {
  14870. if (!cameraTarget)
  14871. return;
  14872. var yRotation;
  14873. if (cameraTarget.rotationQuaternion) {
  14874. var rotMatrix = new BABYLON.Matrix();
  14875. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14876. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14877. }
  14878. else {
  14879. yRotation = cameraTarget.rotation.y;
  14880. }
  14881. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14882. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14883. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14884. var dx = targetX - this.position.x;
  14885. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14886. var dz = (targetZ) - this.position.z;
  14887. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14888. var vy = dy * this.cameraAcceleration;
  14889. var vz = dz * this.cameraAcceleration * 2;
  14890. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14891. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14892. }
  14893. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14894. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14895. }
  14896. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14897. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14898. }
  14899. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14900. this.setTarget(cameraTarget.position);
  14901. };
  14902. FollowCamera.prototype._checkInputs = function () {
  14903. _super.prototype._checkInputs.call(this);
  14904. this.follow(this.target);
  14905. };
  14906. FollowCamera.prototype.getTypeName = function () {
  14907. return "FollowCamera";
  14908. };
  14909. __decorate([
  14910. BABYLON.serialize()
  14911. ], FollowCamera.prototype, "radius", void 0);
  14912. __decorate([
  14913. BABYLON.serialize()
  14914. ], FollowCamera.prototype, "rotationOffset", void 0);
  14915. __decorate([
  14916. BABYLON.serialize()
  14917. ], FollowCamera.prototype, "heightOffset", void 0);
  14918. __decorate([
  14919. BABYLON.serialize()
  14920. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14921. __decorate([
  14922. BABYLON.serialize()
  14923. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14924. __decorate([
  14925. BABYLON.serializeAsMeshReference("lockedTargetId")
  14926. ], FollowCamera.prototype, "target", void 0);
  14927. return FollowCamera;
  14928. }(BABYLON.TargetCamera));
  14929. BABYLON.FollowCamera = FollowCamera;
  14930. var ArcFollowCamera = (function (_super) {
  14931. __extends(ArcFollowCamera, _super);
  14932. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14933. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14934. this.alpha = alpha;
  14935. this.beta = beta;
  14936. this.radius = radius;
  14937. this.target = target;
  14938. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14939. this.follow();
  14940. }
  14941. ArcFollowCamera.prototype.follow = function () {
  14942. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14943. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14944. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14945. this.position = this.target.position.add(this._cartesianCoordinates);
  14946. this.setTarget(this.target.position);
  14947. };
  14948. ArcFollowCamera.prototype._checkInputs = function () {
  14949. _super.prototype._checkInputs.call(this);
  14950. this.follow();
  14951. };
  14952. ArcFollowCamera.prototype.getTypeName = function () {
  14953. return "ArcFollowCamera";
  14954. };
  14955. return ArcFollowCamera;
  14956. }(BABYLON.TargetCamera));
  14957. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14958. })(BABYLON || (BABYLON = {}));
  14959. var BABYLON;
  14960. (function (BABYLON) {
  14961. // We're mainly based on the logic defined into the FreeCamera code
  14962. var TouchCamera = (function (_super) {
  14963. __extends(TouchCamera, _super);
  14964. //-- end properties for backward compatibility for inputs
  14965. function TouchCamera(name, position, scene) {
  14966. _super.call(this, name, position, scene);
  14967. this.inputs.addTouch();
  14968. this._setupInputs();
  14969. }
  14970. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14971. //-- Begin properties for backward compatibility for inputs
  14972. get: function () {
  14973. var touch = this.inputs.attached["touch"];
  14974. if (touch)
  14975. return touch.touchAngularSensibility;
  14976. },
  14977. set: function (value) {
  14978. var touch = this.inputs.attached["touch"];
  14979. if (touch)
  14980. touch.touchAngularSensibility = value;
  14981. },
  14982. enumerable: true,
  14983. configurable: true
  14984. });
  14985. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14986. get: function () {
  14987. var touch = this.inputs.attached["touch"];
  14988. if (touch)
  14989. return touch.touchMoveSensibility;
  14990. },
  14991. set: function (value) {
  14992. var touch = this.inputs.attached["touch"];
  14993. if (touch)
  14994. touch.touchMoveSensibility = value;
  14995. },
  14996. enumerable: true,
  14997. configurable: true
  14998. });
  14999. TouchCamera.prototype.getTypeName = function () {
  15000. return "TouchCamera";
  15001. };
  15002. TouchCamera.prototype._setupInputs = function () {
  15003. var mouse = this.inputs.attached["mouse"];
  15004. if (mouse) {
  15005. mouse.touchEnabled = false;
  15006. }
  15007. };
  15008. return TouchCamera;
  15009. }(BABYLON.FreeCamera));
  15010. BABYLON.TouchCamera = TouchCamera;
  15011. })(BABYLON || (BABYLON = {}));
  15012. var BABYLON;
  15013. (function (BABYLON) {
  15014. var ArcRotateCamera = (function (_super) {
  15015. __extends(ArcRotateCamera, _super);
  15016. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15017. var _this = this;
  15018. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15019. this.inertialAlphaOffset = 0;
  15020. this.inertialBetaOffset = 0;
  15021. this.inertialRadiusOffset = 0;
  15022. this.lowerAlphaLimit = null;
  15023. this.upperAlphaLimit = null;
  15024. this.lowerBetaLimit = 0.01;
  15025. this.upperBetaLimit = Math.PI;
  15026. this.lowerRadiusLimit = null;
  15027. this.upperRadiusLimit = null;
  15028. this.inertialPanningX = 0;
  15029. this.inertialPanningY = 0;
  15030. //-- end properties for backward compatibility for inputs
  15031. this.zoomOnFactor = 1;
  15032. this.targetScreenOffset = BABYLON.Vector2.Zero();
  15033. this.allowUpsideDown = true;
  15034. this._viewMatrix = new BABYLON.Matrix();
  15035. // Panning
  15036. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15037. this.checkCollisions = false;
  15038. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15039. this._collider = new BABYLON.Collider();
  15040. this._previousPosition = BABYLON.Vector3.Zero();
  15041. this._collisionVelocity = BABYLON.Vector3.Zero();
  15042. this._newPosition = BABYLON.Vector3.Zero();
  15043. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15044. if (collidedMesh === void 0) { collidedMesh = null; }
  15045. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15046. newPosition.multiplyInPlace(_this._collider.radius);
  15047. }
  15048. if (!collidedMesh) {
  15049. _this._previousPosition.copyFrom(_this.position);
  15050. }
  15051. else {
  15052. _this.setPosition(newPosition);
  15053. if (_this.onCollide) {
  15054. _this.onCollide(collidedMesh);
  15055. }
  15056. }
  15057. // Recompute because of constraints
  15058. var cosa = Math.cos(_this.alpha);
  15059. var sina = Math.sin(_this.alpha);
  15060. var cosb = Math.cos(_this.beta);
  15061. var sinb = Math.sin(_this.beta);
  15062. if (sinb === 0) {
  15063. sinb = 0.0001;
  15064. }
  15065. var target = _this._getTargetPosition();
  15066. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15067. _this.position.copyFrom(_this._newPosition);
  15068. var up = _this.upVector;
  15069. if (_this.allowUpsideDown && _this.beta < 0) {
  15070. up = up.clone();
  15071. up = up.negate();
  15072. }
  15073. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15074. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15075. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15076. _this._collisionTriggered = false;
  15077. };
  15078. if (!target) {
  15079. this.target = BABYLON.Vector3.Zero();
  15080. }
  15081. else {
  15082. this.target = target;
  15083. }
  15084. this.alpha = alpha;
  15085. this.beta = beta;
  15086. this.radius = radius;
  15087. this.getViewMatrix();
  15088. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15089. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15090. }
  15091. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15092. //-- begin properties for backward compatibility for inputs
  15093. get: function () {
  15094. var pointers = this.inputs.attached["pointers"];
  15095. if (pointers)
  15096. return pointers.angularSensibilityX;
  15097. },
  15098. set: function (value) {
  15099. var pointers = this.inputs.attached["pointers"];
  15100. if (pointers) {
  15101. pointers.angularSensibilityX = value;
  15102. }
  15103. },
  15104. enumerable: true,
  15105. configurable: true
  15106. });
  15107. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15108. get: function () {
  15109. var pointers = this.inputs.attached["pointers"];
  15110. if (pointers)
  15111. return pointers.angularSensibilityY;
  15112. },
  15113. set: function (value) {
  15114. var pointers = this.inputs.attached["pointers"];
  15115. if (pointers) {
  15116. pointers.angularSensibilityY = value;
  15117. }
  15118. },
  15119. enumerable: true,
  15120. configurable: true
  15121. });
  15122. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15123. get: function () {
  15124. var pointers = this.inputs.attached["pointers"];
  15125. if (pointers)
  15126. return pointers.pinchPrecision;
  15127. },
  15128. set: function (value) {
  15129. var pointers = this.inputs.attached["pointers"];
  15130. if (pointers) {
  15131. pointers.pinchPrecision = value;
  15132. }
  15133. },
  15134. enumerable: true,
  15135. configurable: true
  15136. });
  15137. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15138. get: function () {
  15139. var pointers = this.inputs.attached["pointers"];
  15140. if (pointers)
  15141. return pointers.panningSensibility;
  15142. },
  15143. set: function (value) {
  15144. var pointers = this.inputs.attached["pointers"];
  15145. if (pointers) {
  15146. pointers.panningSensibility = value;
  15147. }
  15148. },
  15149. enumerable: true,
  15150. configurable: true
  15151. });
  15152. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15153. get: function () {
  15154. var keyboard = this.inputs.attached["keyboard"];
  15155. if (keyboard)
  15156. return keyboard.keysUp;
  15157. },
  15158. set: function (value) {
  15159. var keyboard = this.inputs.attached["keyboard"];
  15160. if (keyboard)
  15161. keyboard.keysUp = value;
  15162. },
  15163. enumerable: true,
  15164. configurable: true
  15165. });
  15166. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15167. get: function () {
  15168. var keyboard = this.inputs.attached["keyboard"];
  15169. if (keyboard)
  15170. return keyboard.keysDown;
  15171. },
  15172. set: function (value) {
  15173. var keyboard = this.inputs.attached["keyboard"];
  15174. if (keyboard)
  15175. keyboard.keysDown = value;
  15176. },
  15177. enumerable: true,
  15178. configurable: true
  15179. });
  15180. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15181. get: function () {
  15182. var keyboard = this.inputs.attached["keyboard"];
  15183. if (keyboard)
  15184. return keyboard.keysLeft;
  15185. },
  15186. set: function (value) {
  15187. var keyboard = this.inputs.attached["keyboard"];
  15188. if (keyboard)
  15189. keyboard.keysLeft = value;
  15190. },
  15191. enumerable: true,
  15192. configurable: true
  15193. });
  15194. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15195. get: function () {
  15196. var keyboard = this.inputs.attached["keyboard"];
  15197. if (keyboard)
  15198. return keyboard.keysRight;
  15199. },
  15200. set: function (value) {
  15201. var keyboard = this.inputs.attached["keyboard"];
  15202. if (keyboard)
  15203. keyboard.keysRight = value;
  15204. },
  15205. enumerable: true,
  15206. configurable: true
  15207. });
  15208. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15209. get: function () {
  15210. var mousewheel = this.inputs.attached["mousewheel"];
  15211. if (mousewheel)
  15212. return mousewheel.wheelPrecision;
  15213. },
  15214. set: function (value) {
  15215. var mousewheel = this.inputs.attached["mousewheel"];
  15216. if (mousewheel)
  15217. mousewheel.wheelPrecision = value;
  15218. },
  15219. enumerable: true,
  15220. configurable: true
  15221. });
  15222. // Cache
  15223. ArcRotateCamera.prototype._initCache = function () {
  15224. _super.prototype._initCache.call(this);
  15225. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15226. this._cache.alpha = undefined;
  15227. this._cache.beta = undefined;
  15228. this._cache.radius = undefined;
  15229. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15230. };
  15231. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15232. if (!ignoreParentClass) {
  15233. _super.prototype._updateCache.call(this);
  15234. }
  15235. this._cache.target.copyFrom(this._getTargetPosition());
  15236. this._cache.alpha = this.alpha;
  15237. this._cache.beta = this.beta;
  15238. this._cache.radius = this.radius;
  15239. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15240. };
  15241. ArcRotateCamera.prototype._getTargetPosition = function () {
  15242. if (this.target.getAbsolutePosition) {
  15243. var pos = this.target.getAbsolutePosition();
  15244. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15245. }
  15246. return this.target;
  15247. };
  15248. // Synchronized
  15249. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15250. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15251. return false;
  15252. return this._cache.target.equals(this.target)
  15253. && this._cache.alpha === this.alpha
  15254. && this._cache.beta === this.beta
  15255. && this._cache.radius === this.radius
  15256. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15257. };
  15258. // Methods
  15259. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15260. var _this = this;
  15261. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15262. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15263. this._useCtrlForPanning = useCtrlForPanning;
  15264. this._panningMouseButton = panningMouseButton;
  15265. this.inputs.attachElement(element, noPreventDefault);
  15266. this._reset = function () {
  15267. _this.inertialAlphaOffset = 0;
  15268. _this.inertialBetaOffset = 0;
  15269. _this.inertialRadiusOffset = 0;
  15270. };
  15271. };
  15272. ArcRotateCamera.prototype.detachControl = function (element) {
  15273. this.inputs.detachElement(element);
  15274. if (this._reset) {
  15275. this._reset();
  15276. }
  15277. };
  15278. ArcRotateCamera.prototype._checkInputs = function () {
  15279. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15280. if (this._collisionTriggered) {
  15281. return;
  15282. }
  15283. this.inputs.checkInputs();
  15284. // Inertia
  15285. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15286. this.beta += this.inertialBetaOffset;
  15287. if (this.getScene().useRightHandedSystem) {
  15288. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15289. }
  15290. else {
  15291. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15292. }
  15293. this.radius -= this.inertialRadiusOffset;
  15294. this.inertialAlphaOffset *= this.inertia;
  15295. this.inertialBetaOffset *= this.inertia;
  15296. this.inertialRadiusOffset *= this.inertia;
  15297. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15298. this.inertialAlphaOffset = 0;
  15299. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15300. this.inertialBetaOffset = 0;
  15301. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15302. this.inertialRadiusOffset = 0;
  15303. }
  15304. // Panning inertia
  15305. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15306. if (!this._localDirection) {
  15307. this._localDirection = BABYLON.Vector3.Zero();
  15308. this._transformedDirection = BABYLON.Vector3.Zero();
  15309. }
  15310. this.inertialPanningX *= this.inertia;
  15311. this.inertialPanningY *= this.inertia;
  15312. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15313. this.inertialPanningX = 0;
  15314. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15315. this.inertialPanningY = 0;
  15316. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15317. this._localDirection.multiplyInPlace(this.panningAxis);
  15318. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15319. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15320. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15321. if (!this.panningAxis.y) {
  15322. this._transformedDirection.y = 0;
  15323. }
  15324. if (!this.target.getAbsolutePosition) {
  15325. this.target.addInPlace(this._transformedDirection);
  15326. }
  15327. }
  15328. // Limits
  15329. this._checkLimits();
  15330. _super.prototype._checkInputs.call(this);
  15331. };
  15332. ArcRotateCamera.prototype._checkLimits = function () {
  15333. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15334. if (this.allowUpsideDown && this.beta > Math.PI) {
  15335. this.beta = this.beta - (2 * Math.PI);
  15336. }
  15337. }
  15338. else {
  15339. if (this.beta < this.lowerBetaLimit) {
  15340. this.beta = this.lowerBetaLimit;
  15341. }
  15342. }
  15343. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15344. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15345. this.beta = this.beta + (2 * Math.PI);
  15346. }
  15347. }
  15348. else {
  15349. if (this.beta > this.upperBetaLimit) {
  15350. this.beta = this.upperBetaLimit;
  15351. }
  15352. }
  15353. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15354. this.alpha = this.lowerAlphaLimit;
  15355. }
  15356. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15357. this.alpha = this.upperAlphaLimit;
  15358. }
  15359. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15360. this.radius = this.lowerRadiusLimit;
  15361. }
  15362. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15363. this.radius = this.upperRadiusLimit;
  15364. }
  15365. };
  15366. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15367. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15368. this.radius = radiusv3.length();
  15369. // Alpha
  15370. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15371. if (radiusv3.z < 0) {
  15372. this.alpha = 2 * Math.PI - this.alpha;
  15373. }
  15374. // Beta
  15375. this.beta = Math.acos(radiusv3.y / this.radius);
  15376. this._checkLimits();
  15377. };
  15378. ArcRotateCamera.prototype.setPosition = function (position) {
  15379. if (this.position.equals(position)) {
  15380. return;
  15381. }
  15382. this.position.copyFrom(position);
  15383. this.rebuildAnglesAndRadius();
  15384. };
  15385. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15386. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15387. if (this._getTargetPosition().equals(target)) {
  15388. return;
  15389. }
  15390. if (toBoundingCenter && target.getBoundingInfo) {
  15391. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15392. }
  15393. else {
  15394. this._targetBoundingCenter = null;
  15395. }
  15396. this.target = target;
  15397. this.rebuildAnglesAndRadius();
  15398. };
  15399. ArcRotateCamera.prototype._getViewMatrix = function () {
  15400. // Compute
  15401. var cosa = Math.cos(this.alpha);
  15402. var sina = Math.sin(this.alpha);
  15403. var cosb = Math.cos(this.beta);
  15404. var sinb = Math.sin(this.beta);
  15405. if (sinb === 0) {
  15406. sinb = 0.0001;
  15407. }
  15408. var target = this._getTargetPosition();
  15409. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15410. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15411. this._collider.radius = this.collisionRadius;
  15412. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15413. this._collisionTriggered = true;
  15414. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15415. }
  15416. else {
  15417. this.position.copyFrom(this._newPosition);
  15418. var up = this.upVector;
  15419. if (this.allowUpsideDown && this.beta < 0) {
  15420. up = up.clone();
  15421. up = up.negate();
  15422. }
  15423. if (this.getScene().useRightHandedSystem) {
  15424. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15425. }
  15426. else {
  15427. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15428. }
  15429. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15430. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15431. }
  15432. return this._viewMatrix;
  15433. };
  15434. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15435. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15436. meshes = meshes || this.getScene().meshes;
  15437. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15438. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15439. this.radius = distance * this.zoomOnFactor;
  15440. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15441. };
  15442. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15443. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15444. var meshesOrMinMaxVector;
  15445. var distance;
  15446. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15447. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15448. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15449. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15450. }
  15451. else {
  15452. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15453. distance = meshesOrMinMaxVectorAndDistance.distance;
  15454. }
  15455. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15456. if (!doNotUpdateMaxZ) {
  15457. this.maxZ = distance * 2;
  15458. }
  15459. };
  15460. /**
  15461. * @override
  15462. * Override Camera.createRigCamera
  15463. */
  15464. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15465. var alphaShift;
  15466. switch (this.cameraRigMode) {
  15467. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15468. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15469. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15470. case BABYLON.Camera.RIG_MODE_VR:
  15471. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15472. break;
  15473. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15474. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15475. break;
  15476. }
  15477. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15478. rigCam._cameraRigParams = {};
  15479. return rigCam;
  15480. };
  15481. /**
  15482. * @override
  15483. * Override Camera._updateRigCameras
  15484. */
  15485. ArcRotateCamera.prototype._updateRigCameras = function () {
  15486. var camLeft = this._rigCameras[0];
  15487. var camRight = this._rigCameras[1];
  15488. camLeft.beta = camRight.beta = this.beta;
  15489. camLeft.radius = camRight.radius = this.radius;
  15490. switch (this.cameraRigMode) {
  15491. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15492. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15493. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15494. case BABYLON.Camera.RIG_MODE_VR:
  15495. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15496. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15497. break;
  15498. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15499. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15500. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15501. break;
  15502. }
  15503. _super.prototype._updateRigCameras.call(this);
  15504. };
  15505. ArcRotateCamera.prototype.dispose = function () {
  15506. this.inputs.clear();
  15507. _super.prototype.dispose.call(this);
  15508. };
  15509. ArcRotateCamera.prototype.getTypeName = function () {
  15510. return "ArcRotateCamera";
  15511. };
  15512. __decorate([
  15513. BABYLON.serialize()
  15514. ], ArcRotateCamera.prototype, "alpha", void 0);
  15515. __decorate([
  15516. BABYLON.serialize()
  15517. ], ArcRotateCamera.prototype, "beta", void 0);
  15518. __decorate([
  15519. BABYLON.serialize()
  15520. ], ArcRotateCamera.prototype, "radius", void 0);
  15521. __decorate([
  15522. BABYLON.serializeAsVector3()
  15523. ], ArcRotateCamera.prototype, "target", void 0);
  15524. __decorate([
  15525. BABYLON.serialize()
  15526. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15527. __decorate([
  15528. BABYLON.serialize()
  15529. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15530. __decorate([
  15531. BABYLON.serialize()
  15532. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15533. __decorate([
  15534. BABYLON.serialize()
  15535. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15536. __decorate([
  15537. BABYLON.serialize()
  15538. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15539. __decorate([
  15540. BABYLON.serialize()
  15541. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15542. __decorate([
  15543. BABYLON.serialize()
  15544. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15545. __decorate([
  15546. BABYLON.serialize()
  15547. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15548. __decorate([
  15549. BABYLON.serialize()
  15550. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15551. __decorate([
  15552. BABYLON.serialize()
  15553. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15554. __decorate([
  15555. BABYLON.serialize()
  15556. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15557. __decorate([
  15558. BABYLON.serialize()
  15559. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15560. __decorate([
  15561. BABYLON.serialize()
  15562. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15563. return ArcRotateCamera;
  15564. }(BABYLON.TargetCamera));
  15565. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15566. })(BABYLON || (BABYLON = {}));
  15567. var BABYLON;
  15568. (function (BABYLON) {
  15569. var ArcRotateCameraInputsManager = (function (_super) {
  15570. __extends(ArcRotateCameraInputsManager, _super);
  15571. function ArcRotateCameraInputsManager(camera) {
  15572. _super.call(this, camera);
  15573. }
  15574. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15575. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15576. return this;
  15577. };
  15578. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15579. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15580. return this;
  15581. };
  15582. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15583. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15584. return this;
  15585. };
  15586. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15587. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15588. return this;
  15589. };
  15590. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15591. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15592. return this;
  15593. };
  15594. return ArcRotateCameraInputsManager;
  15595. }(BABYLON.CameraInputsManager));
  15596. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15597. })(BABYLON || (BABYLON = {}));
  15598. var BABYLON;
  15599. (function (BABYLON) {
  15600. var RenderingManager = (function () {
  15601. function RenderingManager(scene) {
  15602. this._renderingGroups = new Array();
  15603. this._autoClearDepthStencil = {};
  15604. this._customOpaqueSortCompareFn = {};
  15605. this._customAlphaTestSortCompareFn = {};
  15606. this._customTransparentSortCompareFn = {};
  15607. this._scene = scene;
  15608. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15609. this._autoClearDepthStencil[i] = true;
  15610. }
  15611. }
  15612. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15613. if (this._scene._activeParticleSystems.length === 0) {
  15614. return;
  15615. }
  15616. // Particles
  15617. var activeCamera = this._scene.activeCamera;
  15618. this._scene._particlesDuration.beginMonitoring();
  15619. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15620. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15621. if (particleSystem.renderingGroupId !== index) {
  15622. continue;
  15623. }
  15624. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15625. continue;
  15626. }
  15627. this._clearDepthStencilBuffer();
  15628. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15629. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15630. }
  15631. }
  15632. this._scene._particlesDuration.endMonitoring(false);
  15633. };
  15634. RenderingManager.prototype._renderSprites = function (index) {
  15635. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15636. return;
  15637. }
  15638. // Sprites
  15639. var activeCamera = this._scene.activeCamera;
  15640. this._scene._spritesDuration.beginMonitoring();
  15641. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15642. var spriteManager = this._scene.spriteManagers[id];
  15643. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15644. this._clearDepthStencilBuffer();
  15645. spriteManager.render();
  15646. }
  15647. }
  15648. this._scene._spritesDuration.endMonitoring(false);
  15649. };
  15650. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15651. if (this._depthStencilBufferAlreadyCleaned) {
  15652. return;
  15653. }
  15654. this._scene.getEngine().clear(0, false, true, true);
  15655. this._depthStencilBufferAlreadyCleaned = true;
  15656. };
  15657. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15658. if (this._currentRenderSprites) {
  15659. this._renderSprites(this._currentIndex);
  15660. }
  15661. if (this._currentRenderParticles) {
  15662. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15663. }
  15664. };
  15665. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15666. this._currentActiveMeshes = activeMeshes;
  15667. this._currentRenderParticles = renderParticles;
  15668. this._currentRenderSprites = renderSprites;
  15669. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15670. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15671. var renderingGroup = this._renderingGroups[index];
  15672. var needToStepBack = false;
  15673. this._currentIndex = index;
  15674. if (renderingGroup) {
  15675. if (this._autoClearDepthStencil[index]) {
  15676. this._clearDepthStencilBuffer();
  15677. }
  15678. if (!renderingGroup.onBeforeTransparentRendering) {
  15679. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15680. }
  15681. if (!renderingGroup.render(customRenderFunction)) {
  15682. this._renderingGroups.splice(index, 1);
  15683. needToStepBack = true;
  15684. this._renderSpritesAndParticles();
  15685. }
  15686. }
  15687. else {
  15688. this._renderSpritesAndParticles();
  15689. }
  15690. if (needToStepBack) {
  15691. index--;
  15692. }
  15693. }
  15694. };
  15695. RenderingManager.prototype.reset = function () {
  15696. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15697. var renderingGroup = this._renderingGroups[index];
  15698. if (renderingGroup) {
  15699. renderingGroup.prepare();
  15700. }
  15701. }
  15702. };
  15703. RenderingManager.prototype.dispatch = function (subMesh) {
  15704. var mesh = subMesh.getMesh();
  15705. var renderingGroupId = mesh.renderingGroupId || 0;
  15706. if (!this._renderingGroups[renderingGroupId]) {
  15707. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15708. }
  15709. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15710. };
  15711. /**
  15712. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15713. * This allowed control for front to back rendering or reversly depending of the special needs.
  15714. *
  15715. * @param renderingGroupId The rendering group id corresponding to its index
  15716. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15717. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15718. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15719. */
  15720. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15721. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15722. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15723. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15724. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15725. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15726. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15727. if (this._renderingGroups[renderingGroupId]) {
  15728. var group = this._renderingGroups[renderingGroupId];
  15729. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15730. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15731. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15732. }
  15733. };
  15734. /**
  15735. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15736. *
  15737. * @param renderingGroupId The rendering group id corresponding to its index
  15738. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15739. */
  15740. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15741. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15742. };
  15743. /**
  15744. * The max id used for rendering groups (not included)
  15745. */
  15746. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15747. /**
  15748. * The min id used for rendering groups (included)
  15749. */
  15750. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15751. return RenderingManager;
  15752. }());
  15753. BABYLON.RenderingManager = RenderingManager;
  15754. })(BABYLON || (BABYLON = {}));
  15755. var BABYLON;
  15756. (function (BABYLON) {
  15757. var RenderingGroup = (function () {
  15758. /**
  15759. * Creates a new rendering group.
  15760. * @param index The rendering group index
  15761. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15762. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15763. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15764. */
  15765. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15766. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15767. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15768. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15769. this.index = index;
  15770. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15771. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15772. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15773. this._scene = scene;
  15774. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15775. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15776. this.transparentSortCompareFn = transparentSortCompareFn;
  15777. }
  15778. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15779. /**
  15780. * Set the opaque sort comparison function.
  15781. * If null the sub meshes will be render in the order they were created
  15782. */
  15783. set: function (value) {
  15784. this._opaqueSortCompareFn = value;
  15785. if (value) {
  15786. this._renderOpaque = this.renderOpaqueSorted;
  15787. }
  15788. else {
  15789. this._renderOpaque = RenderingGroup.renderUnsorted;
  15790. }
  15791. },
  15792. enumerable: true,
  15793. configurable: true
  15794. });
  15795. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15796. /**
  15797. * Set the alpha test sort comparison function.
  15798. * If null the sub meshes will be render in the order they were created
  15799. */
  15800. set: function (value) {
  15801. this._alphaTestSortCompareFn = value;
  15802. if (value) {
  15803. this._renderAlphaTest = this.renderAlphaTestSorted;
  15804. }
  15805. else {
  15806. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15807. }
  15808. },
  15809. enumerable: true,
  15810. configurable: true
  15811. });
  15812. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15813. /**
  15814. * Set the transparent sort comparison function.
  15815. * If null the sub meshes will be render in the order they were created
  15816. */
  15817. set: function (value) {
  15818. if (value) {
  15819. this._transparentSortCompareFn = value;
  15820. }
  15821. else {
  15822. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15823. }
  15824. this._renderTransparent = this.renderTransparentSorted;
  15825. },
  15826. enumerable: true,
  15827. configurable: true
  15828. });
  15829. /**
  15830. * Render all the sub meshes contained in the group.
  15831. * @param customRenderFunction Used to override the default render behaviour of the group.
  15832. * @returns true if rendered some submeshes.
  15833. */
  15834. RenderingGroup.prototype.render = function (customRenderFunction) {
  15835. if (customRenderFunction) {
  15836. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15837. return true;
  15838. }
  15839. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15840. if (this.onBeforeTransparentRendering) {
  15841. this.onBeforeTransparentRendering();
  15842. }
  15843. return false;
  15844. }
  15845. var engine = this._scene.getEngine();
  15846. // Opaque
  15847. this._renderOpaque(this._opaqueSubMeshes);
  15848. // Alpha test
  15849. engine.setAlphaTesting(true);
  15850. this._renderAlphaTest(this._alphaTestSubMeshes);
  15851. engine.setAlphaTesting(false);
  15852. if (this.onBeforeTransparentRendering) {
  15853. this.onBeforeTransparentRendering();
  15854. }
  15855. // Transparent
  15856. this._renderTransparent(this._transparentSubMeshes);
  15857. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15858. return true;
  15859. };
  15860. /**
  15861. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15862. * @param subMeshes The submeshes to render
  15863. */
  15864. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15865. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15866. };
  15867. /**
  15868. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15869. * @param subMeshes The submeshes to render
  15870. */
  15871. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15872. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15873. };
  15874. /**
  15875. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15876. * @param subMeshes The submeshes to render
  15877. */
  15878. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15879. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15880. };
  15881. /**
  15882. * Renders the submeshes in a specified order.
  15883. * @param subMeshes The submeshes to sort before render
  15884. * @param sortCompareFn The comparison function use to sort
  15885. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15886. * @param transparent Specifies to activate blending if true
  15887. */
  15888. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15889. var subIndex = 0;
  15890. var subMesh;
  15891. for (; subIndex < subMeshes.length; subIndex++) {
  15892. subMesh = subMeshes.data[subIndex];
  15893. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15894. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15895. }
  15896. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15897. sortedArray.sort(sortCompareFn);
  15898. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15899. subMesh = sortedArray[subIndex];
  15900. subMesh.render(transparent);
  15901. }
  15902. };
  15903. /**
  15904. * Renders the submeshes in the order they were dispatched (no sort applied).
  15905. * @param subMeshes The submeshes to render
  15906. */
  15907. RenderingGroup.renderUnsorted = function (subMeshes) {
  15908. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15909. var submesh = subMeshes.data[subIndex];
  15910. submesh.render(false);
  15911. }
  15912. };
  15913. /**
  15914. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15915. * are rendered back to front if in the same alpha index.
  15916. *
  15917. * @param a The first submesh
  15918. * @param b The second submesh
  15919. * @returns The result of the comparison
  15920. */
  15921. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15922. // Alpha index first
  15923. if (a._alphaIndex > b._alphaIndex) {
  15924. return 1;
  15925. }
  15926. if (a._alphaIndex < b._alphaIndex) {
  15927. return -1;
  15928. }
  15929. // Then distance to camera
  15930. return RenderingGroup.backToFrontSortCompare(a, b);
  15931. };
  15932. /**
  15933. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15934. * are rendered back to front.
  15935. *
  15936. * @param a The first submesh
  15937. * @param b The second submesh
  15938. * @returns The result of the comparison
  15939. */
  15940. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15941. // Then distance to camera
  15942. if (a._distanceToCamera < b._distanceToCamera) {
  15943. return 1;
  15944. }
  15945. if (a._distanceToCamera > b._distanceToCamera) {
  15946. return -1;
  15947. }
  15948. return 0;
  15949. };
  15950. /**
  15951. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15952. * are rendered front to back (prevent overdraw).
  15953. *
  15954. * @param a The first submesh
  15955. * @param b The second submesh
  15956. * @returns The result of the comparison
  15957. */
  15958. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15959. // Then distance to camera
  15960. if (a._distanceToCamera < b._distanceToCamera) {
  15961. return -1;
  15962. }
  15963. if (a._distanceToCamera > b._distanceToCamera) {
  15964. return 1;
  15965. }
  15966. return 0;
  15967. };
  15968. /**
  15969. * Resets the different lists of submeshes to prepare a new frame.
  15970. */
  15971. RenderingGroup.prototype.prepare = function () {
  15972. this._opaqueSubMeshes.reset();
  15973. this._transparentSubMeshes.reset();
  15974. this._alphaTestSubMeshes.reset();
  15975. };
  15976. /**
  15977. * Inserts the submesh in its correct queue depending on its material.
  15978. * @param subMesh The submesh to dispatch
  15979. */
  15980. RenderingGroup.prototype.dispatch = function (subMesh) {
  15981. var material = subMesh.getMaterial();
  15982. var mesh = subMesh.getMesh();
  15983. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15984. this._transparentSubMeshes.push(subMesh);
  15985. }
  15986. else if (material.needAlphaTesting()) {
  15987. this._alphaTestSubMeshes.push(subMesh);
  15988. }
  15989. else {
  15990. this._opaqueSubMeshes.push(subMesh); // Opaque
  15991. }
  15992. };
  15993. return RenderingGroup;
  15994. }());
  15995. BABYLON.RenderingGroup = RenderingGroup;
  15996. })(BABYLON || (BABYLON = {}));
  15997. var BABYLON;
  15998. (function (BABYLON) {
  15999. var PointerEventTypes = (function () {
  16000. function PointerEventTypes() {
  16001. }
  16002. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16003. get: function () {
  16004. return PointerEventTypes._POINTERDOWN;
  16005. },
  16006. enumerable: true,
  16007. configurable: true
  16008. });
  16009. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16010. get: function () {
  16011. return PointerEventTypes._POINTERUP;
  16012. },
  16013. enumerable: true,
  16014. configurable: true
  16015. });
  16016. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16017. get: function () {
  16018. return PointerEventTypes._POINTERMOVE;
  16019. },
  16020. enumerable: true,
  16021. configurable: true
  16022. });
  16023. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16024. get: function () {
  16025. return PointerEventTypes._POINTERWHEEL;
  16026. },
  16027. enumerable: true,
  16028. configurable: true
  16029. });
  16030. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16031. get: function () {
  16032. return PointerEventTypes._POINTERPICK;
  16033. },
  16034. enumerable: true,
  16035. configurable: true
  16036. });
  16037. PointerEventTypes._POINTERDOWN = 0x01;
  16038. PointerEventTypes._POINTERUP = 0x02;
  16039. PointerEventTypes._POINTERMOVE = 0x04;
  16040. PointerEventTypes._POINTERWHEEL = 0x08;
  16041. PointerEventTypes._POINTERPICK = 0x10;
  16042. return PointerEventTypes;
  16043. }());
  16044. BABYLON.PointerEventTypes = PointerEventTypes;
  16045. var PointerInfoBase = (function () {
  16046. function PointerInfoBase(type, event) {
  16047. this.type = type;
  16048. this.event = event;
  16049. }
  16050. return PointerInfoBase;
  16051. }());
  16052. BABYLON.PointerInfoBase = PointerInfoBase;
  16053. /**
  16054. * This class is used to store pointer related info for the onPrePointerObservable event.
  16055. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16056. */
  16057. var PointerInfoPre = (function (_super) {
  16058. __extends(PointerInfoPre, _super);
  16059. function PointerInfoPre(type, event, localX, localY) {
  16060. _super.call(this, type, event);
  16061. this.skipOnPointerObservable = false;
  16062. this.localPosition = new BABYLON.Vector2(localX, localY);
  16063. }
  16064. return PointerInfoPre;
  16065. }(PointerInfoBase));
  16066. BABYLON.PointerInfoPre = PointerInfoPre;
  16067. /**
  16068. * This type contains all the data related to a pointer event in Babylon.js.
  16069. * 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.
  16070. */
  16071. var PointerInfo = (function (_super) {
  16072. __extends(PointerInfo, _super);
  16073. function PointerInfo(type, event, pickInfo) {
  16074. _super.call(this, type, event);
  16075. this.pickInfo = pickInfo;
  16076. }
  16077. return PointerInfo;
  16078. }(PointerInfoBase));
  16079. BABYLON.PointerInfo = PointerInfo;
  16080. /**
  16081. * Represents a scene to be rendered by the engine.
  16082. * @see http://doc.babylonjs.com/page.php?p=21911
  16083. */
  16084. var Scene = (function () {
  16085. /**
  16086. * @constructor
  16087. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16088. */
  16089. function Scene(engine) {
  16090. // Members
  16091. this.autoClear = true;
  16092. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16093. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16094. this.forceWireframe = false;
  16095. this.forcePointsCloud = false;
  16096. this.forceShowBoundingBoxes = false;
  16097. this.animationsEnabled = true;
  16098. this.constantlyUpdateMeshUnderPointer = false;
  16099. this.useRightHandedSystem = false;
  16100. this.hoverCursor = "pointer";
  16101. // Events
  16102. /**
  16103. * An event triggered when the scene is disposed.
  16104. * @type {BABYLON.Observable}
  16105. */
  16106. this.onDisposeObservable = new BABYLON.Observable();
  16107. /**
  16108. * An event triggered before rendering the scene
  16109. * @type {BABYLON.Observable}
  16110. */
  16111. this.onBeforeRenderObservable = new BABYLON.Observable();
  16112. /**
  16113. * An event triggered after rendering the scene
  16114. * @type {BABYLON.Observable}
  16115. */
  16116. this.onAfterRenderObservable = new BABYLON.Observable();
  16117. /**
  16118. * An event triggered when the scene is ready
  16119. * @type {BABYLON.Observable}
  16120. */
  16121. this.onReadyObservable = new BABYLON.Observable();
  16122. /**
  16123. * An event triggered before rendering a camera
  16124. * @type {BABYLON.Observable}
  16125. */
  16126. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16127. /**
  16128. * An event triggered after rendering a camera
  16129. * @type {BABYLON.Observable}
  16130. */
  16131. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16132. /**
  16133. * An event triggered when a camera is created
  16134. * @type {BABYLON.Observable}
  16135. */
  16136. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16137. /**
  16138. * An event triggered when a camera is removed
  16139. * @type {BABYLON.Observable}
  16140. */
  16141. this.onCameraRemovedObservable = new BABYLON.Observable();
  16142. /**
  16143. * An event triggered when a light is created
  16144. * @type {BABYLON.Observable}
  16145. */
  16146. this.onNewLightAddedObservable = new BABYLON.Observable();
  16147. /**
  16148. * An event triggered when a light is removed
  16149. * @type {BABYLON.Observable}
  16150. */
  16151. this.onLightRemovedObservable = new BABYLON.Observable();
  16152. /**
  16153. * An event triggered when a geometry is created
  16154. * @type {BABYLON.Observable}
  16155. */
  16156. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16157. /**
  16158. * An event triggered when a geometry is removed
  16159. * @type {BABYLON.Observable}
  16160. */
  16161. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16162. /**
  16163. * An event triggered when a mesh is created
  16164. * @type {BABYLON.Observable}
  16165. */
  16166. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16167. /**
  16168. * An event triggered when a mesh is removed
  16169. * @type {BABYLON.Observable}
  16170. */
  16171. this.onMeshRemovedObservable = new BABYLON.Observable();
  16172. // Animations
  16173. this.animations = [];
  16174. /**
  16175. * 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).
  16176. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16177. */
  16178. this.onPrePointerObservable = new BABYLON.Observable();
  16179. /**
  16180. * Observable event triggered each time an input event is received from the rendering canvas
  16181. */
  16182. this.onPointerObservable = new BABYLON.Observable();
  16183. 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
  16184. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16185. this._startingPointerTime = 0;
  16186. // Fog
  16187. /**
  16188. * is fog enabled on this scene.
  16189. * @type {boolean}
  16190. */
  16191. this.fogEnabled = true;
  16192. this.fogMode = Scene.FOGMODE_NONE;
  16193. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16194. this.fogDensity = 0.1;
  16195. this.fogStart = 0;
  16196. this.fogEnd = 1000.0;
  16197. // Lights
  16198. /**
  16199. * is shadow enabled on this scene.
  16200. * @type {boolean}
  16201. */
  16202. this.shadowsEnabled = true;
  16203. /**
  16204. * is light enabled on this scene.
  16205. * @type {boolean}
  16206. */
  16207. this.lightsEnabled = true;
  16208. /**
  16209. * All of the lights added to this scene.
  16210. * @see BABYLON.Light
  16211. * @type {BABYLON.Light[]}
  16212. */
  16213. this.lights = new Array();
  16214. // Cameras
  16215. /**
  16216. * All of the cameras added to this scene.
  16217. * @see BABYLON.Camera
  16218. * @type {BABYLON.Camera[]}
  16219. */
  16220. this.cameras = new Array();
  16221. this.activeCameras = new Array();
  16222. // Meshes
  16223. /**
  16224. * All of the (abstract) meshes added to this scene.
  16225. * @see BABYLON.AbstractMesh
  16226. * @type {BABYLON.AbstractMesh[]}
  16227. */
  16228. this.meshes = new Array();
  16229. // Geometries
  16230. this._geometries = new Array();
  16231. this.materials = new Array();
  16232. this.multiMaterials = new Array();
  16233. // Textures
  16234. this.texturesEnabled = true;
  16235. this.textures = new Array();
  16236. // Particles
  16237. this.particlesEnabled = true;
  16238. this.particleSystems = new Array();
  16239. // Sprites
  16240. this.spritesEnabled = true;
  16241. this.spriteManagers = new Array();
  16242. // Layers
  16243. this.layers = new Array();
  16244. this.highlightLayers = new Array();
  16245. // Skeletons
  16246. this.skeletonsEnabled = true;
  16247. this.skeletons = new Array();
  16248. // Lens flares
  16249. this.lensFlaresEnabled = true;
  16250. this.lensFlareSystems = new Array();
  16251. // Collisions
  16252. this.collisionsEnabled = true;
  16253. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16254. // Postprocesses
  16255. this.postProcessesEnabled = true;
  16256. // Customs render targets
  16257. this.renderTargetsEnabled = true;
  16258. this.dumpNextRenderTargets = false;
  16259. this.customRenderTargets = new Array();
  16260. // Imported meshes
  16261. this.importedMeshesFiles = new Array();
  16262. // Probes
  16263. this.probesEnabled = true;
  16264. this.reflectionProbes = new Array();
  16265. this._actionManagers = new Array();
  16266. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16267. // Procedural textures
  16268. this.proceduralTexturesEnabled = true;
  16269. this._proceduralTextures = new Array();
  16270. this.soundTracks = new Array();
  16271. this._audioEnabled = true;
  16272. this._headphone = false;
  16273. // Performance counters
  16274. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16275. this._totalLightsCounter = new BABYLON.PerfCounter();
  16276. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16277. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16278. this._totalVertices = new BABYLON.PerfCounter();
  16279. this._activeIndices = new BABYLON.PerfCounter();
  16280. this._activeParticles = new BABYLON.PerfCounter();
  16281. this._lastFrameDuration = new BABYLON.PerfCounter();
  16282. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16283. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16284. this._particlesDuration = new BABYLON.PerfCounter();
  16285. this._renderDuration = new BABYLON.PerfCounter();
  16286. this._spritesDuration = new BABYLON.PerfCounter();
  16287. this._activeBones = new BABYLON.PerfCounter();
  16288. this._renderId = 0;
  16289. this._executeWhenReadyTimeoutId = -1;
  16290. this._intermediateRendering = false;
  16291. this._toBeDisposed = new BABYLON.SmartArray(256);
  16292. this._pendingData = []; //ANY
  16293. this._activeMeshes = new BABYLON.SmartArray(256);
  16294. this._processedMaterials = new BABYLON.SmartArray(256);
  16295. this._renderTargets = new BABYLON.SmartArray(256);
  16296. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16297. this._activeSkeletons = new BABYLON.SmartArray(32);
  16298. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16299. this._activeAnimatables = new Array();
  16300. this._transformMatrix = BABYLON.Matrix.Zero();
  16301. this._edgesRenderers = new BABYLON.SmartArray(16);
  16302. this._uniqueIdCounter = 0;
  16303. this._engine = engine;
  16304. engine.scenes.push(this);
  16305. this._renderingManager = new BABYLON.RenderingManager(this);
  16306. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16307. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16308. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16309. if (BABYLON.OutlineRenderer) {
  16310. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16311. }
  16312. this.attachControl();
  16313. if (BABYLON.SoundTrack) {
  16314. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16315. }
  16316. //simplification queue
  16317. if (BABYLON.SimplificationQueue) {
  16318. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16319. }
  16320. //collision coordinator initialization. For now legacy per default.
  16321. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16322. }
  16323. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16324. get: function () {
  16325. return Scene._FOGMODE_NONE;
  16326. },
  16327. enumerable: true,
  16328. configurable: true
  16329. });
  16330. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16331. get: function () {
  16332. return Scene._FOGMODE_EXP;
  16333. },
  16334. enumerable: true,
  16335. configurable: true
  16336. });
  16337. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16338. get: function () {
  16339. return Scene._FOGMODE_EXP2;
  16340. },
  16341. enumerable: true,
  16342. configurable: true
  16343. });
  16344. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16345. get: function () {
  16346. return Scene._FOGMODE_LINEAR;
  16347. },
  16348. enumerable: true,
  16349. configurable: true
  16350. });
  16351. Object.defineProperty(Scene.prototype, "onDispose", {
  16352. set: function (callback) {
  16353. if (this._onDisposeObserver) {
  16354. this.onDisposeObservable.remove(this._onDisposeObserver);
  16355. }
  16356. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16357. },
  16358. enumerable: true,
  16359. configurable: true
  16360. });
  16361. Object.defineProperty(Scene.prototype, "beforeRender", {
  16362. set: function (callback) {
  16363. if (this._onBeforeRenderObserver) {
  16364. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16365. }
  16366. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16367. },
  16368. enumerable: true,
  16369. configurable: true
  16370. });
  16371. Object.defineProperty(Scene.prototype, "afterRender", {
  16372. set: function (callback) {
  16373. if (this._onAfterRenderObserver) {
  16374. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16375. }
  16376. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16377. },
  16378. enumerable: true,
  16379. configurable: true
  16380. });
  16381. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16382. set: function (callback) {
  16383. if (this._onBeforeCameraRenderObserver) {
  16384. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16385. }
  16386. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16387. },
  16388. enumerable: true,
  16389. configurable: true
  16390. });
  16391. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16392. set: function (callback) {
  16393. if (this._onAfterCameraRenderObserver) {
  16394. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16395. }
  16396. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16397. },
  16398. enumerable: true,
  16399. configurable: true
  16400. });
  16401. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16402. get: function () {
  16403. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16404. },
  16405. enumerable: true,
  16406. configurable: true
  16407. });
  16408. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16409. get: function () {
  16410. if (!this._defaultMaterial) {
  16411. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16412. }
  16413. return this._defaultMaterial;
  16414. },
  16415. enumerable: true,
  16416. configurable: true
  16417. });
  16418. Object.defineProperty(Scene.prototype, "debugLayer", {
  16419. // Properties
  16420. get: function () {
  16421. if (!this._debugLayer) {
  16422. this._debugLayer = new BABYLON.DebugLayer(this);
  16423. }
  16424. return this._debugLayer;
  16425. },
  16426. enumerable: true,
  16427. configurable: true
  16428. });
  16429. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16430. get: function () {
  16431. return this._workerCollisions;
  16432. },
  16433. set: function (enabled) {
  16434. enabled = (enabled && !!Worker);
  16435. this._workerCollisions = enabled;
  16436. if (this.collisionCoordinator) {
  16437. this.collisionCoordinator.destroy();
  16438. }
  16439. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16440. this.collisionCoordinator.init(this);
  16441. },
  16442. enumerable: true,
  16443. configurable: true
  16444. });
  16445. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16446. get: function () {
  16447. return this._selectionOctree;
  16448. },
  16449. enumerable: true,
  16450. configurable: true
  16451. });
  16452. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16453. /**
  16454. * The mesh that is currently under the pointer.
  16455. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16456. */
  16457. get: function () {
  16458. return this._pointerOverMesh;
  16459. },
  16460. enumerable: true,
  16461. configurable: true
  16462. });
  16463. Object.defineProperty(Scene.prototype, "pointerX", {
  16464. /**
  16465. * Current on-screen X position of the pointer
  16466. * @return {number} X position of the pointer
  16467. */
  16468. get: function () {
  16469. return this._pointerX;
  16470. },
  16471. enumerable: true,
  16472. configurable: true
  16473. });
  16474. Object.defineProperty(Scene.prototype, "pointerY", {
  16475. /**
  16476. * Current on-screen Y position of the pointer
  16477. * @return {number} Y position of the pointer
  16478. */
  16479. get: function () {
  16480. return this._pointerY;
  16481. },
  16482. enumerable: true,
  16483. configurable: true
  16484. });
  16485. Scene.prototype.getCachedMaterial = function () {
  16486. return this._cachedMaterial;
  16487. };
  16488. Scene.prototype.getBoundingBoxRenderer = function () {
  16489. return this._boundingBoxRenderer;
  16490. };
  16491. Scene.prototype.getOutlineRenderer = function () {
  16492. return this._outlineRenderer;
  16493. };
  16494. Scene.prototype.getEngine = function () {
  16495. return this._engine;
  16496. };
  16497. Scene.prototype.getTotalVertices = function () {
  16498. return this._totalVertices.current;
  16499. };
  16500. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16501. get: function () {
  16502. return this._totalVertices;
  16503. },
  16504. enumerable: true,
  16505. configurable: true
  16506. });
  16507. Scene.prototype.getActiveIndices = function () {
  16508. return this._activeIndices.current;
  16509. };
  16510. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16511. get: function () {
  16512. return this._activeIndices;
  16513. },
  16514. enumerable: true,
  16515. configurable: true
  16516. });
  16517. Scene.prototype.getActiveParticles = function () {
  16518. return this._activeParticles.current;
  16519. };
  16520. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16521. get: function () {
  16522. return this._activeParticles;
  16523. },
  16524. enumerable: true,
  16525. configurable: true
  16526. });
  16527. Scene.prototype.getActiveBones = function () {
  16528. return this._activeBones.current;
  16529. };
  16530. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16531. get: function () {
  16532. return this._activeBones;
  16533. },
  16534. enumerable: true,
  16535. configurable: true
  16536. });
  16537. // Stats
  16538. Scene.prototype.getLastFrameDuration = function () {
  16539. return this._lastFrameDuration.current;
  16540. };
  16541. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16542. get: function () {
  16543. return this._lastFrameDuration;
  16544. },
  16545. enumerable: true,
  16546. configurable: true
  16547. });
  16548. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16549. return this._evaluateActiveMeshesDuration.current;
  16550. };
  16551. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16552. get: function () {
  16553. return this._evaluateActiveMeshesDuration;
  16554. },
  16555. enumerable: true,
  16556. configurable: true
  16557. });
  16558. Scene.prototype.getActiveMeshes = function () {
  16559. return this._activeMeshes;
  16560. };
  16561. Scene.prototype.getRenderTargetsDuration = function () {
  16562. return this._renderTargetsDuration.current;
  16563. };
  16564. Scene.prototype.getRenderDuration = function () {
  16565. return this._renderDuration.current;
  16566. };
  16567. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16568. get: function () {
  16569. return this._renderDuration;
  16570. },
  16571. enumerable: true,
  16572. configurable: true
  16573. });
  16574. Scene.prototype.getParticlesDuration = function () {
  16575. return this._particlesDuration.current;
  16576. };
  16577. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16578. get: function () {
  16579. return this._particlesDuration;
  16580. },
  16581. enumerable: true,
  16582. configurable: true
  16583. });
  16584. Scene.prototype.getSpritesDuration = function () {
  16585. return this._spritesDuration.current;
  16586. };
  16587. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16588. get: function () {
  16589. return this._spritesDuration;
  16590. },
  16591. enumerable: true,
  16592. configurable: true
  16593. });
  16594. Scene.prototype.getAnimationRatio = function () {
  16595. return this._animationRatio;
  16596. };
  16597. Scene.prototype.getRenderId = function () {
  16598. return this._renderId;
  16599. };
  16600. Scene.prototype.incrementRenderId = function () {
  16601. this._renderId++;
  16602. };
  16603. Scene.prototype._updatePointerPosition = function (evt) {
  16604. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16605. this._pointerX = evt.clientX - canvasRect.left;
  16606. this._pointerY = evt.clientY - canvasRect.top;
  16607. this._unTranslatedPointerX = this._pointerX;
  16608. this._unTranslatedPointerY = this._pointerY;
  16609. if (this.cameraToUseForPointers) {
  16610. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16611. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16612. }
  16613. };
  16614. // Pointers handling
  16615. /**
  16616. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16617. * @param attachUp defines if you want to attach events to pointerup
  16618. * @param attachDown defines if you want to attach events to pointerdown
  16619. * @param attachMove defines if you want to attach events to pointermove
  16620. */
  16621. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16622. var _this = this;
  16623. if (attachUp === void 0) { attachUp = true; }
  16624. if (attachDown === void 0) { attachDown = true; }
  16625. if (attachMove === void 0) { attachMove = true; }
  16626. var spritePredicate = function (sprite) {
  16627. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16628. };
  16629. this._onPointerMove = function (evt) {
  16630. _this._updatePointerPosition(evt);
  16631. // PreObservable support
  16632. if (_this.onPrePointerObservable.hasObservers()) {
  16633. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16634. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16635. _this.onPrePointerObservable.notifyObservers(pi, type);
  16636. if (pi.skipOnPointerObservable) {
  16637. return;
  16638. }
  16639. }
  16640. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16641. return;
  16642. }
  16643. var canvas = _this._engine.getRenderingCanvas();
  16644. if (!_this.pointerMovePredicate) {
  16645. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16646. }
  16647. // Meshes
  16648. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16649. if (pickResult.hit && pickResult.pickedMesh) {
  16650. _this.setPointerOverSprite(null);
  16651. _this.setPointerOverMesh(pickResult.pickedMesh);
  16652. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16653. canvas.style.cursor = _this.hoverCursor;
  16654. }
  16655. else {
  16656. canvas.style.cursor = "";
  16657. }
  16658. }
  16659. else {
  16660. _this.setPointerOverMesh(null);
  16661. // Sprites
  16662. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16663. if (pickResult.hit && pickResult.pickedSprite) {
  16664. canvas.style.cursor = _this.hoverCursor;
  16665. _this.setPointerOverSprite(pickResult.pickedSprite);
  16666. }
  16667. else {
  16668. _this.setPointerOverSprite(null);
  16669. // Restore pointer
  16670. canvas.style.cursor = "";
  16671. }
  16672. }
  16673. if (_this.onPointerMove) {
  16674. _this.onPointerMove(evt, pickResult);
  16675. }
  16676. if (_this.onPointerObservable.hasObservers()) {
  16677. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16678. var pi = new PointerInfo(type, evt, pickResult);
  16679. _this.onPointerObservable.notifyObservers(pi, type);
  16680. }
  16681. };
  16682. this._onPointerDown = function (evt) {
  16683. _this._updatePointerPosition(evt);
  16684. // PreObservable support
  16685. if (_this.onPrePointerObservable.hasObservers()) {
  16686. var type = PointerEventTypes.POINTERDOWN;
  16687. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16688. _this.onPrePointerObservable.notifyObservers(pi, type);
  16689. if (pi.skipOnPointerObservable) {
  16690. return;
  16691. }
  16692. }
  16693. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16694. return;
  16695. }
  16696. _this._startingPointerPosition.x = _this._pointerX;
  16697. _this._startingPointerPosition.y = _this._pointerY;
  16698. _this._startingPointerTime = new Date().getTime();
  16699. if (!_this.pointerDownPredicate) {
  16700. _this.pointerDownPredicate = function (mesh) {
  16701. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16702. };
  16703. }
  16704. // Meshes
  16705. _this._pickedDownMesh = null;
  16706. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16707. if (pickResult.hit && pickResult.pickedMesh) {
  16708. if (pickResult.pickedMesh.actionManager) {
  16709. _this._pickedDownMesh = pickResult.pickedMesh;
  16710. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16711. switch (evt.button) {
  16712. case 0:
  16713. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16714. break;
  16715. case 1:
  16716. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16717. break;
  16718. case 2:
  16719. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16720. break;
  16721. }
  16722. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16723. }
  16724. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16725. var that = _this;
  16726. window.setTimeout(function () {
  16727. 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);
  16728. if (pickResult.hit && pickResult.pickedMesh) {
  16729. if (pickResult.pickedMesh.actionManager) {
  16730. 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)) {
  16731. that._startingPointerTime = 0;
  16732. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16733. }
  16734. }
  16735. }
  16736. }, BABYLON.ActionManager.LongPressDelay);
  16737. }
  16738. }
  16739. }
  16740. if (_this.onPointerDown) {
  16741. _this.onPointerDown(evt, pickResult);
  16742. }
  16743. if (_this.onPointerObservable.hasObservers()) {
  16744. var type = PointerEventTypes.POINTERDOWN;
  16745. var pi = new PointerInfo(type, evt, pickResult);
  16746. _this.onPointerObservable.notifyObservers(pi, type);
  16747. }
  16748. // Sprites
  16749. _this._pickedDownSprite = null;
  16750. if (_this.spriteManagers.length > 0) {
  16751. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16752. if (pickResult.hit && pickResult.pickedSprite) {
  16753. if (pickResult.pickedSprite.actionManager) {
  16754. _this._pickedDownSprite = pickResult.pickedSprite;
  16755. switch (evt.button) {
  16756. case 0:
  16757. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16758. break;
  16759. case 1:
  16760. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16761. break;
  16762. case 2:
  16763. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16764. break;
  16765. }
  16766. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16767. }
  16768. }
  16769. }
  16770. };
  16771. this._onPointerUp = function (evt) {
  16772. _this._updatePointerPosition(evt);
  16773. // PreObservable support
  16774. if (_this.onPrePointerObservable.hasObservers()) {
  16775. var type = PointerEventTypes.POINTERUP;
  16776. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16777. _this.onPrePointerObservable.notifyObservers(pi, type);
  16778. if (pi.skipOnPointerObservable) {
  16779. return;
  16780. }
  16781. }
  16782. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16783. return;
  16784. }
  16785. if (!_this.pointerUpPredicate) {
  16786. _this.pointerUpPredicate = function (mesh) {
  16787. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16788. };
  16789. }
  16790. // Meshes
  16791. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16792. if (pickResult.hit && pickResult.pickedMesh) {
  16793. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16794. if (_this.onPointerPick) {
  16795. _this.onPointerPick(evt, pickResult);
  16796. }
  16797. if (_this.onPointerObservable.hasObservers()) {
  16798. var type = PointerEventTypes.POINTERPICK;
  16799. var pi = new PointerInfo(type, evt, pickResult);
  16800. _this.onPointerObservable.notifyObservers(pi, type);
  16801. }
  16802. }
  16803. if (pickResult.pickedMesh.actionManager) {
  16804. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16805. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16806. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16807. }
  16808. }
  16809. }
  16810. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16811. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16812. }
  16813. if (_this.onPointerUp) {
  16814. _this.onPointerUp(evt, pickResult);
  16815. }
  16816. if (_this.onPointerObservable.hasObservers()) {
  16817. var type = PointerEventTypes.POINTERUP;
  16818. var pi = new PointerInfo(type, evt, pickResult);
  16819. _this.onPointerObservable.notifyObservers(pi, type);
  16820. }
  16821. _this._startingPointerTime = 0;
  16822. // Sprites
  16823. if (_this.spriteManagers.length > 0) {
  16824. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16825. if (pickResult.hit && pickResult.pickedSprite) {
  16826. if (pickResult.pickedSprite.actionManager) {
  16827. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16828. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16829. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16830. }
  16831. }
  16832. }
  16833. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16834. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16835. }
  16836. }
  16837. };
  16838. this._onKeyDown = function (evt) {
  16839. if (_this.actionManager) {
  16840. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16841. }
  16842. };
  16843. this._onKeyUp = function (evt) {
  16844. if (_this.actionManager) {
  16845. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16846. }
  16847. };
  16848. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16849. var canvas = this._engine.getRenderingCanvas();
  16850. if (attachMove) {
  16851. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16852. // Wheel
  16853. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16854. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16855. }
  16856. if (attachDown) {
  16857. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16858. }
  16859. if (attachUp) {
  16860. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16861. }
  16862. canvas.tabIndex = 1;
  16863. canvas.addEventListener("keydown", this._onKeyDown, false);
  16864. canvas.addEventListener("keyup", this._onKeyUp, false);
  16865. };
  16866. Scene.prototype.detachControl = function () {
  16867. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16868. var canvas = this._engine.getRenderingCanvas();
  16869. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16870. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16871. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16872. // Wheel
  16873. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16874. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16875. canvas.removeEventListener("keydown", this._onKeyDown);
  16876. canvas.removeEventListener("keyup", this._onKeyUp);
  16877. };
  16878. // Ready
  16879. Scene.prototype.isReady = function () {
  16880. if (this._pendingData.length > 0) {
  16881. return false;
  16882. }
  16883. var index;
  16884. for (index = 0; index < this._geometries.length; index++) {
  16885. var geometry = this._geometries[index];
  16886. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16887. return false;
  16888. }
  16889. }
  16890. for (index = 0; index < this.meshes.length; index++) {
  16891. var mesh = this.meshes[index];
  16892. if (!mesh.isReady()) {
  16893. return false;
  16894. }
  16895. var mat = mesh.material;
  16896. if (mat) {
  16897. if (!mat.isReady(mesh)) {
  16898. return false;
  16899. }
  16900. }
  16901. }
  16902. return true;
  16903. };
  16904. Scene.prototype.resetCachedMaterial = function () {
  16905. this._cachedMaterial = null;
  16906. };
  16907. Scene.prototype.registerBeforeRender = function (func) {
  16908. this.onBeforeRenderObservable.add(func);
  16909. };
  16910. Scene.prototype.unregisterBeforeRender = function (func) {
  16911. this.onBeforeRenderObservable.removeCallback(func);
  16912. };
  16913. Scene.prototype.registerAfterRender = function (func) {
  16914. this.onAfterRenderObservable.add(func);
  16915. };
  16916. Scene.prototype.unregisterAfterRender = function (func) {
  16917. this.onAfterRenderObservable.removeCallback(func);
  16918. };
  16919. Scene.prototype._addPendingData = function (data) {
  16920. this._pendingData.push(data);
  16921. };
  16922. Scene.prototype._removePendingData = function (data) {
  16923. var index = this._pendingData.indexOf(data);
  16924. if (index !== -1) {
  16925. this._pendingData.splice(index, 1);
  16926. }
  16927. };
  16928. Scene.prototype.getWaitingItemsCount = function () {
  16929. return this._pendingData.length;
  16930. };
  16931. /**
  16932. * Registers a function to be executed when the scene is ready.
  16933. * @param {Function} func - the function to be executed.
  16934. */
  16935. Scene.prototype.executeWhenReady = function (func) {
  16936. var _this = this;
  16937. this.onReadyObservable.add(func);
  16938. if (this._executeWhenReadyTimeoutId !== -1) {
  16939. return;
  16940. }
  16941. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16942. _this._checkIsReady();
  16943. }, 150);
  16944. };
  16945. Scene.prototype._checkIsReady = function () {
  16946. var _this = this;
  16947. if (this.isReady()) {
  16948. this.onReadyObservable.notifyObservers(this);
  16949. this.onReadyObservable.clear();
  16950. this._executeWhenReadyTimeoutId = -1;
  16951. return;
  16952. }
  16953. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16954. _this._checkIsReady();
  16955. }, 150);
  16956. };
  16957. // Animations
  16958. /**
  16959. * Will start the animation sequence of a given target
  16960. * @param target - the target
  16961. * @param {number} from - from which frame should animation start
  16962. * @param {number} to - till which frame should animation run.
  16963. * @param {boolean} [loop] - should the animation loop
  16964. * @param {number} [speedRatio] - the speed in which to run the animation
  16965. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16966. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16967. * @return {BABYLON.Animatable} the animatable object created for this animation
  16968. * @see BABYLON.Animatable
  16969. * @see http://doc.babylonjs.com/page.php?p=22081
  16970. */
  16971. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16972. if (speedRatio === void 0) { speedRatio = 1.0; }
  16973. this.stopAnimation(target);
  16974. if (!animatable) {
  16975. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16976. }
  16977. // Local animations
  16978. if (target.animations) {
  16979. animatable.appendAnimations(target, target.animations);
  16980. }
  16981. // Children animations
  16982. if (target.getAnimatables) {
  16983. var animatables = target.getAnimatables();
  16984. for (var index = 0; index < animatables.length; index++) {
  16985. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16986. }
  16987. }
  16988. animatable.reset();
  16989. return animatable;
  16990. };
  16991. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16992. if (speedRatio === undefined) {
  16993. speedRatio = 1.0;
  16994. }
  16995. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16996. return animatable;
  16997. };
  16998. Scene.prototype.getAnimatableByTarget = function (target) {
  16999. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17000. if (this._activeAnimatables[index].target === target) {
  17001. return this._activeAnimatables[index];
  17002. }
  17003. }
  17004. return null;
  17005. };
  17006. Object.defineProperty(Scene.prototype, "Animatables", {
  17007. get: function () {
  17008. return this._activeAnimatables;
  17009. },
  17010. enumerable: true,
  17011. configurable: true
  17012. });
  17013. /**
  17014. * Will stop the animation of the given target
  17015. * @param target - the target
  17016. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17017. * @see beginAnimation
  17018. */
  17019. Scene.prototype.stopAnimation = function (target, animationName) {
  17020. var animatable = this.getAnimatableByTarget(target);
  17021. if (animatable) {
  17022. animatable.stop(animationName);
  17023. }
  17024. };
  17025. Scene.prototype._animate = function () {
  17026. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17027. return;
  17028. }
  17029. if (!this._animationStartDate) {
  17030. if (this._pendingData.length > 0) {
  17031. return;
  17032. }
  17033. this._animationStartDate = BABYLON.Tools.Now;
  17034. }
  17035. // Getting time
  17036. var now = BABYLON.Tools.Now;
  17037. var delay = now - this._animationStartDate;
  17038. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17039. this._activeAnimatables[index]._animate(delay);
  17040. }
  17041. };
  17042. // Matrix
  17043. Scene.prototype.getViewMatrix = function () {
  17044. return this._viewMatrix;
  17045. };
  17046. Scene.prototype.getProjectionMatrix = function () {
  17047. return this._projectionMatrix;
  17048. };
  17049. Scene.prototype.getTransformMatrix = function () {
  17050. return this._transformMatrix;
  17051. };
  17052. Scene.prototype.setTransformMatrix = function (view, projection) {
  17053. this._viewMatrix = view;
  17054. this._projectionMatrix = projection;
  17055. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17056. // Update frustum
  17057. if (!this._frustumPlanes) {
  17058. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17059. }
  17060. else {
  17061. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17062. }
  17063. };
  17064. // Methods
  17065. Scene.prototype.addMesh = function (newMesh) {
  17066. newMesh.uniqueId = this._uniqueIdCounter++;
  17067. var position = this.meshes.push(newMesh);
  17068. //notify the collision coordinator
  17069. this.collisionCoordinator.onMeshAdded(newMesh);
  17070. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17071. };
  17072. Scene.prototype.removeMesh = function (toRemove) {
  17073. var index = this.meshes.indexOf(toRemove);
  17074. if (index !== -1) {
  17075. // Remove from the scene if mesh found
  17076. this.meshes.splice(index, 1);
  17077. }
  17078. //notify the collision coordinator
  17079. this.collisionCoordinator.onMeshRemoved(toRemove);
  17080. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17081. return index;
  17082. };
  17083. Scene.prototype.removeSkeleton = function (toRemove) {
  17084. var index = this.skeletons.indexOf(toRemove);
  17085. if (index !== -1) {
  17086. // Remove from the scene if mesh found
  17087. this.skeletons.splice(index, 1);
  17088. }
  17089. return index;
  17090. };
  17091. Scene.prototype.removeLight = function (toRemove) {
  17092. var index = this.lights.indexOf(toRemove);
  17093. if (index !== -1) {
  17094. // Remove from the scene if mesh found
  17095. this.lights.splice(index, 1);
  17096. }
  17097. this.onLightRemovedObservable.notifyObservers(toRemove);
  17098. return index;
  17099. };
  17100. Scene.prototype.removeCamera = function (toRemove) {
  17101. var index = this.cameras.indexOf(toRemove);
  17102. if (index !== -1) {
  17103. // Remove from the scene if mesh found
  17104. this.cameras.splice(index, 1);
  17105. }
  17106. // Remove from activeCameras
  17107. var index2 = this.activeCameras.indexOf(toRemove);
  17108. if (index2 !== -1) {
  17109. // Remove from the scene if mesh found
  17110. this.activeCameras.splice(index2, 1);
  17111. }
  17112. // Reset the activeCamera
  17113. if (this.activeCamera === toRemove) {
  17114. if (this.cameras.length > 0) {
  17115. this.activeCamera = this.cameras[0];
  17116. }
  17117. else {
  17118. this.activeCamera = null;
  17119. }
  17120. }
  17121. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17122. return index;
  17123. };
  17124. Scene.prototype.addLight = function (newLight) {
  17125. newLight.uniqueId = this._uniqueIdCounter++;
  17126. var position = this.lights.push(newLight);
  17127. this.onNewLightAddedObservable.notifyObservers(newLight);
  17128. };
  17129. Scene.prototype.addCamera = function (newCamera) {
  17130. newCamera.uniqueId = this._uniqueIdCounter++;
  17131. var position = this.cameras.push(newCamera);
  17132. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17133. };
  17134. /**
  17135. * Switch active camera
  17136. * @param {Camera} newCamera - new active camera
  17137. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17138. */
  17139. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17140. if (attachControl === void 0) { attachControl = true; }
  17141. var canvas = this._engine.getRenderingCanvas();
  17142. this.activeCamera.detachControl(canvas);
  17143. this.activeCamera = newCamera;
  17144. if (attachControl) {
  17145. newCamera.attachControl(canvas);
  17146. }
  17147. };
  17148. /**
  17149. * sets the active camera of the scene using its ID
  17150. * @param {string} id - the camera's ID
  17151. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17152. * @see activeCamera
  17153. */
  17154. Scene.prototype.setActiveCameraByID = function (id) {
  17155. var camera = this.getCameraByID(id);
  17156. if (camera) {
  17157. this.activeCamera = camera;
  17158. return camera;
  17159. }
  17160. return null;
  17161. };
  17162. /**
  17163. * sets the active camera of the scene using its name
  17164. * @param {string} name - the camera's name
  17165. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17166. * @see activeCamera
  17167. */
  17168. Scene.prototype.setActiveCameraByName = function (name) {
  17169. var camera = this.getCameraByName(name);
  17170. if (camera) {
  17171. this.activeCamera = camera;
  17172. return camera;
  17173. }
  17174. return null;
  17175. };
  17176. /**
  17177. * get a material using its id
  17178. * @param {string} the material's ID
  17179. * @return {BABYLON.Material|null} the material or null if none found.
  17180. */
  17181. Scene.prototype.getMaterialByID = function (id) {
  17182. for (var index = 0; index < this.materials.length; index++) {
  17183. if (this.materials[index].id === id) {
  17184. return this.materials[index];
  17185. }
  17186. }
  17187. return null;
  17188. };
  17189. /**
  17190. * get a material using its name
  17191. * @param {string} the material's name
  17192. * @return {BABYLON.Material|null} the material or null if none found.
  17193. */
  17194. Scene.prototype.getMaterialByName = function (name) {
  17195. for (var index = 0; index < this.materials.length; index++) {
  17196. if (this.materials[index].name === name) {
  17197. return this.materials[index];
  17198. }
  17199. }
  17200. return null;
  17201. };
  17202. Scene.prototype.getLensFlareSystemByName = function (name) {
  17203. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17204. if (this.lensFlareSystems[index].name === name) {
  17205. return this.lensFlareSystems[index];
  17206. }
  17207. }
  17208. return null;
  17209. };
  17210. Scene.prototype.getLensFlareSystemByID = function (id) {
  17211. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17212. if (this.lensFlareSystems[index].id === id) {
  17213. return this.lensFlareSystems[index];
  17214. }
  17215. }
  17216. return null;
  17217. };
  17218. Scene.prototype.getCameraByID = function (id) {
  17219. for (var index = 0; index < this.cameras.length; index++) {
  17220. if (this.cameras[index].id === id) {
  17221. return this.cameras[index];
  17222. }
  17223. }
  17224. return null;
  17225. };
  17226. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17227. for (var index = 0; index < this.cameras.length; index++) {
  17228. if (this.cameras[index].uniqueId === uniqueId) {
  17229. return this.cameras[index];
  17230. }
  17231. }
  17232. return null;
  17233. };
  17234. /**
  17235. * get a camera using its name
  17236. * @param {string} the camera's name
  17237. * @return {BABYLON.Camera|null} the camera or null if none found.
  17238. */
  17239. Scene.prototype.getCameraByName = function (name) {
  17240. for (var index = 0; index < this.cameras.length; index++) {
  17241. if (this.cameras[index].name === name) {
  17242. return this.cameras[index];
  17243. }
  17244. }
  17245. return null;
  17246. };
  17247. /**
  17248. * get a bone using its id
  17249. * @param {string} the bone's id
  17250. * @return {BABYLON.Bone|null} the bone or null if not found
  17251. */
  17252. Scene.prototype.getBoneByID = function (id) {
  17253. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17254. var skeleton = this.skeletons[skeletonIndex];
  17255. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17256. if (skeleton.bones[boneIndex].id === id) {
  17257. return skeleton.bones[boneIndex];
  17258. }
  17259. }
  17260. }
  17261. return null;
  17262. };
  17263. /**
  17264. * get a bone using its id
  17265. * @param {string} the bone's name
  17266. * @return {BABYLON.Bone|null} the bone or null if not found
  17267. */
  17268. Scene.prototype.getBoneByName = function (name) {
  17269. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17270. var skeleton = this.skeletons[skeletonIndex];
  17271. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17272. if (skeleton.bones[boneIndex].name === name) {
  17273. return skeleton.bones[boneIndex];
  17274. }
  17275. }
  17276. }
  17277. return null;
  17278. };
  17279. /**
  17280. * get a light node using its name
  17281. * @param {string} the light's name
  17282. * @return {BABYLON.Light|null} the light or null if none found.
  17283. */
  17284. Scene.prototype.getLightByName = function (name) {
  17285. for (var index = 0; index < this.lights.length; index++) {
  17286. if (this.lights[index].name === name) {
  17287. return this.lights[index];
  17288. }
  17289. }
  17290. return null;
  17291. };
  17292. /**
  17293. * get a light node using its ID
  17294. * @param {string} the light's id
  17295. * @return {BABYLON.Light|null} the light or null if none found.
  17296. */
  17297. Scene.prototype.getLightByID = function (id) {
  17298. for (var index = 0; index < this.lights.length; index++) {
  17299. if (this.lights[index].id === id) {
  17300. return this.lights[index];
  17301. }
  17302. }
  17303. return null;
  17304. };
  17305. /**
  17306. * get a light node using its scene-generated unique ID
  17307. * @param {number} the light's unique id
  17308. * @return {BABYLON.Light|null} the light or null if none found.
  17309. */
  17310. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17311. for (var index = 0; index < this.lights.length; index++) {
  17312. if (this.lights[index].uniqueId === uniqueId) {
  17313. return this.lights[index];
  17314. }
  17315. }
  17316. return null;
  17317. };
  17318. /**
  17319. * get a particle system by id
  17320. * @param id {number} the particle system id
  17321. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17322. */
  17323. Scene.prototype.getParticleSystemByID = function (id) {
  17324. for (var index = 0; index < this.particleSystems.length; index++) {
  17325. if (this.particleSystems[index].id === id) {
  17326. return this.particleSystems[index];
  17327. }
  17328. }
  17329. return null;
  17330. };
  17331. /**
  17332. * get a geometry using its ID
  17333. * @param {string} the geometry's id
  17334. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17335. */
  17336. Scene.prototype.getGeometryByID = function (id) {
  17337. for (var index = 0; index < this._geometries.length; index++) {
  17338. if (this._geometries[index].id === id) {
  17339. return this._geometries[index];
  17340. }
  17341. }
  17342. return null;
  17343. };
  17344. /**
  17345. * add a new geometry to this scene.
  17346. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17347. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17348. * @return {boolean} was the geometry added or not
  17349. */
  17350. Scene.prototype.pushGeometry = function (geometry, force) {
  17351. if (!force && this.getGeometryByID(geometry.id)) {
  17352. return false;
  17353. }
  17354. this._geometries.push(geometry);
  17355. //notify the collision coordinator
  17356. this.collisionCoordinator.onGeometryAdded(geometry);
  17357. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17358. return true;
  17359. };
  17360. /**
  17361. * Removes an existing geometry
  17362. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17363. * @return {boolean} was the geometry removed or not
  17364. */
  17365. Scene.prototype.removeGeometry = function (geometry) {
  17366. var index = this._geometries.indexOf(geometry);
  17367. if (index > -1) {
  17368. this._geometries.splice(index, 1);
  17369. //notify the collision coordinator
  17370. this.collisionCoordinator.onGeometryDeleted(geometry);
  17371. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17372. return true;
  17373. }
  17374. return false;
  17375. };
  17376. Scene.prototype.getGeometries = function () {
  17377. return this._geometries;
  17378. };
  17379. /**
  17380. * Get the first added mesh found of a given ID
  17381. * @param {string} id - the id to search for
  17382. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17383. */
  17384. Scene.prototype.getMeshByID = function (id) {
  17385. for (var index = 0; index < this.meshes.length; index++) {
  17386. if (this.meshes[index].id === id) {
  17387. return this.meshes[index];
  17388. }
  17389. }
  17390. return null;
  17391. };
  17392. Scene.prototype.getMeshesByID = function (id) {
  17393. return this.meshes.filter(function (m) {
  17394. return m.id === id;
  17395. });
  17396. };
  17397. /**
  17398. * Get a mesh with its auto-generated unique id
  17399. * @param {number} uniqueId - the unique id to search for
  17400. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17401. */
  17402. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17403. for (var index = 0; index < this.meshes.length; index++) {
  17404. if (this.meshes[index].uniqueId === uniqueId) {
  17405. return this.meshes[index];
  17406. }
  17407. }
  17408. return null;
  17409. };
  17410. /**
  17411. * Get a the last added mesh found of a given ID
  17412. * @param {string} id - the id to search for
  17413. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17414. */
  17415. Scene.prototype.getLastMeshByID = function (id) {
  17416. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17417. if (this.meshes[index].id === id) {
  17418. return this.meshes[index];
  17419. }
  17420. }
  17421. return null;
  17422. };
  17423. /**
  17424. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17425. * @param {string} id - the id to search for
  17426. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17427. */
  17428. Scene.prototype.getLastEntryByID = function (id) {
  17429. var index;
  17430. for (index = this.meshes.length - 1; index >= 0; index--) {
  17431. if (this.meshes[index].id === id) {
  17432. return this.meshes[index];
  17433. }
  17434. }
  17435. for (index = this.cameras.length - 1; index >= 0; index--) {
  17436. if (this.cameras[index].id === id) {
  17437. return this.cameras[index];
  17438. }
  17439. }
  17440. for (index = this.lights.length - 1; index >= 0; index--) {
  17441. if (this.lights[index].id === id) {
  17442. return this.lights[index];
  17443. }
  17444. }
  17445. return null;
  17446. };
  17447. Scene.prototype.getNodeByID = function (id) {
  17448. var mesh = this.getMeshByID(id);
  17449. if (mesh) {
  17450. return mesh;
  17451. }
  17452. var light = this.getLightByID(id);
  17453. if (light) {
  17454. return light;
  17455. }
  17456. var camera = this.getCameraByID(id);
  17457. if (camera) {
  17458. return camera;
  17459. }
  17460. var bone = this.getBoneByID(id);
  17461. return bone;
  17462. };
  17463. Scene.prototype.getNodeByName = function (name) {
  17464. var mesh = this.getMeshByName(name);
  17465. if (mesh) {
  17466. return mesh;
  17467. }
  17468. var light = this.getLightByName(name);
  17469. if (light) {
  17470. return light;
  17471. }
  17472. var camera = this.getCameraByName(name);
  17473. if (camera) {
  17474. return camera;
  17475. }
  17476. var bone = this.getBoneByName(name);
  17477. return bone;
  17478. };
  17479. Scene.prototype.getMeshByName = function (name) {
  17480. for (var index = 0; index < this.meshes.length; index++) {
  17481. if (this.meshes[index].name === name) {
  17482. return this.meshes[index];
  17483. }
  17484. }
  17485. return null;
  17486. };
  17487. Scene.prototype.getSoundByName = function (name) {
  17488. var index;
  17489. if (BABYLON.AudioEngine) {
  17490. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17491. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17492. return this.mainSoundTrack.soundCollection[index];
  17493. }
  17494. }
  17495. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17496. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17497. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17498. return this.soundTracks[sdIndex].soundCollection[index];
  17499. }
  17500. }
  17501. }
  17502. }
  17503. return null;
  17504. };
  17505. Scene.prototype.getLastSkeletonByID = function (id) {
  17506. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17507. if (this.skeletons[index].id === id) {
  17508. return this.skeletons[index];
  17509. }
  17510. }
  17511. return null;
  17512. };
  17513. Scene.prototype.getSkeletonById = function (id) {
  17514. for (var index = 0; index < this.skeletons.length; index++) {
  17515. if (this.skeletons[index].id === id) {
  17516. return this.skeletons[index];
  17517. }
  17518. }
  17519. return null;
  17520. };
  17521. Scene.prototype.getSkeletonByName = function (name) {
  17522. for (var index = 0; index < this.skeletons.length; index++) {
  17523. if (this.skeletons[index].name === name) {
  17524. return this.skeletons[index];
  17525. }
  17526. }
  17527. return null;
  17528. };
  17529. Scene.prototype.isActiveMesh = function (mesh) {
  17530. return (this._activeMeshes.indexOf(mesh) !== -1);
  17531. };
  17532. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17533. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17534. var material = subMesh.getMaterial();
  17535. if (mesh.showSubMeshesBoundingBox) {
  17536. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17537. }
  17538. if (material) {
  17539. // Render targets
  17540. if (material.getRenderTargetTextures) {
  17541. if (this._processedMaterials.indexOf(material) === -1) {
  17542. this._processedMaterials.push(material);
  17543. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17544. }
  17545. }
  17546. // Dispatch
  17547. this._activeIndices.addCount(subMesh.indexCount, false);
  17548. this._renderingManager.dispatch(subMesh);
  17549. }
  17550. }
  17551. };
  17552. Scene.prototype._isInIntermediateRendering = function () {
  17553. return this._intermediateRendering;
  17554. };
  17555. Scene.prototype._evaluateActiveMeshes = function () {
  17556. this.activeCamera._activeMeshes.reset();
  17557. this._activeMeshes.reset();
  17558. this._renderingManager.reset();
  17559. this._processedMaterials.reset();
  17560. this._activeParticleSystems.reset();
  17561. this._activeSkeletons.reset();
  17562. this._softwareSkinnedMeshes.reset();
  17563. this._boundingBoxRenderer.reset();
  17564. this._edgesRenderers.reset();
  17565. // Meshes
  17566. var meshes;
  17567. var len;
  17568. if (this._selectionOctree) {
  17569. var selection = this._selectionOctree.select(this._frustumPlanes);
  17570. meshes = selection.data;
  17571. len = selection.length;
  17572. }
  17573. else {
  17574. len = this.meshes.length;
  17575. meshes = this.meshes;
  17576. }
  17577. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17578. var mesh = meshes[meshIndex];
  17579. if (mesh.isBlocked) {
  17580. continue;
  17581. }
  17582. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17583. if (!mesh.isReady() || !mesh.isEnabled()) {
  17584. continue;
  17585. }
  17586. mesh.computeWorldMatrix();
  17587. // Intersections
  17588. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17589. this._meshesForIntersections.pushNoDuplicate(mesh);
  17590. }
  17591. // Switch to current LOD
  17592. var meshLOD = mesh.getLOD(this.activeCamera);
  17593. if (!meshLOD) {
  17594. continue;
  17595. }
  17596. mesh._preActivate();
  17597. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17598. this._activeMeshes.push(mesh);
  17599. this.activeCamera._activeMeshes.push(mesh);
  17600. mesh._activate(this._renderId);
  17601. this._activeMesh(mesh, meshLOD);
  17602. }
  17603. }
  17604. // Particle systems
  17605. this._particlesDuration.beginMonitoring();
  17606. var beforeParticlesDate = BABYLON.Tools.Now;
  17607. if (this.particlesEnabled) {
  17608. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17609. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17610. var particleSystem = this.particleSystems[particleIndex];
  17611. if (!particleSystem.isStarted()) {
  17612. continue;
  17613. }
  17614. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17615. this._activeParticleSystems.push(particleSystem);
  17616. particleSystem.animate();
  17617. }
  17618. }
  17619. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17620. }
  17621. this._particlesDuration.endMonitoring(false);
  17622. };
  17623. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17624. if (mesh.skeleton && this.skeletonsEnabled) {
  17625. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17626. mesh.skeleton.prepare();
  17627. }
  17628. if (!mesh.computeBonesUsingShaders) {
  17629. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17630. }
  17631. }
  17632. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17633. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17634. }
  17635. if (sourceMesh._edgesRenderer) {
  17636. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17637. }
  17638. if (mesh && mesh.subMeshes) {
  17639. // Submeshes Octrees
  17640. var len;
  17641. var subMeshes;
  17642. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17643. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17644. len = intersections.length;
  17645. subMeshes = intersections.data;
  17646. }
  17647. else {
  17648. subMeshes = mesh.subMeshes;
  17649. len = subMeshes.length;
  17650. }
  17651. for (var subIndex = 0; subIndex < len; subIndex++) {
  17652. var subMesh = subMeshes[subIndex];
  17653. this._evaluateSubMesh(subMesh, mesh);
  17654. }
  17655. }
  17656. };
  17657. Scene.prototype.updateTransformMatrix = function (force) {
  17658. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17659. };
  17660. Scene.prototype._renderForCamera = function (camera) {
  17661. var engine = this._engine;
  17662. var startTime = BABYLON.Tools.Now;
  17663. this.activeCamera = camera;
  17664. if (!this.activeCamera)
  17665. throw new Error("Active camera not set");
  17666. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17667. // Viewport
  17668. engine.setViewport(this.activeCamera.viewport);
  17669. // Camera
  17670. this.resetCachedMaterial();
  17671. this._renderId++;
  17672. this.updateTransformMatrix();
  17673. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17674. // Meshes
  17675. this._evaluateActiveMeshesDuration.beginMonitoring();
  17676. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17677. this._evaluateActiveMeshes();
  17678. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17679. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17680. // Software skinning
  17681. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17682. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17683. mesh.applySkeleton(mesh.skeleton);
  17684. }
  17685. // Render targets
  17686. this._renderTargetsDuration.beginMonitoring();
  17687. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17688. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17689. this._intermediateRendering = true;
  17690. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17691. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17692. var renderTarget = this._renderTargets.data[renderIndex];
  17693. if (renderTarget._shouldRender()) {
  17694. this._renderId++;
  17695. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17696. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17697. }
  17698. }
  17699. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17700. this._intermediateRendering = false;
  17701. this._renderId++;
  17702. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17703. }
  17704. this._renderTargetsDuration.endMonitoring(false);
  17705. // Prepare Frame
  17706. this.postProcessManager._prepareFrame();
  17707. this._renderDuration.beginMonitoring();
  17708. // Backgrounds
  17709. var layerIndex;
  17710. var layer;
  17711. if (this.layers.length) {
  17712. engine.setDepthBuffer(false);
  17713. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17714. layer = this.layers[layerIndex];
  17715. if (layer.isBackground) {
  17716. layer.render();
  17717. }
  17718. }
  17719. engine.setDepthBuffer(true);
  17720. }
  17721. // Render
  17722. BABYLON.Tools.StartPerformanceCounter("Main render");
  17723. // Activate HighlightLayer stencil
  17724. var stencilState = this._engine.getStencilBuffer();
  17725. var renderhighlights = false;
  17726. if (this.highlightLayers && this.highlightLayers.length > 0) {
  17727. for (var i = 0; i < this.highlightLayers.length; i++) {
  17728. var highlightLayer = this.highlightLayers[i];
  17729. if ((highlightLayer.layerMask & camera.layerMask) && highlightLayer.shouldRender()) {
  17730. renderhighlights = true;
  17731. this._engine.setStencilBuffer(true);
  17732. break;
  17733. }
  17734. }
  17735. }
  17736. this._renderingManager.render(null, null, true, true);
  17737. // Restore HighlightLayer stencil
  17738. if (renderhighlights) {
  17739. this._engine.setStencilBuffer(stencilState);
  17740. }
  17741. BABYLON.Tools.EndPerformanceCounter("Main render");
  17742. // Bounding boxes
  17743. this._boundingBoxRenderer.render();
  17744. // Edges
  17745. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17746. this._edgesRenderers.data[edgesRendererIndex].render();
  17747. }
  17748. // Lens flares
  17749. if (this.lensFlaresEnabled) {
  17750. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17751. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17752. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17753. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17754. lensFlareSystem.render();
  17755. }
  17756. }
  17757. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17758. }
  17759. // Foregrounds
  17760. if (this.layers.length) {
  17761. engine.setDepthBuffer(false);
  17762. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17763. layer = this.layers[layerIndex];
  17764. if (!layer.isBackground) {
  17765. layer.render();
  17766. }
  17767. }
  17768. engine.setDepthBuffer(true);
  17769. }
  17770. // Highlight Layer
  17771. if (renderhighlights) {
  17772. engine.setDepthBuffer(false);
  17773. for (var i = 0; i < this.highlightLayers.length; i++) {
  17774. if (this.highlightLayers[i].shouldRender()) {
  17775. this.highlightLayers[i].render();
  17776. }
  17777. }
  17778. engine.setDepthBuffer(true);
  17779. }
  17780. this._renderDuration.endMonitoring(false);
  17781. // Finalize frame
  17782. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17783. // Update camera
  17784. this.activeCamera._updateFromScene();
  17785. // Reset some special arrays
  17786. this._renderTargets.reset();
  17787. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17788. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17789. };
  17790. Scene.prototype._processSubCameras = function (camera) {
  17791. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17792. this._renderForCamera(camera);
  17793. return;
  17794. }
  17795. // rig cameras
  17796. for (var index = 0; index < camera._rigCameras.length; index++) {
  17797. this._renderForCamera(camera._rigCameras[index]);
  17798. }
  17799. this.activeCamera = camera;
  17800. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17801. // Update camera
  17802. this.activeCamera._updateFromScene();
  17803. };
  17804. Scene.prototype._checkIntersections = function () {
  17805. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17806. var sourceMesh = this._meshesForIntersections.data[index];
  17807. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17808. var action = sourceMesh.actionManager.actions[actionIndex];
  17809. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17810. var parameters = action.getTriggerParameter();
  17811. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17812. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17813. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17814. if (areIntersecting && currentIntersectionInProgress === -1) {
  17815. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17816. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17817. sourceMesh._intersectionsInProgress.push(otherMesh);
  17818. }
  17819. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17820. sourceMesh._intersectionsInProgress.push(otherMesh);
  17821. }
  17822. }
  17823. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17824. //They intersected, and now they don't.
  17825. //is this trigger an exit trigger? execute an event.
  17826. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17827. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17828. }
  17829. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17830. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17831. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17832. }
  17833. }
  17834. }
  17835. }
  17836. }
  17837. };
  17838. Scene.prototype.render = function () {
  17839. this._lastFrameDuration.beginMonitoring();
  17840. this._particlesDuration.fetchNewFrame();
  17841. this._spritesDuration.fetchNewFrame();
  17842. this._activeParticles.fetchNewFrame();
  17843. this._renderDuration.fetchNewFrame();
  17844. this._renderTargetsDuration.fetchNewFrame();
  17845. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17846. this._totalVertices.fetchNewFrame();
  17847. this._activeIndices.fetchNewFrame();
  17848. this._activeBones.fetchNewFrame();
  17849. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17850. this._meshesForIntersections.reset();
  17851. this.resetCachedMaterial();
  17852. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17853. // Actions
  17854. if (this.actionManager) {
  17855. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17856. }
  17857. //Simplification Queue
  17858. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17859. this.simplificationQueue.executeNext();
  17860. }
  17861. // Animations
  17862. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17863. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17864. this._animate();
  17865. // Physics
  17866. if (this._physicsEngine) {
  17867. BABYLON.Tools.StartPerformanceCounter("Physics");
  17868. this._physicsEngine._step(deltaTime / 1000.0);
  17869. BABYLON.Tools.EndPerformanceCounter("Physics");
  17870. }
  17871. // Before render
  17872. this.onBeforeRenderObservable.notifyObservers(this);
  17873. // Customs render targets
  17874. this._renderTargetsDuration.beginMonitoring();
  17875. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17876. var engine = this.getEngine();
  17877. var currentActiveCamera = this.activeCamera;
  17878. if (this.renderTargetsEnabled) {
  17879. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17880. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17881. var renderTarget = this.customRenderTargets[customIndex];
  17882. if (renderTarget._shouldRender()) {
  17883. this._renderId++;
  17884. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17885. if (!this.activeCamera)
  17886. throw new Error("Active camera not set");
  17887. // Viewport
  17888. engine.setViewport(this.activeCamera.viewport);
  17889. // Camera
  17890. this.updateTransformMatrix();
  17891. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17892. }
  17893. }
  17894. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17895. this._renderId++;
  17896. }
  17897. if (this.customRenderTargets.length > 0) {
  17898. engine.restoreDefaultFramebuffer();
  17899. }
  17900. this._renderTargetsDuration.endMonitoring();
  17901. this.activeCamera = currentActiveCamera;
  17902. // Procedural textures
  17903. if (this.proceduralTexturesEnabled) {
  17904. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17905. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17906. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17907. if (proceduralTexture._shouldRender()) {
  17908. proceduralTexture.render();
  17909. }
  17910. }
  17911. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17912. }
  17913. // Clear
  17914. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  17915. // Shadows
  17916. if (this.shadowsEnabled) {
  17917. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17918. var light = this.lights[lightIndex];
  17919. var shadowGenerator = light.getShadowGenerator();
  17920. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  17921. this._renderTargets.push(shadowGenerator.getShadowMap());
  17922. }
  17923. }
  17924. }
  17925. // Depth renderer
  17926. if (this._depthRenderer) {
  17927. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17928. }
  17929. // HighlightLayer
  17930. if (this.highlightLayers && this.highlightLayers.length > 0) {
  17931. for (var i = 0; i < this.highlightLayers.length; i++) {
  17932. if (this.highlightLayers[i].shouldRender()) {
  17933. this._renderTargets.push(this.highlightLayers[i]._mainTexture);
  17934. }
  17935. }
  17936. }
  17937. // RenderPipeline
  17938. this.postProcessRenderPipelineManager.update();
  17939. // Multi-cameras?
  17940. if (this.activeCameras.length > 0) {
  17941. var currentRenderId = this._renderId;
  17942. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17943. this._renderId = currentRenderId;
  17944. if (cameraIndex > 0) {
  17945. this._engine.clear(0, false, true, true);
  17946. }
  17947. this._processSubCameras(this.activeCameras[cameraIndex]);
  17948. }
  17949. }
  17950. else {
  17951. if (!this.activeCamera) {
  17952. throw new Error("No camera defined");
  17953. }
  17954. this._processSubCameras(this.activeCamera);
  17955. }
  17956. // Intersection checks
  17957. this._checkIntersections();
  17958. // Update the audio listener attached to the camera
  17959. if (BABYLON.AudioEngine) {
  17960. this._updateAudioParameters();
  17961. }
  17962. // After render
  17963. if (this.afterRender) {
  17964. this.afterRender();
  17965. }
  17966. this.onAfterRenderObservable.notifyObservers(this);
  17967. // Cleaning
  17968. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17969. this._toBeDisposed.data[index].dispose();
  17970. this._toBeDisposed[index] = null;
  17971. }
  17972. this._toBeDisposed.reset();
  17973. if (this.dumpNextRenderTargets) {
  17974. this.dumpNextRenderTargets = false;
  17975. }
  17976. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17977. this._lastFrameDuration.endMonitoring();
  17978. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17979. this._totalLightsCounter.addCount(this.lights.length, true);
  17980. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17981. this._totalTexturesCounter.addCount(this.textures.length, true);
  17982. this._activeBones.addCount(0, true);
  17983. this._activeIndices.addCount(0, true);
  17984. this._activeParticles.addCount(0, true);
  17985. };
  17986. Scene.prototype._updateAudioParameters = function () {
  17987. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17988. return;
  17989. }
  17990. var listeningCamera;
  17991. var audioEngine = BABYLON.Engine.audioEngine;
  17992. if (this.activeCameras.length > 0) {
  17993. listeningCamera = this.activeCameras[0];
  17994. }
  17995. else {
  17996. listeningCamera = this.activeCamera;
  17997. }
  17998. if (listeningCamera && audioEngine.canUseWebAudio) {
  17999. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18000. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18001. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18002. cameraDirection.normalize();
  18003. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18004. var i;
  18005. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18006. var sound = this.mainSoundTrack.soundCollection[i];
  18007. if (sound.useCustomAttenuation) {
  18008. sound.updateDistanceFromListener();
  18009. }
  18010. }
  18011. for (i = 0; i < this.soundTracks.length; i++) {
  18012. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18013. sound = this.soundTracks[i].soundCollection[j];
  18014. if (sound.useCustomAttenuation) {
  18015. sound.updateDistanceFromListener();
  18016. }
  18017. }
  18018. }
  18019. }
  18020. };
  18021. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18022. // Audio
  18023. get: function () {
  18024. return this._audioEnabled;
  18025. },
  18026. set: function (value) {
  18027. this._audioEnabled = value;
  18028. if (BABYLON.AudioEngine) {
  18029. if (this._audioEnabled) {
  18030. this._enableAudio();
  18031. }
  18032. else {
  18033. this._disableAudio();
  18034. }
  18035. }
  18036. },
  18037. enumerable: true,
  18038. configurable: true
  18039. });
  18040. Scene.prototype._disableAudio = function () {
  18041. var i;
  18042. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18043. this.mainSoundTrack.soundCollection[i].pause();
  18044. }
  18045. for (i = 0; i < this.soundTracks.length; i++) {
  18046. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18047. this.soundTracks[i].soundCollection[j].pause();
  18048. }
  18049. }
  18050. };
  18051. Scene.prototype._enableAudio = function () {
  18052. var i;
  18053. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18054. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18055. this.mainSoundTrack.soundCollection[i].play();
  18056. }
  18057. }
  18058. for (i = 0; i < this.soundTracks.length; i++) {
  18059. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18060. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18061. this.soundTracks[i].soundCollection[j].play();
  18062. }
  18063. }
  18064. }
  18065. };
  18066. Object.defineProperty(Scene.prototype, "headphone", {
  18067. get: function () {
  18068. return this._headphone;
  18069. },
  18070. set: function (value) {
  18071. this._headphone = value;
  18072. if (BABYLON.AudioEngine) {
  18073. if (this._headphone) {
  18074. this._switchAudioModeForHeadphones();
  18075. }
  18076. else {
  18077. this._switchAudioModeForNormalSpeakers();
  18078. }
  18079. }
  18080. },
  18081. enumerable: true,
  18082. configurable: true
  18083. });
  18084. Scene.prototype._switchAudioModeForHeadphones = function () {
  18085. this.mainSoundTrack.switchPanningModelToHRTF();
  18086. for (var i = 0; i < this.soundTracks.length; i++) {
  18087. this.soundTracks[i].switchPanningModelToHRTF();
  18088. }
  18089. };
  18090. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18091. this.mainSoundTrack.switchPanningModelToEqualPower();
  18092. for (var i = 0; i < this.soundTracks.length; i++) {
  18093. this.soundTracks[i].switchPanningModelToEqualPower();
  18094. }
  18095. };
  18096. Scene.prototype.enableDepthRenderer = function () {
  18097. if (this._depthRenderer) {
  18098. return this._depthRenderer;
  18099. }
  18100. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18101. return this._depthRenderer;
  18102. };
  18103. Scene.prototype.disableDepthRenderer = function () {
  18104. if (!this._depthRenderer) {
  18105. return;
  18106. }
  18107. this._depthRenderer.dispose();
  18108. this._depthRenderer = null;
  18109. };
  18110. Scene.prototype.freezeMaterials = function () {
  18111. for (var i = 0; i < this.materials.length; i++) {
  18112. this.materials[i].freeze();
  18113. }
  18114. };
  18115. Scene.prototype.unfreezeMaterials = function () {
  18116. for (var i = 0; i < this.materials.length; i++) {
  18117. this.materials[i].unfreeze();
  18118. }
  18119. };
  18120. Scene.prototype.dispose = function () {
  18121. this.beforeRender = null;
  18122. this.afterRender = null;
  18123. this.skeletons = [];
  18124. this._boundingBoxRenderer.dispose();
  18125. if (this._depthRenderer) {
  18126. this._depthRenderer.dispose();
  18127. }
  18128. // Debug layer
  18129. if (this._debugLayer) {
  18130. this._debugLayer.hide();
  18131. }
  18132. // Events
  18133. this.onDisposeObservable.notifyObservers(this);
  18134. this.onDisposeObservable.clear();
  18135. this.onBeforeRenderObservable.clear();
  18136. this.onAfterRenderObservable.clear();
  18137. this.detachControl();
  18138. // Release sounds & sounds tracks
  18139. if (BABYLON.AudioEngine) {
  18140. this.disposeSounds();
  18141. }
  18142. // Detach cameras
  18143. var canvas = this._engine.getRenderingCanvas();
  18144. var index;
  18145. for (index = 0; index < this.cameras.length; index++) {
  18146. this.cameras[index].detachControl(canvas);
  18147. }
  18148. // Release lights
  18149. while (this.lights.length) {
  18150. this.lights[0].dispose();
  18151. }
  18152. // Release meshes
  18153. while (this.meshes.length) {
  18154. this.meshes[0].dispose(true);
  18155. }
  18156. // Release cameras
  18157. while (this.cameras.length) {
  18158. this.cameras[0].dispose();
  18159. }
  18160. // Release materials
  18161. while (this.materials.length) {
  18162. this.materials[0].dispose();
  18163. }
  18164. // Release particles
  18165. while (this.particleSystems.length) {
  18166. this.particleSystems[0].dispose();
  18167. }
  18168. // Release sprites
  18169. while (this.spriteManagers.length) {
  18170. this.spriteManagers[0].dispose();
  18171. }
  18172. // Release layers
  18173. while (this.layers.length) {
  18174. this.layers[0].dispose();
  18175. }
  18176. while (this.highlightLayers.length) {
  18177. this.highlightLayers[0].dispose();
  18178. }
  18179. // Release textures
  18180. while (this.textures.length) {
  18181. this.textures[0].dispose();
  18182. }
  18183. // Post-processes
  18184. this.postProcessManager.dispose();
  18185. // Physics
  18186. if (this._physicsEngine) {
  18187. this.disablePhysicsEngine();
  18188. }
  18189. // Remove from engine
  18190. index = this._engine.scenes.indexOf(this);
  18191. if (index > -1) {
  18192. this._engine.scenes.splice(index, 1);
  18193. }
  18194. this._engine.wipeCaches();
  18195. };
  18196. // Release sounds & sounds tracks
  18197. Scene.prototype.disposeSounds = function () {
  18198. this.mainSoundTrack.dispose();
  18199. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18200. this.soundTracks[scIndex].dispose();
  18201. }
  18202. };
  18203. // Octrees
  18204. Scene.prototype.getWorldExtends = function () {
  18205. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18206. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18207. for (var index = 0; index < this.meshes.length; index++) {
  18208. var mesh = this.meshes[index];
  18209. mesh.computeWorldMatrix(true);
  18210. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18211. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18212. BABYLON.Tools.CheckExtends(minBox, min, max);
  18213. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18214. }
  18215. return {
  18216. min: min,
  18217. max: max
  18218. };
  18219. };
  18220. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18221. if (maxCapacity === void 0) { maxCapacity = 64; }
  18222. if (maxDepth === void 0) { maxDepth = 2; }
  18223. if (!this._selectionOctree) {
  18224. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18225. }
  18226. var worldExtends = this.getWorldExtends();
  18227. // Update octree
  18228. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18229. return this._selectionOctree;
  18230. };
  18231. // Picking
  18232. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18233. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18234. var engine = this._engine;
  18235. if (!camera) {
  18236. if (!this.activeCamera)
  18237. throw new Error("Active camera not set");
  18238. camera = this.activeCamera;
  18239. }
  18240. var cameraViewport = camera.viewport;
  18241. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18242. // Moving coordinates to local viewport world
  18243. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18244. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18245. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18246. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18247. };
  18248. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18249. var engine = this._engine;
  18250. if (!camera) {
  18251. if (!this.activeCamera)
  18252. throw new Error("Active camera not set");
  18253. camera = this.activeCamera;
  18254. }
  18255. var cameraViewport = camera.viewport;
  18256. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18257. var identity = BABYLON.Matrix.Identity();
  18258. // Moving coordinates to local viewport world
  18259. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18260. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18261. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18262. };
  18263. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18264. var pickingInfo = null;
  18265. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18266. var mesh = this.meshes[meshIndex];
  18267. if (predicate) {
  18268. if (!predicate(mesh)) {
  18269. continue;
  18270. }
  18271. }
  18272. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18273. continue;
  18274. }
  18275. var world = mesh.getWorldMatrix();
  18276. var ray = rayFunction(world);
  18277. var result = mesh.intersects(ray, fastCheck);
  18278. if (!result || !result.hit)
  18279. continue;
  18280. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18281. continue;
  18282. pickingInfo = result;
  18283. if (fastCheck) {
  18284. break;
  18285. }
  18286. }
  18287. return pickingInfo || new BABYLON.PickingInfo();
  18288. };
  18289. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18290. var pickingInfo = null;
  18291. camera = camera || this.activeCamera;
  18292. if (this.spriteManagers.length > 0) {
  18293. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18294. var spriteManager = this.spriteManagers[spriteIndex];
  18295. if (!spriteManager.isPickable) {
  18296. continue;
  18297. }
  18298. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18299. if (!result || !result.hit)
  18300. continue;
  18301. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18302. continue;
  18303. pickingInfo = result;
  18304. if (fastCheck) {
  18305. break;
  18306. }
  18307. }
  18308. }
  18309. return pickingInfo || new BABYLON.PickingInfo();
  18310. };
  18311. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18312. var _this = this;
  18313. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18314. /// <param name="x">X position on screen</param>
  18315. /// <param name="y">Y position on screen</param>
  18316. /// <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>
  18317. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18318. /// <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>
  18319. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18320. };
  18321. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18322. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18323. /// <param name="x">X position on screen</param>
  18324. /// <param name="y">Y position on screen</param>
  18325. /// <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>
  18326. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18327. /// <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>
  18328. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18329. };
  18330. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18331. var _this = this;
  18332. return this._internalPick(function (world) {
  18333. if (!_this._pickWithRayInverseMatrix) {
  18334. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18335. }
  18336. world.invertToRef(_this._pickWithRayInverseMatrix);
  18337. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18338. }, predicate, fastCheck);
  18339. };
  18340. Scene.prototype.setPointerOverMesh = function (mesh) {
  18341. if (this._pointerOverMesh === mesh) {
  18342. return;
  18343. }
  18344. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18345. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18346. }
  18347. this._pointerOverMesh = mesh;
  18348. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18349. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18350. }
  18351. };
  18352. Scene.prototype.getPointerOverMesh = function () {
  18353. return this._pointerOverMesh;
  18354. };
  18355. Scene.prototype.setPointerOverSprite = function (sprite) {
  18356. if (this._pointerOverSprite === sprite) {
  18357. return;
  18358. }
  18359. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18360. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18361. }
  18362. this._pointerOverSprite = sprite;
  18363. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18364. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18365. }
  18366. };
  18367. Scene.prototype.getPointerOverSprite = function () {
  18368. return this._pointerOverSprite;
  18369. };
  18370. // Physics
  18371. Scene.prototype.getPhysicsEngine = function () {
  18372. return this._physicsEngine;
  18373. };
  18374. /**
  18375. * Enables physics to the current scene
  18376. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18377. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18378. * @return {boolean} was the physics engine initialized
  18379. */
  18380. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18381. if (this._physicsEngine) {
  18382. return true;
  18383. }
  18384. try {
  18385. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18386. return true;
  18387. }
  18388. catch (e) {
  18389. BABYLON.Tools.Error(e.message);
  18390. return false;
  18391. }
  18392. };
  18393. Scene.prototype.disablePhysicsEngine = function () {
  18394. if (!this._physicsEngine) {
  18395. return;
  18396. }
  18397. this._physicsEngine.dispose();
  18398. this._physicsEngine = undefined;
  18399. };
  18400. Scene.prototype.isPhysicsEnabled = function () {
  18401. return this._physicsEngine !== undefined;
  18402. };
  18403. /**
  18404. *
  18405. * Sets the gravity of the physics engine (and NOT of the scene)
  18406. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  18407. */
  18408. Scene.prototype.setGravity = function (gravity) {
  18409. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  18410. if (!this._physicsEngine) {
  18411. return;
  18412. }
  18413. this._physicsEngine.setGravity(gravity);
  18414. };
  18415. /**
  18416. * Legacy support, using the new API
  18417. * @Deprecated
  18418. */
  18419. Scene.prototype.createCompoundImpostor = function (parts, options) {
  18420. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  18421. if (parts.parts) {
  18422. options = parts;
  18423. parts = parts.parts;
  18424. }
  18425. var mainMesh = parts[0].mesh;
  18426. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  18427. for (var index = 1; index < parts.length; index++) {
  18428. var mesh = parts[index].mesh;
  18429. if (mesh.parent !== mainMesh) {
  18430. mesh.position = mesh.position.subtract(mainMesh.position);
  18431. mesh.parent = mainMesh;
  18432. }
  18433. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  18434. }
  18435. mainMesh.physicsImpostor.forceUpdate();
  18436. };
  18437. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18438. var mesh = compound.parts[0].mesh;
  18439. mesh.physicsImpostor.dispose();
  18440. mesh.physicsImpostor = null;
  18441. };
  18442. // Misc.
  18443. Scene.prototype.createDefaultCameraOrLight = function () {
  18444. // Light
  18445. if (this.lights.length === 0) {
  18446. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18447. }
  18448. // Camera
  18449. if (!this.activeCamera) {
  18450. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  18451. // Compute position
  18452. var worldExtends = this.getWorldExtends();
  18453. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  18454. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  18455. camera.setTarget(worldCenter);
  18456. this.activeCamera = camera;
  18457. }
  18458. };
  18459. // Tags
  18460. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18461. if (tagsQuery === undefined) {
  18462. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18463. return list;
  18464. }
  18465. var listByTags = [];
  18466. forEach = forEach || (function (item) { return; });
  18467. for (var i in list) {
  18468. var item = list[i];
  18469. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18470. listByTags.push(item);
  18471. forEach(item);
  18472. }
  18473. }
  18474. return listByTags;
  18475. };
  18476. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18477. return this._getByTags(this.meshes, tagsQuery, forEach);
  18478. };
  18479. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18480. return this._getByTags(this.cameras, tagsQuery, forEach);
  18481. };
  18482. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18483. return this._getByTags(this.lights, tagsQuery, forEach);
  18484. };
  18485. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18486. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18487. };
  18488. /**
  18489. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18490. * This allowed control for front to back rendering or reversly depending of the special needs.
  18491. *
  18492. * @param renderingGroupId The rendering group id corresponding to its index
  18493. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18494. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18495. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18496. */
  18497. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18498. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18499. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18500. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18501. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18502. };
  18503. /**
  18504. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18505. *
  18506. * @param renderingGroupId The rendering group id corresponding to its index
  18507. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18508. */
  18509. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18510. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18511. };
  18512. // Statics
  18513. Scene._FOGMODE_NONE = 0;
  18514. Scene._FOGMODE_EXP = 1;
  18515. Scene._FOGMODE_EXP2 = 2;
  18516. Scene._FOGMODE_LINEAR = 3;
  18517. Scene.MinDeltaTime = 1.0;
  18518. Scene.MaxDeltaTime = 1000.0;
  18519. return Scene;
  18520. }());
  18521. BABYLON.Scene = Scene;
  18522. })(BABYLON || (BABYLON = {}));
  18523. var BABYLON;
  18524. (function (BABYLON) {
  18525. var Buffer = (function () {
  18526. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18527. if (engine instanceof BABYLON.Mesh) {
  18528. this._engine = engine.getScene().getEngine();
  18529. }
  18530. else {
  18531. this._engine = engine;
  18532. }
  18533. this._updatable = updatable;
  18534. this._data = data;
  18535. this._strideSize = stride;
  18536. if (!postponeInternalCreation) {
  18537. this.create();
  18538. }
  18539. this._instanced = instanced;
  18540. }
  18541. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18542. // a lot of these parameters are ignored as they are overriden by the buffer
  18543. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18544. };
  18545. // Properties
  18546. Buffer.prototype.isUpdatable = function () {
  18547. return this._updatable;
  18548. };
  18549. Buffer.prototype.getData = function () {
  18550. return this._data;
  18551. };
  18552. Buffer.prototype.getBuffer = function () {
  18553. return this._buffer;
  18554. };
  18555. Buffer.prototype.getStrideSize = function () {
  18556. return this._strideSize;
  18557. };
  18558. Buffer.prototype.getIsInstanced = function () {
  18559. return this._instanced;
  18560. };
  18561. // Methods
  18562. Buffer.prototype.create = function (data) {
  18563. if (!data && this._buffer) {
  18564. return; // nothing to do
  18565. }
  18566. data = data || this._data;
  18567. if (!this._buffer) {
  18568. if (this._updatable) {
  18569. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18570. this._data = data;
  18571. }
  18572. else {
  18573. this._buffer = this._engine.createVertexBuffer(data);
  18574. }
  18575. }
  18576. else if (this._updatable) {
  18577. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18578. this._data = data;
  18579. }
  18580. };
  18581. Buffer.prototype.update = function (data) {
  18582. this.create(data);
  18583. };
  18584. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18585. if (!this._buffer) {
  18586. return;
  18587. }
  18588. if (this._updatable) {
  18589. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18590. this._data = null;
  18591. }
  18592. };
  18593. Buffer.prototype.dispose = function () {
  18594. if (!this._buffer) {
  18595. return;
  18596. }
  18597. if (this._engine._releaseBuffer(this._buffer)) {
  18598. this._buffer = null;
  18599. }
  18600. };
  18601. return Buffer;
  18602. }());
  18603. BABYLON.Buffer = Buffer;
  18604. })(BABYLON || (BABYLON = {}));
  18605. var BABYLON;
  18606. (function (BABYLON) {
  18607. var VertexBuffer = (function () {
  18608. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18609. if (!stride) {
  18610. // Deduce stride from kind
  18611. switch (kind) {
  18612. case VertexBuffer.PositionKind:
  18613. stride = 3;
  18614. break;
  18615. case VertexBuffer.NormalKind:
  18616. stride = 3;
  18617. break;
  18618. case VertexBuffer.UVKind:
  18619. case VertexBuffer.UV2Kind:
  18620. case VertexBuffer.UV3Kind:
  18621. case VertexBuffer.UV4Kind:
  18622. case VertexBuffer.UV5Kind:
  18623. case VertexBuffer.UV6Kind:
  18624. stride = 2;
  18625. break;
  18626. case VertexBuffer.ColorKind:
  18627. stride = 4;
  18628. break;
  18629. case VertexBuffer.MatricesIndicesKind:
  18630. case VertexBuffer.MatricesIndicesExtraKind:
  18631. stride = 4;
  18632. break;
  18633. case VertexBuffer.MatricesWeightsKind:
  18634. case VertexBuffer.MatricesWeightsExtraKind:
  18635. stride = 4;
  18636. break;
  18637. }
  18638. }
  18639. if (data instanceof BABYLON.Buffer) {
  18640. if (!stride) {
  18641. stride = data.getStrideSize();
  18642. }
  18643. this._buffer = data;
  18644. this._ownsBuffer = false;
  18645. }
  18646. else {
  18647. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18648. this._ownsBuffer = true;
  18649. }
  18650. this._stride = stride;
  18651. this._offset = offset ? offset : 0;
  18652. this._size = size ? size : stride;
  18653. this._kind = kind;
  18654. }
  18655. VertexBuffer.prototype.getKind = function () {
  18656. return this._kind;
  18657. };
  18658. // Properties
  18659. VertexBuffer.prototype.isUpdatable = function () {
  18660. return this._buffer.isUpdatable();
  18661. };
  18662. VertexBuffer.prototype.getData = function () {
  18663. return this._buffer.getData();
  18664. };
  18665. VertexBuffer.prototype.getBuffer = function () {
  18666. return this._buffer.getBuffer();
  18667. };
  18668. VertexBuffer.prototype.getStrideSize = function () {
  18669. return this._stride;
  18670. };
  18671. VertexBuffer.prototype.getOffset = function () {
  18672. return this._offset;
  18673. };
  18674. VertexBuffer.prototype.getSize = function () {
  18675. return this._size;
  18676. };
  18677. VertexBuffer.prototype.getIsInstanced = function () {
  18678. return this._buffer.getIsInstanced();
  18679. };
  18680. // Methods
  18681. VertexBuffer.prototype.create = function (data) {
  18682. return this._buffer.create(data);
  18683. };
  18684. VertexBuffer.prototype.update = function (data) {
  18685. return this._buffer.update(data);
  18686. };
  18687. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18688. return this._buffer.updateDirectly(data, offset);
  18689. };
  18690. VertexBuffer.prototype.dispose = function () {
  18691. if (this._ownsBuffer) {
  18692. this._buffer.dispose();
  18693. }
  18694. };
  18695. Object.defineProperty(VertexBuffer, "PositionKind", {
  18696. get: function () {
  18697. return VertexBuffer._PositionKind;
  18698. },
  18699. enumerable: true,
  18700. configurable: true
  18701. });
  18702. Object.defineProperty(VertexBuffer, "NormalKind", {
  18703. get: function () {
  18704. return VertexBuffer._NormalKind;
  18705. },
  18706. enumerable: true,
  18707. configurable: true
  18708. });
  18709. Object.defineProperty(VertexBuffer, "UVKind", {
  18710. get: function () {
  18711. return VertexBuffer._UVKind;
  18712. },
  18713. enumerable: true,
  18714. configurable: true
  18715. });
  18716. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18717. get: function () {
  18718. return VertexBuffer._UV2Kind;
  18719. },
  18720. enumerable: true,
  18721. configurable: true
  18722. });
  18723. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18724. get: function () {
  18725. return VertexBuffer._UV3Kind;
  18726. },
  18727. enumerable: true,
  18728. configurable: true
  18729. });
  18730. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18731. get: function () {
  18732. return VertexBuffer._UV4Kind;
  18733. },
  18734. enumerable: true,
  18735. configurable: true
  18736. });
  18737. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18738. get: function () {
  18739. return VertexBuffer._UV5Kind;
  18740. },
  18741. enumerable: true,
  18742. configurable: true
  18743. });
  18744. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18745. get: function () {
  18746. return VertexBuffer._UV6Kind;
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(VertexBuffer, "ColorKind", {
  18752. get: function () {
  18753. return VertexBuffer._ColorKind;
  18754. },
  18755. enumerable: true,
  18756. configurable: true
  18757. });
  18758. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18759. get: function () {
  18760. return VertexBuffer._MatricesIndicesKind;
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18766. get: function () {
  18767. return VertexBuffer._MatricesWeightsKind;
  18768. },
  18769. enumerable: true,
  18770. configurable: true
  18771. });
  18772. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18773. get: function () {
  18774. return VertexBuffer._MatricesIndicesExtraKind;
  18775. },
  18776. enumerable: true,
  18777. configurable: true
  18778. });
  18779. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18780. get: function () {
  18781. return VertexBuffer._MatricesWeightsExtraKind;
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. // Enums
  18787. VertexBuffer._PositionKind = "position";
  18788. VertexBuffer._NormalKind = "normal";
  18789. VertexBuffer._UVKind = "uv";
  18790. VertexBuffer._UV2Kind = "uv2";
  18791. VertexBuffer._UV3Kind = "uv3";
  18792. VertexBuffer._UV4Kind = "uv4";
  18793. VertexBuffer._UV5Kind = "uv5";
  18794. VertexBuffer._UV6Kind = "uv6";
  18795. VertexBuffer._ColorKind = "color";
  18796. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18797. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18798. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18799. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18800. return VertexBuffer;
  18801. }());
  18802. BABYLON.VertexBuffer = VertexBuffer;
  18803. })(BABYLON || (BABYLON = {}));
  18804. var BABYLON;
  18805. (function (BABYLON) {
  18806. /**
  18807. * Creates an instance based on a source mesh.
  18808. */
  18809. var InstancedMesh = (function (_super) {
  18810. __extends(InstancedMesh, _super);
  18811. function InstancedMesh(name, source) {
  18812. _super.call(this, name, source.getScene());
  18813. source.instances.push(this);
  18814. this._sourceMesh = source;
  18815. this.position.copyFrom(source.position);
  18816. this.rotation.copyFrom(source.rotation);
  18817. this.scaling.copyFrom(source.scaling);
  18818. if (source.rotationQuaternion) {
  18819. this.rotationQuaternion = source.rotationQuaternion.clone();
  18820. }
  18821. this.infiniteDistance = source.infiniteDistance;
  18822. this.setPivotMatrix(source.getPivotMatrix());
  18823. this.refreshBoundingInfo();
  18824. this._syncSubMeshes();
  18825. }
  18826. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  18827. // Methods
  18828. get: function () {
  18829. return this._sourceMesh.receiveShadows;
  18830. },
  18831. enumerable: true,
  18832. configurable: true
  18833. });
  18834. Object.defineProperty(InstancedMesh.prototype, "material", {
  18835. get: function () {
  18836. return this._sourceMesh.material;
  18837. },
  18838. enumerable: true,
  18839. configurable: true
  18840. });
  18841. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  18842. get: function () {
  18843. return this._sourceMesh.visibility;
  18844. },
  18845. enumerable: true,
  18846. configurable: true
  18847. });
  18848. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  18849. get: function () {
  18850. return this._sourceMesh.skeleton;
  18851. },
  18852. enumerable: true,
  18853. configurable: true
  18854. });
  18855. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  18856. get: function () {
  18857. return this._sourceMesh.renderingGroupId;
  18858. },
  18859. enumerable: true,
  18860. configurable: true
  18861. });
  18862. InstancedMesh.prototype.getTotalVertices = function () {
  18863. return this._sourceMesh.getTotalVertices();
  18864. };
  18865. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  18866. get: function () {
  18867. return this._sourceMesh;
  18868. },
  18869. enumerable: true,
  18870. configurable: true
  18871. });
  18872. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18873. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  18874. };
  18875. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  18876. return this._sourceMesh.isVerticesDataPresent(kind);
  18877. };
  18878. InstancedMesh.prototype.getIndices = function () {
  18879. return this._sourceMesh.getIndices();
  18880. };
  18881. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  18882. get: function () {
  18883. return this._sourceMesh._positions;
  18884. },
  18885. enumerable: true,
  18886. configurable: true
  18887. });
  18888. InstancedMesh.prototype.refreshBoundingInfo = function () {
  18889. var meshBB = this._sourceMesh.getBoundingInfo();
  18890. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  18891. this._updateBoundingInfo();
  18892. };
  18893. InstancedMesh.prototype._preActivate = function () {
  18894. if (this._currentLOD) {
  18895. this._currentLOD._preActivate();
  18896. }
  18897. };
  18898. InstancedMesh.prototype._activate = function (renderId) {
  18899. if (this._currentLOD) {
  18900. this._currentLOD._registerInstanceForRenderId(this, renderId);
  18901. }
  18902. };
  18903. InstancedMesh.prototype.getLOD = function (camera) {
  18904. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  18905. if (this._currentLOD === this.sourceMesh) {
  18906. return this;
  18907. }
  18908. return this._currentLOD;
  18909. };
  18910. InstancedMesh.prototype._syncSubMeshes = function () {
  18911. this.releaseSubMeshes();
  18912. if (this._sourceMesh.subMeshes) {
  18913. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  18914. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  18915. }
  18916. }
  18917. };
  18918. InstancedMesh.prototype._generatePointsArray = function () {
  18919. return this._sourceMesh._generatePointsArray();
  18920. };
  18921. // Clone
  18922. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18923. var result = this._sourceMesh.createInstance(name);
  18924. // Deep copy
  18925. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  18926. // Bounding info
  18927. this.refreshBoundingInfo();
  18928. // Parent
  18929. if (newParent) {
  18930. result.parent = newParent;
  18931. }
  18932. if (!doNotCloneChildren) {
  18933. // Children
  18934. for (var index = 0; index < this.getScene().meshes.length; index++) {
  18935. var mesh = this.getScene().meshes[index];
  18936. if (mesh.parent === this) {
  18937. mesh.clone(mesh.name, result);
  18938. }
  18939. }
  18940. }
  18941. result.computeWorldMatrix(true);
  18942. return result;
  18943. };
  18944. // Dispoe
  18945. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  18946. // Remove from mesh
  18947. var index = this._sourceMesh.instances.indexOf(this);
  18948. this._sourceMesh.instances.splice(index, 1);
  18949. _super.prototype.dispose.call(this, doNotRecurse);
  18950. };
  18951. return InstancedMesh;
  18952. }(BABYLON.AbstractMesh));
  18953. BABYLON.InstancedMesh = InstancedMesh;
  18954. })(BABYLON || (BABYLON = {}));
  18955. var BABYLON;
  18956. (function (BABYLON) {
  18957. var _InstancesBatch = (function () {
  18958. function _InstancesBatch() {
  18959. this.mustReturn = false;
  18960. this.visibleInstances = new Array();
  18961. this.renderSelf = new Array();
  18962. }
  18963. return _InstancesBatch;
  18964. }());
  18965. BABYLON._InstancesBatch = _InstancesBatch;
  18966. var Mesh = (function (_super) {
  18967. __extends(Mesh, _super);
  18968. /**
  18969. * @constructor
  18970. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18971. * @param {Scene} scene The scene to add this mesh to.
  18972. * @param {Node} parent The parent of this mesh, if it has one
  18973. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18974. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18975. * When false, achieved by calling a clone(), also passing False.
  18976. * This will make creation of children, recursive.
  18977. */
  18978. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18979. if (parent === void 0) { parent = null; }
  18980. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18981. _super.call(this, name, scene);
  18982. // Events
  18983. /**
  18984. * An event triggered before rendering the mesh
  18985. * @type {BABYLON.Observable}
  18986. */
  18987. this.onBeforeRenderObservable = new BABYLON.Observable();
  18988. /**
  18989. * An event triggered after rendering the mesh
  18990. * @type {BABYLON.Observable}
  18991. */
  18992. this.onAfterRenderObservable = new BABYLON.Observable();
  18993. /**
  18994. * An event triggered before drawing the mesh
  18995. * @type {BABYLON.Observable}
  18996. */
  18997. this.onBeforeDrawObservable = new BABYLON.Observable();
  18998. // Members
  18999. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19000. this.instances = new Array();
  19001. this._LODLevels = new Array();
  19002. this._visibleInstances = {};
  19003. this._renderIdForInstances = new Array();
  19004. this._batchCache = new _InstancesBatch();
  19005. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19006. this._sideOrientation = Mesh._DEFAULTSIDE;
  19007. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19008. if (source) {
  19009. // Geometry
  19010. if (source._geometry) {
  19011. source._geometry.applyToMesh(this);
  19012. }
  19013. // Deep copy
  19014. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  19015. // Pivot
  19016. this.setPivotMatrix(source.getPivotMatrix());
  19017. this.id = name + "." + source.id;
  19018. // Material
  19019. this.material = source.material;
  19020. var index;
  19021. if (!doNotCloneChildren) {
  19022. // Children
  19023. for (index = 0; index < scene.meshes.length; index++) {
  19024. var mesh = scene.meshes[index];
  19025. if (mesh.parent === source) {
  19026. // doNotCloneChildren is always going to be False
  19027. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  19028. }
  19029. }
  19030. }
  19031. // Physics clone
  19032. var physicsEngine = this.getScene().getPhysicsEngine();
  19033. if (clonePhysicsImpostor && physicsEngine) {
  19034. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19035. if (impostor) {
  19036. this.physicsImpostor = impostor.clone(this);
  19037. }
  19038. }
  19039. // Particles
  19040. for (index = 0; index < scene.particleSystems.length; index++) {
  19041. var system = scene.particleSystems[index];
  19042. if (system.emitter === source) {
  19043. system.clone(system.name, this);
  19044. }
  19045. }
  19046. this.computeWorldMatrix(true);
  19047. }
  19048. // Parent
  19049. if (parent !== null) {
  19050. this.parent = parent;
  19051. }
  19052. }
  19053. Object.defineProperty(Mesh, "FRONTSIDE", {
  19054. /**
  19055. * Mesh side orientation : usually the external or front surface
  19056. */
  19057. get: function () {
  19058. return Mesh._FRONTSIDE;
  19059. },
  19060. enumerable: true,
  19061. configurable: true
  19062. });
  19063. Object.defineProperty(Mesh, "BACKSIDE", {
  19064. /**
  19065. * Mesh side orientation : usually the internal or back surface
  19066. */
  19067. get: function () {
  19068. return Mesh._BACKSIDE;
  19069. },
  19070. enumerable: true,
  19071. configurable: true
  19072. });
  19073. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19074. /**
  19075. * Mesh side orientation : both internal and external or front and back surfaces
  19076. */
  19077. get: function () {
  19078. return Mesh._DOUBLESIDE;
  19079. },
  19080. enumerable: true,
  19081. configurable: true
  19082. });
  19083. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19084. /**
  19085. * Mesh side orientation : by default, `FRONTSIDE`
  19086. */
  19087. get: function () {
  19088. return Mesh._DEFAULTSIDE;
  19089. },
  19090. enumerable: true,
  19091. configurable: true
  19092. });
  19093. Object.defineProperty(Mesh, "NO_CAP", {
  19094. /**
  19095. * Mesh cap setting : no cap
  19096. */
  19097. get: function () {
  19098. return Mesh._NO_CAP;
  19099. },
  19100. enumerable: true,
  19101. configurable: true
  19102. });
  19103. Object.defineProperty(Mesh, "CAP_START", {
  19104. /**
  19105. * Mesh cap setting : one cap at the beginning of the mesh
  19106. */
  19107. get: function () {
  19108. return Mesh._CAP_START;
  19109. },
  19110. enumerable: true,
  19111. configurable: true
  19112. });
  19113. Object.defineProperty(Mesh, "CAP_END", {
  19114. /**
  19115. * Mesh cap setting : one cap at the end of the mesh
  19116. */
  19117. get: function () {
  19118. return Mesh._CAP_END;
  19119. },
  19120. enumerable: true,
  19121. configurable: true
  19122. });
  19123. Object.defineProperty(Mesh, "CAP_ALL", {
  19124. /**
  19125. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19126. */
  19127. get: function () {
  19128. return Mesh._CAP_ALL;
  19129. },
  19130. enumerable: true,
  19131. configurable: true
  19132. });
  19133. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19134. set: function (callback) {
  19135. if (this._onBeforeDrawObserver) {
  19136. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19137. }
  19138. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19139. },
  19140. enumerable: true,
  19141. configurable: true
  19142. });
  19143. // Methods
  19144. /**
  19145. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19146. */
  19147. Mesh.prototype.toString = function (fullDetails) {
  19148. var ret = _super.prototype.toString.call(this, fullDetails);
  19149. ret += ", n vertices: " + this.getTotalVertices();
  19150. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19151. if (this.animations) {
  19152. for (var i = 0; i < this.animations.length; i++) {
  19153. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19154. }
  19155. }
  19156. if (fullDetails) {
  19157. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19158. }
  19159. return ret;
  19160. };
  19161. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19162. get: function () {
  19163. return this._LODLevels.length > 0;
  19164. },
  19165. enumerable: true,
  19166. configurable: true
  19167. });
  19168. Mesh.prototype._sortLODLevels = function () {
  19169. this._LODLevels.sort(function (a, b) {
  19170. if (a.distance < b.distance) {
  19171. return 1;
  19172. }
  19173. if (a.distance > b.distance) {
  19174. return -1;
  19175. }
  19176. return 0;
  19177. });
  19178. };
  19179. /**
  19180. * Add a mesh as LOD level triggered at the given distance.
  19181. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19182. * @param {number} distance The distance from the center of the object to show this level
  19183. * @param {Mesh} mesh The mesh to be added as LOD level
  19184. * @return {Mesh} This mesh (for chaining)
  19185. */
  19186. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19187. if (mesh && mesh._masterMesh) {
  19188. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19189. return this;
  19190. }
  19191. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19192. this._LODLevels.push(level);
  19193. if (mesh) {
  19194. mesh._masterMesh = this;
  19195. }
  19196. this._sortLODLevels();
  19197. return this;
  19198. };
  19199. /**
  19200. * Returns the LOD level mesh at the passed distance or null if not found.
  19201. * It is related to the method `addLODLevel(distance, mesh)`.
  19202. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19203. */
  19204. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19205. for (var index = 0; index < this._LODLevels.length; index++) {
  19206. var level = this._LODLevels[index];
  19207. if (level.distance === distance) {
  19208. return level.mesh;
  19209. }
  19210. }
  19211. return null;
  19212. };
  19213. /**
  19214. * Remove a mesh from the LOD array
  19215. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19216. * @param {Mesh} mesh The mesh to be removed.
  19217. * @return {Mesh} This mesh (for chaining)
  19218. */
  19219. Mesh.prototype.removeLODLevel = function (mesh) {
  19220. for (var index = 0; index < this._LODLevels.length; index++) {
  19221. if (this._LODLevels[index].mesh === mesh) {
  19222. this._LODLevels.splice(index, 1);
  19223. if (mesh) {
  19224. mesh._masterMesh = null;
  19225. }
  19226. }
  19227. }
  19228. this._sortLODLevels();
  19229. return this;
  19230. };
  19231. /**
  19232. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19233. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19234. */
  19235. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19236. if (!this._LODLevels || this._LODLevels.length === 0) {
  19237. return this;
  19238. }
  19239. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19240. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19241. if (this.onLODLevelSelection) {
  19242. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19243. }
  19244. return this;
  19245. }
  19246. for (var index = 0; index < this._LODLevels.length; index++) {
  19247. var level = this._LODLevels[index];
  19248. if (level.distance < distanceToCamera) {
  19249. if (level.mesh) {
  19250. level.mesh._preActivate();
  19251. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19252. }
  19253. if (this.onLODLevelSelection) {
  19254. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19255. }
  19256. return level.mesh;
  19257. }
  19258. }
  19259. if (this.onLODLevelSelection) {
  19260. this.onLODLevelSelection(distanceToCamera, this, this);
  19261. }
  19262. return this;
  19263. };
  19264. Object.defineProperty(Mesh.prototype, "geometry", {
  19265. /**
  19266. * Returns the mesh internal Geometry object.
  19267. */
  19268. get: function () {
  19269. return this._geometry;
  19270. },
  19271. enumerable: true,
  19272. configurable: true
  19273. });
  19274. /**
  19275. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19276. */
  19277. Mesh.prototype.getTotalVertices = function () {
  19278. if (!this._geometry) {
  19279. return 0;
  19280. }
  19281. return this._geometry.getTotalVertices();
  19282. };
  19283. /**
  19284. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19285. * 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.
  19286. * Returns null if the mesh has no geometry or no vertex buffer.
  19287. * Possible `kind` values :
  19288. * - BABYLON.VertexBuffer.PositionKind
  19289. * - BABYLON.VertexBuffer.UVKind
  19290. * - BABYLON.VertexBuffer.UV2Kind
  19291. * - BABYLON.VertexBuffer.UV3Kind
  19292. * - BABYLON.VertexBuffer.UV4Kind
  19293. * - BABYLON.VertexBuffer.UV5Kind
  19294. * - BABYLON.VertexBuffer.UV6Kind
  19295. * - BABYLON.VertexBuffer.ColorKind
  19296. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19297. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19298. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19299. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19300. */
  19301. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19302. if (!this._geometry) {
  19303. return null;
  19304. }
  19305. return this._geometry.getVerticesData(kind, copyWhenShared);
  19306. };
  19307. /**
  19308. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19309. * Returns `undefined` if the mesh has no geometry.
  19310. * Possible `kind` values :
  19311. * - BABYLON.VertexBuffer.PositionKind
  19312. * - BABYLON.VertexBuffer.UVKind
  19313. * - BABYLON.VertexBuffer.UV2Kind
  19314. * - BABYLON.VertexBuffer.UV3Kind
  19315. * - BABYLON.VertexBuffer.UV4Kind
  19316. * - BABYLON.VertexBuffer.UV5Kind
  19317. * - BABYLON.VertexBuffer.UV6Kind
  19318. * - BABYLON.VertexBuffer.ColorKind
  19319. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19320. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19321. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19322. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19323. */
  19324. Mesh.prototype.getVertexBuffer = function (kind) {
  19325. if (!this._geometry) {
  19326. return undefined;
  19327. }
  19328. return this._geometry.getVertexBuffer(kind);
  19329. };
  19330. /**
  19331. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19332. * Possible `kind` values :
  19333. * - BABYLON.VertexBuffer.PositionKind
  19334. * - BABYLON.VertexBuffer.UVKind
  19335. * - BABYLON.VertexBuffer.UV2Kind
  19336. * - BABYLON.VertexBuffer.UV3Kind
  19337. * - BABYLON.VertexBuffer.UV4Kind
  19338. * - BABYLON.VertexBuffer.UV5Kind
  19339. * - BABYLON.VertexBuffer.UV6Kind
  19340. * - BABYLON.VertexBuffer.ColorKind
  19341. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19342. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19343. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19344. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19345. */
  19346. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19347. if (!this._geometry) {
  19348. if (this._delayInfo) {
  19349. return this._delayInfo.indexOf(kind) !== -1;
  19350. }
  19351. return false;
  19352. }
  19353. return this._geometry.isVerticesDataPresent(kind);
  19354. };
  19355. /**
  19356. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19357. * Possible `kind` values :
  19358. * - BABYLON.VertexBuffer.PositionKind
  19359. * - BABYLON.VertexBuffer.UVKind
  19360. * - BABYLON.VertexBuffer.UV2Kind
  19361. * - BABYLON.VertexBuffer.UV3Kind
  19362. * - BABYLON.VertexBuffer.UV4Kind
  19363. * - BABYLON.VertexBuffer.UV5Kind
  19364. * - BABYLON.VertexBuffer.UV6Kind
  19365. * - BABYLON.VertexBuffer.ColorKind
  19366. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19367. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19368. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19369. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19370. */
  19371. Mesh.prototype.getVerticesDataKinds = function () {
  19372. if (!this._geometry) {
  19373. var result = [];
  19374. if (this._delayInfo) {
  19375. this._delayInfo.forEach(function (kind, index, array) {
  19376. result.push(kind);
  19377. });
  19378. }
  19379. return result;
  19380. }
  19381. return this._geometry.getVerticesDataKinds();
  19382. };
  19383. /**
  19384. * Returns a positive integer : the total number of indices in this mesh geometry.
  19385. * Returns zero if the mesh has no geometry.
  19386. */
  19387. Mesh.prototype.getTotalIndices = function () {
  19388. if (!this._geometry) {
  19389. return 0;
  19390. }
  19391. return this._geometry.getTotalIndices();
  19392. };
  19393. /**
  19394. * Returns an array of integers or a Int32Array populated with the mesh indices.
  19395. * 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.
  19396. * Returns an empty array if the mesh has no geometry.
  19397. */
  19398. Mesh.prototype.getIndices = function (copyWhenShared) {
  19399. if (!this._geometry) {
  19400. return [];
  19401. }
  19402. return this._geometry.getIndices(copyWhenShared);
  19403. };
  19404. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19405. get: function () {
  19406. return this._masterMesh !== null && this._masterMesh !== undefined;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. /**
  19412. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19413. */
  19414. Mesh.prototype.isReady = function () {
  19415. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19416. return false;
  19417. }
  19418. return _super.prototype.isReady.call(this);
  19419. };
  19420. /**
  19421. * Boolean : true if the mesh has been disposed.
  19422. */
  19423. Mesh.prototype.isDisposed = function () {
  19424. return this._isDisposed;
  19425. };
  19426. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19427. get: function () {
  19428. return this._sideOrientation;
  19429. },
  19430. /**
  19431. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19432. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19433. */
  19434. set: function (sideO) {
  19435. this._sideOrientation = sideO;
  19436. },
  19437. enumerable: true,
  19438. configurable: true
  19439. });
  19440. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19441. /**
  19442. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19443. * This property is pertinent only for updatable parametric shapes.
  19444. */
  19445. get: function () {
  19446. return this._areNormalsFrozen;
  19447. },
  19448. enumerable: true,
  19449. configurable: true
  19450. });
  19451. /**
  19452. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19453. * It has no effect at all on other shapes.
  19454. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19455. */
  19456. Mesh.prototype.freezeNormals = function () {
  19457. this._areNormalsFrozen = true;
  19458. };
  19459. /**
  19460. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19461. * It has no effect at all on other shapes.
  19462. * It reactivates the mesh normals computation if it was previously frozen.
  19463. */
  19464. Mesh.prototype.unfreezeNormals = function () {
  19465. this._areNormalsFrozen = false;
  19466. };
  19467. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19468. /**
  19469. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19470. */
  19471. set: function (count) {
  19472. this._overridenInstanceCount = count;
  19473. },
  19474. enumerable: true,
  19475. configurable: true
  19476. });
  19477. // Methods
  19478. Mesh.prototype._preActivate = function () {
  19479. var sceneRenderId = this.getScene().getRenderId();
  19480. if (this._preActivateId === sceneRenderId) {
  19481. return;
  19482. }
  19483. this._preActivateId = sceneRenderId;
  19484. this._visibleInstances = null;
  19485. };
  19486. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19487. if (this._visibleInstances) {
  19488. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19489. }
  19490. };
  19491. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19492. if (!this._visibleInstances) {
  19493. this._visibleInstances = {};
  19494. this._visibleInstances.defaultRenderId = renderId;
  19495. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19496. }
  19497. if (!this._visibleInstances[renderId]) {
  19498. this._visibleInstances[renderId] = new Array();
  19499. }
  19500. this._visibleInstances[renderId].push(instance);
  19501. };
  19502. /**
  19503. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19504. * This means the mesh underlying bounding box and sphere are recomputed.
  19505. */
  19506. Mesh.prototype.refreshBoundingInfo = function () {
  19507. if (this._boundingInfo.isLocked) {
  19508. return;
  19509. }
  19510. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19511. if (data) {
  19512. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19513. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19514. }
  19515. if (this.subMeshes) {
  19516. for (var index = 0; index < this.subMeshes.length; index++) {
  19517. this.subMeshes[index].refreshBoundingInfo();
  19518. }
  19519. }
  19520. this._updateBoundingInfo();
  19521. };
  19522. Mesh.prototype._createGlobalSubMesh = function () {
  19523. var totalVertices = this.getTotalVertices();
  19524. if (!totalVertices || !this.getIndices()) {
  19525. return null;
  19526. }
  19527. this.releaseSubMeshes();
  19528. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19529. };
  19530. Mesh.prototype.subdivide = function (count) {
  19531. if (count < 1) {
  19532. return;
  19533. }
  19534. var totalIndices = this.getTotalIndices();
  19535. var subdivisionSize = (totalIndices / count) | 0;
  19536. var offset = 0;
  19537. // Ensure that subdivisionSize is a multiple of 3
  19538. while (subdivisionSize % 3 !== 0) {
  19539. subdivisionSize++;
  19540. }
  19541. this.releaseSubMeshes();
  19542. for (var index = 0; index < count; index++) {
  19543. if (offset >= totalIndices) {
  19544. break;
  19545. }
  19546. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19547. offset += subdivisionSize;
  19548. }
  19549. this.synchronizeInstances();
  19550. };
  19551. /**
  19552. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19553. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19554. * The `data` are either a numeric array either a Float32Array.
  19555. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19556. * 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).
  19557. * Note that a new underlying VertexBuffer object is created each call.
  19558. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19559. *
  19560. * Possible `kind` values :
  19561. * - BABYLON.VertexBuffer.PositionKind
  19562. * - BABYLON.VertexBuffer.UVKind
  19563. * - BABYLON.VertexBuffer.UV2Kind
  19564. * - BABYLON.VertexBuffer.UV3Kind
  19565. * - BABYLON.VertexBuffer.UV4Kind
  19566. * - BABYLON.VertexBuffer.UV5Kind
  19567. * - BABYLON.VertexBuffer.UV6Kind
  19568. * - BABYLON.VertexBuffer.ColorKind
  19569. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19570. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19571. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19572. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19573. */
  19574. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19575. if (!this._geometry) {
  19576. var vertexData = new BABYLON.VertexData();
  19577. vertexData.set(data, kind);
  19578. var scene = this.getScene();
  19579. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19580. }
  19581. else {
  19582. this._geometry.setVerticesData(kind, data, updatable, stride);
  19583. }
  19584. };
  19585. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19586. if (!this._geometry) {
  19587. var scene = this.getScene();
  19588. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19589. }
  19590. this._geometry.setVerticesBuffer(buffer);
  19591. };
  19592. /**
  19593. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19594. * If the mesh has no geometry, it is simply returned as it is.
  19595. * The `data` are either a numeric array either a Float32Array.
  19596. * No new underlying VertexBuffer object is created.
  19597. * 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.
  19598. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19599. *
  19600. * Possible `kind` values :
  19601. * - BABYLON.VertexBuffer.PositionKind
  19602. * - BABYLON.VertexBuffer.UVKind
  19603. * - BABYLON.VertexBuffer.UV2Kind
  19604. * - BABYLON.VertexBuffer.UV3Kind
  19605. * - BABYLON.VertexBuffer.UV4Kind
  19606. * - BABYLON.VertexBuffer.UV5Kind
  19607. * - BABYLON.VertexBuffer.UV6Kind
  19608. * - BABYLON.VertexBuffer.ColorKind
  19609. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19610. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19611. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19612. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19613. */
  19614. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19615. if (!this._geometry) {
  19616. return;
  19617. }
  19618. if (!makeItUnique) {
  19619. this._geometry.updateVerticesData(kind, data, updateExtends);
  19620. }
  19621. else {
  19622. this.makeGeometryUnique();
  19623. this.updateVerticesData(kind, data, updateExtends, false);
  19624. }
  19625. };
  19626. /**
  19627. * Deprecated since BabylonJS v2.3
  19628. */
  19629. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19630. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19631. if (!this._geometry) {
  19632. return;
  19633. }
  19634. if (!makeItUnique) {
  19635. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19636. }
  19637. else {
  19638. this.makeGeometryUnique();
  19639. this.updateVerticesDataDirectly(kind, data, offset, false);
  19640. }
  19641. };
  19642. /**
  19643. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19644. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19645. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19646. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19647. */
  19648. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19649. if (computeNormals === void 0) { computeNormals = true; }
  19650. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19651. positionFunction(positions);
  19652. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19653. if (computeNormals) {
  19654. var indices = this.getIndices();
  19655. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19656. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19657. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19658. }
  19659. };
  19660. Mesh.prototype.makeGeometryUnique = function () {
  19661. if (!this._geometry) {
  19662. return;
  19663. }
  19664. var oldGeometry = this._geometry;
  19665. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19666. oldGeometry.releaseForMesh(this, true);
  19667. geometry.applyToMesh(this);
  19668. };
  19669. /**
  19670. * Sets the mesh indices.
  19671. * Expects an array populated with integers or a Int32Array.
  19672. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19673. * This method creates a new index buffer each call.
  19674. */
  19675. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19676. if (!this._geometry) {
  19677. var vertexData = new BABYLON.VertexData();
  19678. vertexData.indices = indices;
  19679. var scene = this.getScene();
  19680. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19681. }
  19682. else {
  19683. this._geometry.setIndices(indices, totalVertices);
  19684. }
  19685. };
  19686. /**
  19687. * Invert the geometry to move from a right handed system to a left handed one.
  19688. */
  19689. Mesh.prototype.toLeftHanded = function () {
  19690. if (!this._geometry) {
  19691. return;
  19692. }
  19693. this._geometry.toLeftHanded();
  19694. };
  19695. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19696. var engine = this.getScene().getEngine();
  19697. // Wireframe
  19698. var indexToBind;
  19699. if (this._unIndexed) {
  19700. indexToBind = null;
  19701. }
  19702. else {
  19703. switch (fillMode) {
  19704. case BABYLON.Material.PointFillMode:
  19705. indexToBind = null;
  19706. break;
  19707. case BABYLON.Material.WireFrameFillMode:
  19708. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19709. break;
  19710. default:
  19711. case BABYLON.Material.TriangleFillMode:
  19712. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19713. break;
  19714. }
  19715. }
  19716. // VBOs
  19717. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19718. };
  19719. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19720. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19721. return;
  19722. }
  19723. this.onBeforeDrawObservable.notifyObservers(this);
  19724. var engine = this.getScene().getEngine();
  19725. // Draw order
  19726. switch (fillMode) {
  19727. case BABYLON.Material.PointFillMode:
  19728. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19729. break;
  19730. case BABYLON.Material.WireFrameFillMode:
  19731. if (this._unIndexed) {
  19732. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19733. }
  19734. else {
  19735. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19736. }
  19737. break;
  19738. default:
  19739. if (this._unIndexed) {
  19740. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19741. }
  19742. else {
  19743. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19744. }
  19745. }
  19746. };
  19747. /**
  19748. * Registers for this mesh a javascript function called just before the rendering process.
  19749. * This function is passed the current mesh and doesn't return anything.
  19750. */
  19751. Mesh.prototype.registerBeforeRender = function (func) {
  19752. this.onBeforeRenderObservable.add(func);
  19753. };
  19754. /**
  19755. * Disposes a previously registered javascript function called before the rendering.
  19756. * This function is passed the current mesh and doesn't return anything.
  19757. */
  19758. Mesh.prototype.unregisterBeforeRender = function (func) {
  19759. this.onBeforeRenderObservable.removeCallback(func);
  19760. };
  19761. /**
  19762. * Registers for this mesh a javascript function called just after the rendering is complete.
  19763. * This function is passed the current mesh and doesn't return anything.
  19764. */
  19765. Mesh.prototype.registerAfterRender = function (func) {
  19766. this.onAfterRenderObservable.add(func);
  19767. };
  19768. /**
  19769. * Disposes a previously registered javascript function called after the rendering.
  19770. * This function is passed the current mesh and doesn't return anything.
  19771. */
  19772. Mesh.prototype.unregisterAfterRender = function (func) {
  19773. this.onAfterRenderObservable.removeCallback(func);
  19774. };
  19775. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19776. var scene = this.getScene();
  19777. this._batchCache.mustReturn = false;
  19778. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19779. this._batchCache.visibleInstances[subMeshId] = null;
  19780. if (this._visibleInstances) {
  19781. var currentRenderId = scene.getRenderId();
  19782. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19783. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19784. var selfRenderId = this._renderId;
  19785. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19786. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19787. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19788. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19789. }
  19790. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19791. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19792. this._batchCache.mustReturn = true;
  19793. return this._batchCache;
  19794. }
  19795. if (currentRenderId !== selfRenderId) {
  19796. this._batchCache.renderSelf[subMeshId] = false;
  19797. }
  19798. }
  19799. this._renderIdForInstances[subMeshId] = currentRenderId;
  19800. }
  19801. return this._batchCache;
  19802. };
  19803. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19804. var visibleInstances = batch.visibleInstances[subMesh._id];
  19805. var matricesCount = visibleInstances.length + 1;
  19806. var bufferSize = matricesCount * 16 * 4;
  19807. var currentInstancesBufferSize = this._instancesBufferSize;
  19808. var instancesBuffer = this._instancesBuffer;
  19809. while (this._instancesBufferSize < bufferSize) {
  19810. this._instancesBufferSize *= 2;
  19811. }
  19812. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19813. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19814. }
  19815. var offset = 0;
  19816. var instancesCount = 0;
  19817. var world = this.getWorldMatrix();
  19818. if (batch.renderSelf[subMesh._id]) {
  19819. world.copyToArray(this._instancesData, offset);
  19820. offset += 16;
  19821. instancesCount++;
  19822. }
  19823. if (visibleInstances) {
  19824. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19825. var instance = visibleInstances[instanceIndex];
  19826. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19827. offset += 16;
  19828. instancesCount++;
  19829. }
  19830. }
  19831. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19832. if (instancesBuffer) {
  19833. instancesBuffer.dispose();
  19834. }
  19835. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19836. this._instancesBuffer = instancesBuffer;
  19837. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19838. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19839. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19840. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19841. }
  19842. else {
  19843. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19844. }
  19845. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  19846. this._draw(subMesh, fillMode, instancesCount);
  19847. engine.unbindInstanceAttributes();
  19848. };
  19849. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19850. var scene = this.getScene();
  19851. var engine = scene.getEngine();
  19852. if (hardwareInstancedRendering) {
  19853. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19854. }
  19855. else {
  19856. if (batch.renderSelf[subMesh._id]) {
  19857. // Draw
  19858. if (onBeforeDraw) {
  19859. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19860. }
  19861. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19862. }
  19863. if (batch.visibleInstances[subMesh._id]) {
  19864. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19865. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19866. // World
  19867. var world = instance.getWorldMatrix();
  19868. if (onBeforeDraw) {
  19869. onBeforeDraw(true, world, effectiveMaterial);
  19870. }
  19871. // Draw
  19872. this._draw(subMesh, fillMode);
  19873. }
  19874. }
  19875. }
  19876. };
  19877. /**
  19878. * Triggers the draw call for the mesh.
  19879. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19880. */
  19881. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19882. var scene = this.getScene();
  19883. // Managing instances
  19884. var batch = this._getInstancesRenderList(subMesh._id);
  19885. if (batch.mustReturn) {
  19886. return;
  19887. }
  19888. // Checking geometry state
  19889. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19890. return;
  19891. }
  19892. var callbackIndex;
  19893. this.onBeforeRenderObservable.notifyObservers(this);
  19894. var engine = scene.getEngine();
  19895. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19896. // Material
  19897. var effectiveMaterial = subMesh.getMaterial();
  19898. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19899. return;
  19900. }
  19901. // Outline - step 1
  19902. var savedDepthWrite = engine.getDepthWrite();
  19903. if (this.renderOutline) {
  19904. engine.setDepthWrite(false);
  19905. scene.getOutlineRenderer().render(subMesh, batch);
  19906. engine.setDepthWrite(savedDepthWrite);
  19907. }
  19908. effectiveMaterial._preBind();
  19909. var effect = effectiveMaterial.getEffect();
  19910. // Bind
  19911. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19912. this._bind(subMesh, effect, fillMode);
  19913. var world = this.getWorldMatrix();
  19914. effectiveMaterial.bind(world, this);
  19915. // Alpha mode
  19916. if (enableAlphaMode) {
  19917. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19918. }
  19919. // Draw
  19920. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  19921. // Unbind
  19922. effectiveMaterial.unbind();
  19923. // Outline - step 2
  19924. if (this.renderOutline && savedDepthWrite) {
  19925. engine.setDepthWrite(true);
  19926. engine.setColorWrite(false);
  19927. scene.getOutlineRenderer().render(subMesh, batch);
  19928. engine.setColorWrite(true);
  19929. }
  19930. // Overlay
  19931. if (this.renderOverlay) {
  19932. var currentMode = engine.getAlphaMode();
  19933. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19934. scene.getOutlineRenderer().render(subMesh, batch, true);
  19935. engine.setAlphaMode(currentMode);
  19936. }
  19937. this.onAfterRenderObservable.notifyObservers(this);
  19938. };
  19939. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19940. if (isInstance) {
  19941. effectiveMaterial.bindOnlyWorldMatrix(world);
  19942. }
  19943. };
  19944. /**
  19945. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19946. */
  19947. Mesh.prototype.getEmittedParticleSystems = function () {
  19948. var results = new Array();
  19949. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19950. var particleSystem = this.getScene().particleSystems[index];
  19951. if (particleSystem.emitter === this) {
  19952. results.push(particleSystem);
  19953. }
  19954. }
  19955. return results;
  19956. };
  19957. /**
  19958. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19959. */
  19960. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19961. var results = new Array();
  19962. var descendants = this.getDescendants();
  19963. descendants.push(this);
  19964. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19965. var particleSystem = this.getScene().particleSystems[index];
  19966. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19967. results.push(particleSystem);
  19968. }
  19969. }
  19970. return results;
  19971. };
  19972. Mesh.prototype._checkDelayState = function () {
  19973. var scene = this.getScene();
  19974. if (this._geometry) {
  19975. this._geometry.load(scene);
  19976. }
  19977. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19978. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19979. this._queueLoad(this, scene);
  19980. }
  19981. };
  19982. Mesh.prototype._queueLoad = function (mesh, scene) {
  19983. var _this = this;
  19984. scene._addPendingData(mesh);
  19985. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19986. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19987. if (data instanceof ArrayBuffer) {
  19988. _this._delayLoadingFunction(data, _this);
  19989. }
  19990. else {
  19991. _this._delayLoadingFunction(JSON.parse(data), _this);
  19992. }
  19993. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19994. scene._removePendingData(_this);
  19995. }, function () { }, scene.database, getBinaryData);
  19996. };
  19997. /**
  19998. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19999. */
  20000. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20001. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20002. return false;
  20003. }
  20004. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20005. return false;
  20006. }
  20007. this._checkDelayState();
  20008. return true;
  20009. };
  20010. /**
  20011. * Sets the mesh material by the material or multiMaterial `id` property.
  20012. * The material `id` is a string identifying the material or the multiMaterial.
  20013. * This method returns nothing.
  20014. */
  20015. Mesh.prototype.setMaterialByID = function (id) {
  20016. var materials = this.getScene().materials;
  20017. var index;
  20018. for (index = 0; index < materials.length; index++) {
  20019. if (materials[index].id === id) {
  20020. this.material = materials[index];
  20021. return;
  20022. }
  20023. }
  20024. // Multi
  20025. var multiMaterials = this.getScene().multiMaterials;
  20026. for (index = 0; index < multiMaterials.length; index++) {
  20027. if (multiMaterials[index].id === id) {
  20028. this.material = multiMaterials[index];
  20029. return;
  20030. }
  20031. }
  20032. };
  20033. /**
  20034. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20035. */
  20036. Mesh.prototype.getAnimatables = function () {
  20037. var results = [];
  20038. if (this.material) {
  20039. results.push(this.material);
  20040. }
  20041. if (this.skeleton) {
  20042. results.push(this.skeleton);
  20043. }
  20044. return results;
  20045. };
  20046. /**
  20047. * Modifies the mesh geometry according to the passed transformation matrix.
  20048. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20049. * The mesh normals are modified accordingly the same transformation.
  20050. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20051. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20052. */
  20053. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20054. // Position
  20055. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20056. return;
  20057. }
  20058. var submeshes = this.subMeshes.splice(0);
  20059. this._resetPointsArrayCache();
  20060. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20061. var temp = [];
  20062. var index;
  20063. for (index = 0; index < data.length; index += 3) {
  20064. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20065. }
  20066. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20067. // Normals
  20068. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20069. return;
  20070. }
  20071. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20072. temp = [];
  20073. for (index = 0; index < data.length; index += 3) {
  20074. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20075. }
  20076. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20077. // flip faces?
  20078. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20079. this.flipFaces();
  20080. }
  20081. // Restore submeshes
  20082. this.releaseSubMeshes();
  20083. this.subMeshes = submeshes;
  20084. };
  20085. /**
  20086. * Modifies the mesh geometry according to its own current World Matrix.
  20087. * The mesh World Matrix is then reset.
  20088. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20089. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20090. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20091. */
  20092. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20093. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20094. this.scaling.copyFromFloats(1, 1, 1);
  20095. this.position.copyFromFloats(0, 0, 0);
  20096. this.rotation.copyFromFloats(0, 0, 0);
  20097. //only if quaternion is already set
  20098. if (this.rotationQuaternion) {
  20099. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20100. }
  20101. this._worldMatrix = BABYLON.Matrix.Identity();
  20102. };
  20103. // Cache
  20104. Mesh.prototype._resetPointsArrayCache = function () {
  20105. this._positions = null;
  20106. };
  20107. Mesh.prototype._generatePointsArray = function () {
  20108. if (this._positions)
  20109. return true;
  20110. this._positions = [];
  20111. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20112. if (!data) {
  20113. return false;
  20114. }
  20115. for (var index = 0; index < data.length; index += 3) {
  20116. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20117. }
  20118. return true;
  20119. };
  20120. /**
  20121. * Returns a new Mesh object generated from the current mesh properties.
  20122. * This method must not get confused with createInstance().
  20123. * The parameter `name` is a string, the name given to the new mesh.
  20124. * The optional parameter `newParent` can be any Node object (default `null`).
  20125. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20126. * 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.
  20127. */
  20128. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20129. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20130. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20131. };
  20132. /**
  20133. * Disposes the mesh.
  20134. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20135. */
  20136. Mesh.prototype.dispose = function (doNotRecurse) {
  20137. if (this._geometry) {
  20138. this._geometry.releaseForMesh(this, true);
  20139. }
  20140. // Instances
  20141. if (this._instancesBuffer) {
  20142. this._instancesBuffer.dispose();
  20143. this._instancesBuffer = null;
  20144. }
  20145. while (this.instances.length) {
  20146. this.instances[0].dispose();
  20147. }
  20148. // Highlight layers.
  20149. var highlightLayers = this.getScene().highlightLayers;
  20150. for (var i = 0; i < highlightLayers.length; i++) {
  20151. var highlightLayer = highlightLayers[i];
  20152. if (highlightLayer) {
  20153. highlightLayer.removeMesh(this);
  20154. highlightLayer.removeExcludedMesh(this);
  20155. }
  20156. }
  20157. _super.prototype.dispose.call(this, doNotRecurse);
  20158. };
  20159. /**
  20160. * Modifies the mesh geometry according to a displacement map.
  20161. * 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.
  20162. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20163. * This method returns nothing.
  20164. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20165. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20166. * 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.
  20167. */
  20168. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20169. var _this = this;
  20170. var scene = this.getScene();
  20171. var onload = function (img) {
  20172. // Getting height map data
  20173. var canvas = document.createElement("canvas");
  20174. var context = canvas.getContext("2d");
  20175. var heightMapWidth = img.width;
  20176. var heightMapHeight = img.height;
  20177. canvas.width = heightMapWidth;
  20178. canvas.height = heightMapHeight;
  20179. context.drawImage(img, 0, 0);
  20180. // Create VertexData from map data
  20181. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20182. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20183. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20184. //execute success callback, if set
  20185. if (onSuccess) {
  20186. onSuccess(_this);
  20187. }
  20188. };
  20189. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20190. };
  20191. /**
  20192. * Modifies the mesh geometry according to a displacementMap buffer.
  20193. * 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.
  20194. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20195. * This method returns nothing.
  20196. * 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.
  20197. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20198. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20199. */
  20200. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20201. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20202. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20203. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20204. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20205. return;
  20206. }
  20207. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20208. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20209. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20210. var position = BABYLON.Vector3.Zero();
  20211. var normal = BABYLON.Vector3.Zero();
  20212. var uv = BABYLON.Vector2.Zero();
  20213. for (var index = 0; index < positions.length; index += 3) {
  20214. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20215. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20216. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20217. // Compute height
  20218. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20219. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20220. var pos = (u + v * heightMapWidth) * 4;
  20221. var r = buffer[pos] / 255.0;
  20222. var g = buffer[pos + 1] / 255.0;
  20223. var b = buffer[pos + 2] / 255.0;
  20224. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20225. normal.normalize();
  20226. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20227. position = position.add(normal);
  20228. position.toArray(positions, index);
  20229. }
  20230. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20231. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20232. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20233. };
  20234. /**
  20235. * Modify the mesh to get a flat shading rendering.
  20236. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20237. * This method returns nothing.
  20238. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20239. */
  20240. Mesh.prototype.convertToFlatShadedMesh = function () {
  20241. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20242. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20243. var kinds = this.getVerticesDataKinds();
  20244. var vbs = [];
  20245. var data = [];
  20246. var newdata = [];
  20247. var updatableNormals = false;
  20248. var kindIndex;
  20249. var kind;
  20250. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20251. kind = kinds[kindIndex];
  20252. var vertexBuffer = this.getVertexBuffer(kind);
  20253. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20254. updatableNormals = vertexBuffer.isUpdatable();
  20255. kinds.splice(kindIndex, 1);
  20256. kindIndex--;
  20257. continue;
  20258. }
  20259. vbs[kind] = vertexBuffer;
  20260. data[kind] = vbs[kind].getData();
  20261. newdata[kind] = [];
  20262. }
  20263. // Save previous submeshes
  20264. var previousSubmeshes = this.subMeshes.slice(0);
  20265. var indices = this.getIndices();
  20266. var totalIndices = this.getTotalIndices();
  20267. // Generating unique vertices per face
  20268. var index;
  20269. for (index = 0; index < totalIndices; index++) {
  20270. var vertexIndex = indices[index];
  20271. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20272. kind = kinds[kindIndex];
  20273. var stride = vbs[kind].getStrideSize();
  20274. for (var offset = 0; offset < stride; offset++) {
  20275. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20276. }
  20277. }
  20278. }
  20279. // Updating faces & normal
  20280. var normals = [];
  20281. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20282. for (index = 0; index < totalIndices; index += 3) {
  20283. indices[index] = index;
  20284. indices[index + 1] = index + 1;
  20285. indices[index + 2] = index + 2;
  20286. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20287. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20288. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20289. var p1p2 = p1.subtract(p2);
  20290. var p3p2 = p3.subtract(p2);
  20291. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20292. // Store same normals for every vertex
  20293. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20294. normals.push(normal.x);
  20295. normals.push(normal.y);
  20296. normals.push(normal.z);
  20297. }
  20298. }
  20299. this.setIndices(indices);
  20300. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20301. // Updating vertex buffers
  20302. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20303. kind = kinds[kindIndex];
  20304. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20305. }
  20306. // Updating submeshes
  20307. this.releaseSubMeshes();
  20308. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20309. var previousOne = previousSubmeshes[submeshIndex];
  20310. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20311. }
  20312. this.synchronizeInstances();
  20313. };
  20314. /**
  20315. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20316. * In other words, more vertices, no more indices and a single bigger VBO.
  20317. * This method returns nothing.
  20318. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20319. *
  20320. */
  20321. Mesh.prototype.convertToUnIndexedMesh = function () {
  20322. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20323. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20324. var kinds = this.getVerticesDataKinds();
  20325. var vbs = [];
  20326. var data = [];
  20327. var newdata = [];
  20328. var updatableNormals = false;
  20329. var kindIndex;
  20330. var kind;
  20331. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20332. kind = kinds[kindIndex];
  20333. var vertexBuffer = this.getVertexBuffer(kind);
  20334. vbs[kind] = vertexBuffer;
  20335. data[kind] = vbs[kind].getData();
  20336. newdata[kind] = [];
  20337. }
  20338. // Save previous submeshes
  20339. var previousSubmeshes = this.subMeshes.slice(0);
  20340. var indices = this.getIndices();
  20341. var totalIndices = this.getTotalIndices();
  20342. // Generating unique vertices per face
  20343. var index;
  20344. for (index = 0; index < totalIndices; index++) {
  20345. var vertexIndex = indices[index];
  20346. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20347. kind = kinds[kindIndex];
  20348. var stride = vbs[kind].getStrideSize();
  20349. for (var offset = 0; offset < stride; offset++) {
  20350. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20351. }
  20352. }
  20353. }
  20354. // Updating indices
  20355. for (index = 0; index < totalIndices; index += 3) {
  20356. indices[index] = index;
  20357. indices[index + 1] = index + 1;
  20358. indices[index + 2] = index + 2;
  20359. }
  20360. this.setIndices(indices);
  20361. // Updating vertex buffers
  20362. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20363. kind = kinds[kindIndex];
  20364. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20365. }
  20366. // Updating submeshes
  20367. this.releaseSubMeshes();
  20368. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20369. var previousOne = previousSubmeshes[submeshIndex];
  20370. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20371. }
  20372. this._unIndexed = true;
  20373. this.synchronizeInstances();
  20374. };
  20375. /**
  20376. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20377. * This method returns nothing.
  20378. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20379. */
  20380. Mesh.prototype.flipFaces = function (flipNormals) {
  20381. if (flipNormals === void 0) { flipNormals = false; }
  20382. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20383. var i;
  20384. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20385. for (i = 0; i < vertex_data.normals.length; i++) {
  20386. vertex_data.normals[i] *= -1;
  20387. }
  20388. }
  20389. var temp;
  20390. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20391. // reassign indices
  20392. temp = vertex_data.indices[i + 1];
  20393. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20394. vertex_data.indices[i + 2] = temp;
  20395. }
  20396. vertex_data.applyToMesh(this);
  20397. };
  20398. // Instances
  20399. /**
  20400. * Creates a new InstancedMesh object from the mesh model.
  20401. * An instance shares the same properties and the same material than its model.
  20402. * Only these properties of each instance can then be set individually :
  20403. * - position
  20404. * - rotation
  20405. * - rotationQuaternion
  20406. * - setPivotMatrix
  20407. * - scaling
  20408. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20409. * Warning : this method is not supported for Line mesh and LineSystem
  20410. */
  20411. Mesh.prototype.createInstance = function (name) {
  20412. return new BABYLON.InstancedMesh(name, this);
  20413. };
  20414. /**
  20415. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20416. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20417. * This method returns nothing.
  20418. */
  20419. Mesh.prototype.synchronizeInstances = function () {
  20420. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20421. var instance = this.instances[instanceIndex];
  20422. instance._syncSubMeshes();
  20423. }
  20424. };
  20425. /**
  20426. * Simplify the mesh according to the given array of settings.
  20427. * Function will return immediately and will simplify async. It returns nothing.
  20428. * @param settings a collection of simplification settings.
  20429. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20430. * @param type the type of simplification to run.
  20431. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20432. */
  20433. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20434. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20435. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20436. this.getScene().simplificationQueue.addTask({
  20437. settings: settings,
  20438. parallelProcessing: parallelProcessing,
  20439. mesh: this,
  20440. simplificationType: simplificationType,
  20441. successCallback: successCallback
  20442. });
  20443. };
  20444. /**
  20445. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20446. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20447. * This should be used together with the simplification to avoid disappearing triangles.
  20448. * @param successCallback an optional success callback to be called after the optimization finished.
  20449. */
  20450. Mesh.prototype.optimizeIndices = function (successCallback) {
  20451. var _this = this;
  20452. var indices = this.getIndices();
  20453. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20454. var vectorPositions = [];
  20455. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20456. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20457. }
  20458. var dupes = [];
  20459. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20460. var realPos = vectorPositions.length - 1 - iteration;
  20461. var testedPosition = vectorPositions[realPos];
  20462. for (var j = 0; j < realPos; ++j) {
  20463. var againstPosition = vectorPositions[j];
  20464. if (testedPosition.equals(againstPosition)) {
  20465. dupes[realPos] = j;
  20466. break;
  20467. }
  20468. }
  20469. }, function () {
  20470. for (var i = 0; i < indices.length; ++i) {
  20471. indices[i] = dupes[indices[i]] || indices[i];
  20472. }
  20473. //indices are now reordered
  20474. var originalSubMeshes = _this.subMeshes.slice(0);
  20475. _this.setIndices(indices);
  20476. _this.subMeshes = originalSubMeshes;
  20477. if (successCallback) {
  20478. successCallback(_this);
  20479. }
  20480. });
  20481. };
  20482. // Statics
  20483. /**
  20484. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20485. * The parameter `parsedMesh` is the mesh to be copied.
  20486. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20487. */
  20488. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20489. var mesh = new Mesh(parsedMesh.name, scene);
  20490. mesh.id = parsedMesh.id;
  20491. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20492. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20493. if (parsedMesh.rotationQuaternion) {
  20494. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20495. }
  20496. else if (parsedMesh.rotation) {
  20497. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20498. }
  20499. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20500. if (parsedMesh.localMatrix) {
  20501. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20502. }
  20503. else if (parsedMesh.pivotMatrix) {
  20504. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20505. }
  20506. mesh.setEnabled(parsedMesh.isEnabled);
  20507. mesh.isVisible = parsedMesh.isVisible;
  20508. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20509. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20510. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20511. if (parsedMesh.applyFog !== undefined) {
  20512. mesh.applyFog = parsedMesh.applyFog;
  20513. }
  20514. if (parsedMesh.pickable !== undefined) {
  20515. mesh.isPickable = parsedMesh.pickable;
  20516. }
  20517. if (parsedMesh.alphaIndex !== undefined) {
  20518. mesh.alphaIndex = parsedMesh.alphaIndex;
  20519. }
  20520. mesh.receiveShadows = parsedMesh.receiveShadows;
  20521. mesh.billboardMode = parsedMesh.billboardMode;
  20522. if (parsedMesh.visibility !== undefined) {
  20523. mesh.visibility = parsedMesh.visibility;
  20524. }
  20525. mesh.checkCollisions = parsedMesh.checkCollisions;
  20526. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20527. // freezeWorldMatrix
  20528. if (parsedMesh.freezeWorldMatrix) {
  20529. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20530. }
  20531. // Parent
  20532. if (parsedMesh.parentId) {
  20533. mesh._waitingParentId = parsedMesh.parentId;
  20534. }
  20535. // Actions
  20536. if (parsedMesh.actions !== undefined) {
  20537. mesh._waitingActions = parsedMesh.actions;
  20538. }
  20539. // Geometry
  20540. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20541. if (parsedMesh.delayLoadingFile) {
  20542. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20543. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20544. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20545. if (parsedMesh._binaryInfo) {
  20546. mesh._binaryInfo = parsedMesh._binaryInfo;
  20547. }
  20548. mesh._delayInfo = [];
  20549. if (parsedMesh.hasUVs) {
  20550. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20551. }
  20552. if (parsedMesh.hasUVs2) {
  20553. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20554. }
  20555. if (parsedMesh.hasUVs3) {
  20556. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20557. }
  20558. if (parsedMesh.hasUVs4) {
  20559. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20560. }
  20561. if (parsedMesh.hasUVs5) {
  20562. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20563. }
  20564. if (parsedMesh.hasUVs6) {
  20565. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20566. }
  20567. if (parsedMesh.hasColors) {
  20568. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20569. }
  20570. if (parsedMesh.hasMatricesIndices) {
  20571. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20572. }
  20573. if (parsedMesh.hasMatricesWeights) {
  20574. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20575. }
  20576. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20577. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20578. mesh._checkDelayState();
  20579. }
  20580. }
  20581. else {
  20582. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20583. }
  20584. // Material
  20585. if (parsedMesh.materialId) {
  20586. mesh.setMaterialByID(parsedMesh.materialId);
  20587. }
  20588. else {
  20589. mesh.material = null;
  20590. }
  20591. // Skeleton
  20592. if (parsedMesh.skeletonId > -1) {
  20593. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20594. if (parsedMesh.numBoneInfluencers) {
  20595. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20596. }
  20597. }
  20598. // Animations
  20599. if (parsedMesh.animations) {
  20600. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20601. var parsedAnimation = parsedMesh.animations[animationIndex];
  20602. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20603. }
  20604. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20605. }
  20606. if (parsedMesh.autoAnimate) {
  20607. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20608. }
  20609. // Layer Mask
  20610. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20611. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20612. }
  20613. else {
  20614. mesh.layerMask = 0x0FFFFFFF;
  20615. }
  20616. //(Deprecated) physics
  20617. if (parsedMesh.physicsImpostor) {
  20618. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20619. mass: parsedMesh.physicsMass,
  20620. friction: parsedMesh.physicsFriction,
  20621. restitution: parsedMesh.physicsRestitution
  20622. }, scene);
  20623. }
  20624. // Instances
  20625. if (parsedMesh.instances) {
  20626. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20627. var parsedInstance = parsedMesh.instances[index];
  20628. var instance = mesh.createInstance(parsedInstance.name);
  20629. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20630. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20631. if (parsedInstance.parentId) {
  20632. instance._waitingParentId = parsedInstance.parentId;
  20633. }
  20634. if (parsedInstance.rotationQuaternion) {
  20635. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20636. }
  20637. else if (parsedInstance.rotation) {
  20638. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20639. }
  20640. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20641. instance.checkCollisions = mesh.checkCollisions;
  20642. if (parsedMesh.animations) {
  20643. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20644. parsedAnimation = parsedMesh.animations[animationIndex];
  20645. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20646. }
  20647. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20648. }
  20649. }
  20650. }
  20651. return mesh;
  20652. };
  20653. /**
  20654. * Creates a ribbon mesh.
  20655. * Please consider using the same method from the MeshBuilder class instead.
  20656. * 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.
  20657. *
  20658. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20659. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20660. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20661. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20662. * 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.
  20663. * 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.
  20664. * 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
  20665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20666. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20668. */
  20669. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20670. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20671. pathArray: pathArray,
  20672. closeArray: closeArray,
  20673. closePath: closePath,
  20674. offset: offset,
  20675. updatable: updatable,
  20676. sideOrientation: sideOrientation,
  20677. instance: instance
  20678. }, scene);
  20679. };
  20680. /**
  20681. * Creates a plane polygonal mesh. By default, this is a disc.
  20682. * Please consider using the same method from the MeshBuilder class instead.
  20683. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20684. * 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.
  20685. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20686. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20687. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20688. */
  20689. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20690. var options = {
  20691. radius: radius,
  20692. tessellation: tessellation,
  20693. sideOrientation: sideOrientation,
  20694. updatable: updatable
  20695. };
  20696. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20697. };
  20698. /**
  20699. * Creates a box mesh.
  20700. * Please consider using the same method from the MeshBuilder class instead.
  20701. * The parameter `size` sets the size (float) of each box side (default 1).
  20702. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20703. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20704. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20705. */
  20706. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20707. var options = {
  20708. size: size,
  20709. sideOrientation: sideOrientation,
  20710. updatable: updatable
  20711. };
  20712. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20713. };
  20714. /**
  20715. * Creates a sphere mesh.
  20716. * Please consider using the same method from the MeshBuilder class instead.
  20717. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20718. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20719. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20720. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20722. */
  20723. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20724. var options = {
  20725. segments: segments,
  20726. diameterX: diameter,
  20727. diameterY: diameter,
  20728. diameterZ: diameter,
  20729. sideOrientation: sideOrientation,
  20730. updatable: updatable
  20731. };
  20732. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20733. };
  20734. /**
  20735. * Creates a cylinder or a cone mesh.
  20736. * Please consider using the same method from the MeshBuilder class instead.
  20737. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20738. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20739. * 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.
  20740. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20741. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20742. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20743. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20744. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20745. */
  20746. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20747. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20748. if (scene !== undefined) {
  20749. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20750. updatable = scene;
  20751. }
  20752. scene = subdivisions;
  20753. subdivisions = 1;
  20754. }
  20755. var options = {
  20756. height: height,
  20757. diameterTop: diameterTop,
  20758. diameterBottom: diameterBottom,
  20759. tessellation: tessellation,
  20760. subdivisions: subdivisions,
  20761. sideOrientation: sideOrientation,
  20762. updatable: updatable
  20763. };
  20764. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20765. };
  20766. // Torus (Code from SharpDX.org)
  20767. /**
  20768. * Creates a torus mesh.
  20769. * Please consider using the same method from the MeshBuilder class instead.
  20770. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20771. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20772. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20773. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20774. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20776. */
  20777. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20778. var options = {
  20779. diameter: diameter,
  20780. thickness: thickness,
  20781. tessellation: tessellation,
  20782. sideOrientation: sideOrientation,
  20783. updatable: updatable
  20784. };
  20785. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20786. };
  20787. /**
  20788. * Creates a torus knot mesh.
  20789. * Please consider using the same method from the MeshBuilder class instead.
  20790. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20791. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20792. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20793. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20794. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20795. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20797. */
  20798. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20799. var options = {
  20800. radius: radius,
  20801. tube: tube,
  20802. radialSegments: radialSegments,
  20803. tubularSegments: tubularSegments,
  20804. p: p,
  20805. q: q,
  20806. sideOrientation: sideOrientation,
  20807. updatable: updatable
  20808. };
  20809. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20810. };
  20811. /**
  20812. * Creates a line mesh.
  20813. * Please consider using the same method from the MeshBuilder class instead.
  20814. * 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.
  20815. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20816. * The parameter `points` is an array successive Vector3.
  20817. * 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
  20818. * When updating an instance, remember that only point positions can change, not the number of points.
  20819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20820. */
  20821. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20822. var options = {
  20823. points: points,
  20824. updatable: updatable,
  20825. instance: instance
  20826. };
  20827. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20828. };
  20829. /**
  20830. * Creates a dashed line mesh.
  20831. * Please consider using the same method from the MeshBuilder class instead.
  20832. * 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.
  20833. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20834. * The parameter `points` is an array successive Vector3.
  20835. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20836. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20837. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20838. * 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
  20839. * When updating an instance, remember that only point positions can change, not the number of points.
  20840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20841. */
  20842. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20843. var options = {
  20844. points: points,
  20845. dashSize: dashSize,
  20846. gapSize: gapSize,
  20847. dashNb: dashNb,
  20848. updatable: updatable,
  20849. instance: instance
  20850. };
  20851. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20852. };
  20853. /**
  20854. * Creates an extruded shape mesh.
  20855. * 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.
  20856. * Please consider using the same method from the MeshBuilder class instead.
  20857. *
  20858. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20859. * 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
  20860. * extruded along the Z axis.
  20861. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20862. * 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.
  20863. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20864. * 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
  20865. * 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
  20866. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20867. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20868. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20869. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20870. */
  20871. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20872. var options = {
  20873. shape: shape,
  20874. path: path,
  20875. scale: scale,
  20876. rotation: rotation,
  20877. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20878. sideOrientation: sideOrientation,
  20879. instance: instance,
  20880. updatable: updatable
  20881. };
  20882. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20883. };
  20884. /**
  20885. * Creates an custom extruded shape mesh.
  20886. * 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.
  20887. * Please consider using the same method from the MeshBuilder class instead.
  20888. *
  20889. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20890. * 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
  20891. * extruded along the Z axis.
  20892. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20893. * 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
  20894. * and the distance of this point from the begining of the path :
  20895. * ```javascript
  20896. * var rotationFunction = function(i, distance) {
  20897. * // do things
  20898. * return rotationValue; }
  20899. * ```
  20900. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20901. * 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
  20902. * and the distance of this point from the begining of the path :
  20903. * ```javascript
  20904. * var scaleFunction = function(i, distance) {
  20905. * // do things
  20906. * return scaleValue;}
  20907. * ```
  20908. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20909. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20910. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20911. * 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
  20912. * 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
  20913. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20914. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20915. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20916. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20917. */
  20918. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20919. var options = {
  20920. shape: shape,
  20921. path: path,
  20922. scaleFunction: scaleFunction,
  20923. rotationFunction: rotationFunction,
  20924. ribbonCloseArray: ribbonCloseArray,
  20925. ribbonClosePath: ribbonClosePath,
  20926. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20927. sideOrientation: sideOrientation,
  20928. instance: instance,
  20929. updatable: updatable
  20930. };
  20931. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20932. };
  20933. /**
  20934. * Creates lathe mesh.
  20935. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20936. * Please consider using the same method from the MeshBuilder class instead.
  20937. * 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
  20938. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20939. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20940. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20941. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20942. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20944. */
  20945. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20946. var options = {
  20947. shape: shape,
  20948. radius: radius,
  20949. tessellation: tessellation,
  20950. sideOrientation: sideOrientation,
  20951. updatable: updatable
  20952. };
  20953. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20954. };
  20955. /**
  20956. * Creates a plane mesh.
  20957. * Please consider using the same method from the MeshBuilder class instead.
  20958. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20959. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20960. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20961. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20962. */
  20963. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20964. var options = {
  20965. size: size,
  20966. width: size,
  20967. height: size,
  20968. sideOrientation: sideOrientation,
  20969. updatable: updatable
  20970. };
  20971. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20972. };
  20973. /**
  20974. * Creates a ground mesh.
  20975. * Please consider using the same method from the MeshBuilder class instead.
  20976. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20977. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20979. */
  20980. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20981. var options = {
  20982. width: width,
  20983. height: height,
  20984. subdivisions: subdivisions,
  20985. updatable: updatable
  20986. };
  20987. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20988. };
  20989. /**
  20990. * Creates a tiled ground mesh.
  20991. * Please consider using the same method from the MeshBuilder class instead.
  20992. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20993. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20994. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20995. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20996. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20997. * numbers of subdivisions on the ground width and height of each tile.
  20998. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20999. */
  21000. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21001. var options = {
  21002. xmin: xmin,
  21003. zmin: zmin,
  21004. xmax: xmax,
  21005. zmax: zmax,
  21006. subdivisions: subdivisions,
  21007. precision: precision,
  21008. updatable: updatable
  21009. };
  21010. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21011. };
  21012. /**
  21013. * Creates a ground mesh from a height map.
  21014. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21015. * Please consider using the same method from the MeshBuilder class instead.
  21016. * The parameter `url` sets the URL of the height map image resource.
  21017. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21018. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21019. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21020. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21021. * 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).
  21022. * This function is passed the newly built mesh :
  21023. * ```javascript
  21024. * function(mesh) { // do things
  21025. * return; }
  21026. * ```
  21027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21028. */
  21029. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21030. var options = {
  21031. width: width,
  21032. height: height,
  21033. subdivisions: subdivisions,
  21034. minHeight: minHeight,
  21035. maxHeight: maxHeight,
  21036. updatable: updatable,
  21037. onReady: onReady
  21038. };
  21039. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21040. };
  21041. /**
  21042. * Creates a tube mesh.
  21043. * 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.
  21044. * Please consider using the same method from the MeshBuilder class instead.
  21045. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21046. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21047. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21048. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21049. * 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.
  21050. * It must return a radius value (positive float) :
  21051. * ```javascript
  21052. * var radiusFunction = function(i, distance) {
  21053. * // do things
  21054. * return radius; }
  21055. * ```
  21056. * 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
  21057. * 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
  21058. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21059. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21060. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21061. */
  21062. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21063. var options = {
  21064. path: path,
  21065. radius: radius,
  21066. tessellation: tessellation,
  21067. radiusFunction: radiusFunction,
  21068. arc: 1,
  21069. cap: cap,
  21070. updatable: updatable,
  21071. sideOrientation: sideOrientation,
  21072. instance: instance
  21073. };
  21074. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21075. };
  21076. /**
  21077. * Creates a polyhedron mesh.
  21078. * Please consider using the same method from the MeshBuilder class instead.
  21079. * 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
  21080. * to choose the wanted type.
  21081. * The parameter `size` (positive float, default 1) sets the polygon size.
  21082. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21083. * 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`.
  21084. * 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
  21085. * 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)`).
  21086. * 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
  21087. * 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.
  21088. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21089. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21090. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21091. */
  21092. Mesh.CreatePolyhedron = function (name, options, scene) {
  21093. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21094. };
  21095. /**
  21096. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21097. * Please consider using the same method from the MeshBuilder class instead.
  21098. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21099. * 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`).
  21100. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21101. * 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.
  21102. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21103. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21105. */
  21106. Mesh.CreateIcoSphere = function (name, options, scene) {
  21107. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21108. };
  21109. /**
  21110. * Creates a decal mesh.
  21111. * Please consider using the same method from the MeshBuilder class instead.
  21112. * 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.
  21113. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21114. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21115. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21116. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21117. */
  21118. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21119. var options = {
  21120. position: position,
  21121. normal: normal,
  21122. size: size,
  21123. angle: angle
  21124. };
  21125. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21126. };
  21127. // Skeletons
  21128. /**
  21129. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21130. */
  21131. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21132. var source;
  21133. if (!this._sourcePositions) {
  21134. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21135. this._sourcePositions = new Float32Array(source);
  21136. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21137. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21138. }
  21139. }
  21140. return this._sourcePositions;
  21141. };
  21142. /**
  21143. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21144. */
  21145. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21146. var source;
  21147. if (!this._sourceNormals) {
  21148. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21149. this._sourceNormals = new Float32Array(source);
  21150. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21151. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21152. }
  21153. }
  21154. return this._sourceNormals;
  21155. };
  21156. /**
  21157. * Update the vertex buffers by applying transformation from the bones
  21158. * @param {skeleton} skeleton to apply
  21159. */
  21160. Mesh.prototype.applySkeleton = function (skeleton) {
  21161. if (!this.geometry) {
  21162. return;
  21163. }
  21164. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21165. return;
  21166. }
  21167. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21168. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21169. return this;
  21170. }
  21171. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21172. return this;
  21173. }
  21174. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21175. return this;
  21176. }
  21177. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21178. return this;
  21179. }
  21180. if (!this._sourcePositions) {
  21181. this.setPositionsForCPUSkinning();
  21182. }
  21183. if (!this._sourceNormals) {
  21184. this.setNormalsForCPUSkinning();
  21185. }
  21186. // positionsData checks for not being Float32Array will only pass at most once
  21187. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21188. if (!(positionsData instanceof Float32Array)) {
  21189. positionsData = new Float32Array(positionsData);
  21190. }
  21191. // normalsData checks for not being Float32Array will only pass at most once
  21192. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21193. if (!(normalsData instanceof Float32Array)) {
  21194. normalsData = new Float32Array(normalsData);
  21195. }
  21196. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21197. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21198. var needExtras = this.numBoneInfluencers > 4;
  21199. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21200. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21201. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21202. var tempVector3 = BABYLON.Vector3.Zero();
  21203. var finalMatrix = new BABYLON.Matrix();
  21204. var tempMatrix = new BABYLON.Matrix();
  21205. var matWeightIdx = 0;
  21206. var inf;
  21207. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21208. var weight;
  21209. for (inf = 0; inf < 4; inf++) {
  21210. weight = matricesWeightsData[matWeightIdx + inf];
  21211. if (weight > 0) {
  21212. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21213. finalMatrix.addToSelf(tempMatrix);
  21214. }
  21215. else
  21216. break;
  21217. }
  21218. if (needExtras) {
  21219. for (inf = 0; inf < 4; inf++) {
  21220. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21221. if (weight > 0) {
  21222. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21223. finalMatrix.addToSelf(tempMatrix);
  21224. }
  21225. else
  21226. break;
  21227. }
  21228. }
  21229. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21230. tempVector3.toArray(positionsData, index);
  21231. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21232. tempVector3.toArray(normalsData, index);
  21233. finalMatrix.reset();
  21234. }
  21235. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21236. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21237. return this;
  21238. };
  21239. // Tools
  21240. /**
  21241. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21242. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21243. */
  21244. Mesh.MinMax = function (meshes) {
  21245. var minVector = null;
  21246. var maxVector = null;
  21247. meshes.forEach(function (mesh, index, array) {
  21248. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21249. if (!minVector) {
  21250. minVector = boundingBox.minimumWorld;
  21251. maxVector = boundingBox.maximumWorld;
  21252. }
  21253. else {
  21254. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21255. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21256. }
  21257. });
  21258. return {
  21259. min: minVector,
  21260. max: maxVector
  21261. };
  21262. };
  21263. /**
  21264. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21265. */
  21266. Mesh.Center = function (meshesOrMinMaxVector) {
  21267. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21268. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21269. };
  21270. /**
  21271. * Merge the array of meshes into a single mesh for performance reasons.
  21272. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21273. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21274. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21275. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21276. */
  21277. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21278. if (disposeSource === void 0) { disposeSource = true; }
  21279. var index;
  21280. if (!allow32BitsIndices) {
  21281. var totalVertices = 0;
  21282. // Counting vertices
  21283. for (index = 0; index < meshes.length; index++) {
  21284. if (meshes[index]) {
  21285. totalVertices += meshes[index].getTotalVertices();
  21286. if (totalVertices > 65536) {
  21287. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21288. return null;
  21289. }
  21290. }
  21291. }
  21292. }
  21293. // Merge
  21294. var vertexData;
  21295. var otherVertexData;
  21296. var source;
  21297. for (index = 0; index < meshes.length; index++) {
  21298. if (meshes[index]) {
  21299. meshes[index].computeWorldMatrix(true);
  21300. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21301. otherVertexData.transform(meshes[index].getWorldMatrix());
  21302. if (vertexData) {
  21303. vertexData.merge(otherVertexData);
  21304. }
  21305. else {
  21306. vertexData = otherVertexData;
  21307. source = meshes[index];
  21308. }
  21309. }
  21310. }
  21311. if (!meshSubclass) {
  21312. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21313. }
  21314. vertexData.applyToMesh(meshSubclass);
  21315. // Setting properties
  21316. meshSubclass.material = source.material;
  21317. meshSubclass.checkCollisions = source.checkCollisions;
  21318. // Cleaning
  21319. if (disposeSource) {
  21320. for (index = 0; index < meshes.length; index++) {
  21321. if (meshes[index]) {
  21322. meshes[index].dispose();
  21323. }
  21324. }
  21325. }
  21326. return meshSubclass;
  21327. };
  21328. // Consts
  21329. Mesh._FRONTSIDE = 0;
  21330. Mesh._BACKSIDE = 1;
  21331. Mesh._DOUBLESIDE = 2;
  21332. Mesh._DEFAULTSIDE = 0;
  21333. Mesh._NO_CAP = 0;
  21334. Mesh._CAP_START = 1;
  21335. Mesh._CAP_END = 2;
  21336. Mesh._CAP_ALL = 3;
  21337. return Mesh;
  21338. }(BABYLON.AbstractMesh));
  21339. BABYLON.Mesh = Mesh;
  21340. })(BABYLON || (BABYLON = {}));
  21341. var BABYLON;
  21342. (function (BABYLON) {
  21343. var SubMesh = (function () {
  21344. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21345. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21346. this.materialIndex = materialIndex;
  21347. this.verticesStart = verticesStart;
  21348. this.verticesCount = verticesCount;
  21349. this.indexStart = indexStart;
  21350. this.indexCount = indexCount;
  21351. this._renderId = 0;
  21352. this._mesh = mesh;
  21353. this._renderingMesh = renderingMesh || mesh;
  21354. mesh.subMeshes.push(this);
  21355. this._trianglePlanes = [];
  21356. this._id = mesh.subMeshes.length - 1;
  21357. if (createBoundingBox) {
  21358. this.refreshBoundingInfo();
  21359. mesh.computeWorldMatrix(true);
  21360. }
  21361. }
  21362. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21363. get: function () {
  21364. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21365. },
  21366. enumerable: true,
  21367. configurable: true
  21368. });
  21369. SubMesh.prototype.getBoundingInfo = function () {
  21370. if (this.IsGlobal) {
  21371. return this._mesh.getBoundingInfo();
  21372. }
  21373. return this._boundingInfo;
  21374. };
  21375. SubMesh.prototype.getMesh = function () {
  21376. return this._mesh;
  21377. };
  21378. SubMesh.prototype.getRenderingMesh = function () {
  21379. return this._renderingMesh;
  21380. };
  21381. SubMesh.prototype.getMaterial = function () {
  21382. var rootMaterial = this._renderingMesh.material;
  21383. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  21384. var multiMaterial = rootMaterial;
  21385. return multiMaterial.getSubMaterial(this.materialIndex);
  21386. }
  21387. if (!rootMaterial) {
  21388. return this._mesh.getScene().defaultMaterial;
  21389. }
  21390. return rootMaterial;
  21391. };
  21392. // Methods
  21393. SubMesh.prototype.refreshBoundingInfo = function () {
  21394. this._lastColliderWorldVertices = null;
  21395. if (this.IsGlobal) {
  21396. return;
  21397. }
  21398. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21399. if (!data) {
  21400. this._boundingInfo = this._mesh._boundingInfo;
  21401. return;
  21402. }
  21403. var indices = this._renderingMesh.getIndices();
  21404. var extend;
  21405. //is this the only submesh?
  21406. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21407. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21408. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21409. }
  21410. else {
  21411. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21412. }
  21413. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21414. };
  21415. SubMesh.prototype._checkCollision = function (collider) {
  21416. return this.getBoundingInfo()._checkCollision(collider);
  21417. };
  21418. SubMesh.prototype.updateBoundingInfo = function (world) {
  21419. if (!this.getBoundingInfo()) {
  21420. this.refreshBoundingInfo();
  21421. }
  21422. this.getBoundingInfo().update(world);
  21423. };
  21424. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21425. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21426. };
  21427. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21428. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21429. };
  21430. SubMesh.prototype.render = function (enableAlphaMode) {
  21431. this._renderingMesh.render(this, enableAlphaMode);
  21432. };
  21433. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21434. if (!this._linesIndexBuffer) {
  21435. var linesIndices = [];
  21436. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21437. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21438. }
  21439. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21440. this.linesIndexCount = linesIndices.length;
  21441. }
  21442. return this._linesIndexBuffer;
  21443. };
  21444. SubMesh.prototype.canIntersects = function (ray) {
  21445. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21446. };
  21447. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21448. var intersectInfo = null;
  21449. // LineMesh first as it's also a Mesh...
  21450. if (this._mesh instanceof BABYLON.LinesMesh) {
  21451. var lineMesh = this._mesh;
  21452. // Line test
  21453. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21454. var p0 = positions[indices[index]];
  21455. var p1 = positions[indices[index + 1]];
  21456. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21457. if (length < 0) {
  21458. continue;
  21459. }
  21460. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21461. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21462. if (fastCheck) {
  21463. break;
  21464. }
  21465. }
  21466. }
  21467. }
  21468. else {
  21469. // Triangles test
  21470. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21471. var p0 = positions[indices[index]];
  21472. var p1 = positions[indices[index + 1]];
  21473. var p2 = positions[indices[index + 2]];
  21474. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21475. if (currentIntersectInfo) {
  21476. if (currentIntersectInfo.distance < 0) {
  21477. continue;
  21478. }
  21479. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21480. intersectInfo = currentIntersectInfo;
  21481. intersectInfo.faceId = index / 3;
  21482. if (fastCheck) {
  21483. break;
  21484. }
  21485. }
  21486. }
  21487. }
  21488. }
  21489. return intersectInfo;
  21490. };
  21491. // Clone
  21492. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21493. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21494. if (!this.IsGlobal) {
  21495. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21496. }
  21497. return result;
  21498. };
  21499. // Dispose
  21500. SubMesh.prototype.dispose = function () {
  21501. if (this._linesIndexBuffer) {
  21502. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21503. this._linesIndexBuffer = null;
  21504. }
  21505. // Remove from mesh
  21506. var index = this._mesh.subMeshes.indexOf(this);
  21507. this._mesh.subMeshes.splice(index, 1);
  21508. };
  21509. // Statics
  21510. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21511. var minVertexIndex = Number.MAX_VALUE;
  21512. var maxVertexIndex = -Number.MAX_VALUE;
  21513. renderingMesh = renderingMesh || mesh;
  21514. var indices = renderingMesh.getIndices();
  21515. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21516. var vertexIndex = indices[index];
  21517. if (vertexIndex < minVertexIndex)
  21518. minVertexIndex = vertexIndex;
  21519. if (vertexIndex > maxVertexIndex)
  21520. maxVertexIndex = vertexIndex;
  21521. }
  21522. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21523. };
  21524. return SubMesh;
  21525. }());
  21526. BABYLON.SubMesh = SubMesh;
  21527. })(BABYLON || (BABYLON = {}));
  21528. var BABYLON;
  21529. (function (BABYLON) {
  21530. var MeshBuilder = (function () {
  21531. function MeshBuilder() {
  21532. }
  21533. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  21534. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  21535. return BABYLON.Mesh.DOUBLESIDE;
  21536. }
  21537. if (orientation === undefined || orientation === null) {
  21538. return BABYLON.Mesh.FRONTSIDE;
  21539. }
  21540. return orientation;
  21541. };
  21542. /**
  21543. * Creates a box mesh.
  21544. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21545. * The parameter `size` sets the size (float) of each box side (default 1).
  21546. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21547. * 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).
  21548. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21549. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21550. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21552. */
  21553. MeshBuilder.CreateBox = function (name, options, scene) {
  21554. var box = new BABYLON.Mesh(name, scene);
  21555. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21556. var vertexData = BABYLON.VertexData.CreateBox(options);
  21557. vertexData.applyToMesh(box, options.updatable);
  21558. return box;
  21559. };
  21560. /**
  21561. * Creates a sphere mesh.
  21562. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21563. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21564. * 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`).
  21565. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21566. * 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
  21567. * 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).
  21568. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21569. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21571. */
  21572. MeshBuilder.CreateSphere = function (name, options, scene) {
  21573. var sphere = new BABYLON.Mesh(name, scene);
  21574. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21575. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21576. vertexData.applyToMesh(sphere, options.updatable);
  21577. return sphere;
  21578. };
  21579. /**
  21580. * Creates a plane polygonal mesh. By default, this is a disc.
  21581. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21582. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21583. * 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.
  21584. * 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
  21585. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21586. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21587. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21588. */
  21589. MeshBuilder.CreateDisc = function (name, options, scene) {
  21590. var disc = new BABYLON.Mesh(name, scene);
  21591. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21592. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21593. vertexData.applyToMesh(disc, options.updatable);
  21594. return disc;
  21595. };
  21596. /**
  21597. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21598. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21599. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21600. * 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`).
  21601. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21602. * 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.
  21603. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21604. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21606. */
  21607. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21608. var sphere = new BABYLON.Mesh(name, scene);
  21609. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21610. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21611. vertexData.applyToMesh(sphere, options.updatable);
  21612. return sphere;
  21613. };
  21614. ;
  21615. /**
  21616. * Creates a ribbon mesh.
  21617. * 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.
  21618. *
  21619. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21620. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21621. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21622. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21623. * 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.
  21624. * 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.
  21625. * 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
  21626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21627. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21628. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21630. */
  21631. MeshBuilder.CreateRibbon = function (name, options, scene) {
  21632. var pathArray = options.pathArray;
  21633. var closeArray = options.closeArray;
  21634. var closePath = options.closePath;
  21635. var offset = options.offset;
  21636. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21637. var instance = options.instance;
  21638. var updatable = options.updatable;
  21639. if (instance) {
  21640. // positionFunction : ribbon case
  21641. // only pathArray and sideOrientation parameters are taken into account for positions update
  21642. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21643. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21644. var positionFunction = function (positions) {
  21645. var minlg = pathArray[0].length;
  21646. var i = 0;
  21647. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21648. for (var si = 1; si <= ns; si++) {
  21649. for (var p = 0; p < pathArray.length; p++) {
  21650. var path = pathArray[p];
  21651. var l = path.length;
  21652. minlg = (minlg < l) ? minlg : l;
  21653. var j = 0;
  21654. while (j < minlg) {
  21655. positions[i] = path[j].x;
  21656. positions[i + 1] = path[j].y;
  21657. positions[i + 2] = path[j].z;
  21658. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21659. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21660. }
  21661. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21662. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21663. }
  21664. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21665. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21666. }
  21667. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21668. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21669. }
  21670. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21671. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21672. }
  21673. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21674. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21675. }
  21676. j++;
  21677. i += 3;
  21678. }
  21679. if (instance._closePath) {
  21680. positions[i] = path[0].x;
  21681. positions[i + 1] = path[0].y;
  21682. positions[i + 2] = path[0].z;
  21683. i += 3;
  21684. }
  21685. }
  21686. }
  21687. };
  21688. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21689. positionFunction(positions);
  21690. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21691. instance._boundingInfo.update(instance._worldMatrix);
  21692. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21693. if (!(instance.areNormalsFrozen)) {
  21694. var indices = instance.getIndices();
  21695. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21696. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21697. if (instance._closePath) {
  21698. var indexFirst = 0;
  21699. var indexLast = 0;
  21700. for (var p = 0; p < pathArray.length; p++) {
  21701. indexFirst = instance._idx[p] * 3;
  21702. if (p + 1 < pathArray.length) {
  21703. indexLast = (instance._idx[p + 1] - 1) * 3;
  21704. }
  21705. else {
  21706. indexLast = normals.length - 3;
  21707. }
  21708. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21709. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21710. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21711. normals[indexLast] = normals[indexFirst];
  21712. normals[indexLast + 1] = normals[indexFirst + 1];
  21713. normals[indexLast + 2] = normals[indexFirst + 2];
  21714. }
  21715. }
  21716. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21717. }
  21718. return instance;
  21719. }
  21720. else {
  21721. var ribbon = new BABYLON.Mesh(name, scene);
  21722. ribbon.sideOrientation = sideOrientation;
  21723. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21724. if (closePath) {
  21725. ribbon._idx = vertexData._idx;
  21726. }
  21727. ribbon._closePath = closePath;
  21728. ribbon._closeArray = closeArray;
  21729. vertexData.applyToMesh(ribbon, updatable);
  21730. return ribbon;
  21731. }
  21732. };
  21733. /**
  21734. * Creates a cylinder or a cone mesh.
  21735. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21736. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21737. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21738. * 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.
  21739. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21740. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21741. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21742. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21743. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21744. * 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).
  21745. * 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
  21746. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21747. * 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
  21748. * 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.
  21749. * If `enclose` is false, a ring surface is one element.
  21750. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21751. * 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
  21752. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21753. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21754. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21755. */
  21756. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21757. var cylinder = new BABYLON.Mesh(name, scene);
  21758. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21759. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21760. vertexData.applyToMesh(cylinder, options.updatable);
  21761. return cylinder;
  21762. };
  21763. /**
  21764. * Creates a torus mesh.
  21765. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21766. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21767. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21768. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21769. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21770. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21772. */
  21773. MeshBuilder.CreateTorus = function (name, options, scene) {
  21774. var torus = new BABYLON.Mesh(name, scene);
  21775. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21776. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21777. vertexData.applyToMesh(torus, options.updatable);
  21778. return torus;
  21779. };
  21780. /**
  21781. * Creates a torus knot mesh.
  21782. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21783. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21784. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21785. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21786. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21787. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21788. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21789. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21790. */
  21791. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21792. var torusKnot = new BABYLON.Mesh(name, scene);
  21793. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21794. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21795. vertexData.applyToMesh(torusKnot, options.updatable);
  21796. return torusKnot;
  21797. };
  21798. /**
  21799. * Creates a line system mesh.
  21800. * A line system is a pool of many lines gathered in a single mesh.
  21801. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21802. * 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.
  21803. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21804. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21805. * 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
  21806. * 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
  21807. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21809. */
  21810. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  21811. var instance = options.instance;
  21812. var lines = options.lines;
  21813. if (instance) {
  21814. var positionFunction = function (positions) {
  21815. var i = 0;
  21816. for (var l = 0; l < lines.length; l++) {
  21817. var points = lines[l];
  21818. for (var p = 0; p < points.length; p++) {
  21819. positions[i] = points[p].x;
  21820. positions[i + 1] = points[p].y;
  21821. positions[i + 2] = points[p].z;
  21822. i += 3;
  21823. }
  21824. }
  21825. };
  21826. instance.updateMeshPositions(positionFunction, false);
  21827. return instance;
  21828. }
  21829. // line system creation
  21830. var lineSystem = new BABYLON.LinesMesh(name, scene);
  21831. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  21832. vertexData.applyToMesh(lineSystem, options.updatable);
  21833. return lineSystem;
  21834. };
  21835. /**
  21836. * Creates a line mesh.
  21837. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  21838. * 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.
  21839. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21840. * The parameter `points` is an array successive Vector3.
  21841. * 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
  21842. * When updating an instance, remember that only point positions can change, not the number of points.
  21843. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21844. */
  21845. MeshBuilder.CreateLines = function (name, options, scene) {
  21846. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  21847. return lines;
  21848. };
  21849. /**
  21850. * Creates a dashed line mesh.
  21851. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  21852. * 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.
  21853. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21854. * The parameter `points` is an array successive Vector3.
  21855. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21856. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21857. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21858. * 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
  21859. * When updating an instance, remember that only point positions can change, not the number of points.
  21860. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21861. */
  21862. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  21863. var points = options.points;
  21864. var instance = options.instance;
  21865. var gapSize = options.gapSize;
  21866. var dashNb = options.dashNb;
  21867. var dashSize = options.dashSize;
  21868. if (instance) {
  21869. var positionFunction = function (positions) {
  21870. var curvect = BABYLON.Vector3.Zero();
  21871. var nbSeg = positions.length / 6;
  21872. var lg = 0;
  21873. var nb = 0;
  21874. var shft = 0;
  21875. var dashshft = 0;
  21876. var curshft = 0;
  21877. var p = 0;
  21878. var i = 0;
  21879. var j = 0;
  21880. for (i = 0; i < points.length - 1; i++) {
  21881. points[i + 1].subtractToRef(points[i], curvect);
  21882. lg += curvect.length();
  21883. }
  21884. shft = lg / nbSeg;
  21885. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  21886. for (i = 0; i < points.length - 1; i++) {
  21887. points[i + 1].subtractToRef(points[i], curvect);
  21888. nb = Math.floor(curvect.length() / shft);
  21889. curvect.normalize();
  21890. j = 0;
  21891. while (j < nb && p < positions.length) {
  21892. curshft = shft * j;
  21893. positions[p] = points[i].x + curshft * curvect.x;
  21894. positions[p + 1] = points[i].y + curshft * curvect.y;
  21895. positions[p + 2] = points[i].z + curshft * curvect.z;
  21896. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  21897. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  21898. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  21899. p += 6;
  21900. j++;
  21901. }
  21902. }
  21903. while (p < positions.length) {
  21904. positions[p] = points[i].x;
  21905. positions[p + 1] = points[i].y;
  21906. positions[p + 2] = points[i].z;
  21907. p += 3;
  21908. }
  21909. };
  21910. instance.updateMeshPositions(positionFunction, false);
  21911. return instance;
  21912. }
  21913. // dashed lines creation
  21914. var dashedLines = new BABYLON.LinesMesh(name, scene);
  21915. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  21916. vertexData.applyToMesh(dashedLines, options.updatable);
  21917. dashedLines.dashSize = dashSize;
  21918. dashedLines.gapSize = gapSize;
  21919. return dashedLines;
  21920. };
  21921. /**
  21922. * Creates an extruded shape mesh.
  21923. * 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.
  21924. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  21925. *
  21926. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21927. * 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
  21928. * extruded along the Z axis.
  21929. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21930. * 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.
  21931. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21932. * 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
  21933. * 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
  21934. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21936. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21937. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21939. */
  21940. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  21941. var path = options.path;
  21942. var shape = options.shape;
  21943. var scale = options.scale || 1;
  21944. var rotation = options.rotation || 0;
  21945. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21946. var updatable = options.updatable;
  21947. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21948. var instance = options.instance;
  21949. var invertUV = options.invertUV || false;
  21950. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  21951. };
  21952. /**
  21953. * Creates an custom extruded shape mesh.
  21954. * 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.
  21955. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  21956. *
  21957. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21958. * 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
  21959. * extruded along the Z axis.
  21960. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21961. * 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
  21962. * and the distance of this point from the begining of the path :
  21963. * ```javascript
  21964. * var rotationFunction = function(i, distance) {
  21965. * // do things
  21966. * return rotationValue; }
  21967. * ```
  21968. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21969. * 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
  21970. * and the distance of this point from the begining of the path :
  21971. * ```javascript
  21972. * var scaleFunction = function(i, distance) {
  21973. * // do things
  21974. * return scaleValue;}
  21975. * ```
  21976. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21977. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21978. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21979. * 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
  21980. * 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
  21981. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21982. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21983. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21984. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21985. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21986. */
  21987. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  21988. var path = options.path;
  21989. var shape = options.shape;
  21990. var scaleFunction = options.scaleFunction || (function () { return 1; });
  21991. var rotationFunction = options.rotationFunction || (function () { return 0; });
  21992. var ribbonCloseArray = options.ribbonCloseArray || false;
  21993. var ribbonClosePath = options.ribbonClosePath || false;
  21994. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21995. var updatable = options.updatable;
  21996. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21997. var instance = options.instance;
  21998. var invertUV = options.invertUV || false;
  21999. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22000. };
  22001. /**
  22002. * Creates lathe mesh.
  22003. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22004. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22005. *
  22006. * 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
  22007. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22008. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22009. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22010. * 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.
  22011. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22012. * 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
  22013. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22015. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22016. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22017. */
  22018. MeshBuilder.CreateLathe = function (name, options, scene) {
  22019. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22020. var closed = (options.closed === undefined) ? true : options.closed;
  22021. var shape = options.shape;
  22022. var radius = options.radius || 1;
  22023. var tessellation = options.tessellation || 64;
  22024. var updatable = options.updatable;
  22025. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22026. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22027. var pi2 = Math.PI * 2;
  22028. var paths = new Array();
  22029. var invertUV = options.invertUV || false;
  22030. var i = 0;
  22031. var p = 0;
  22032. var step = pi2 / tessellation * arc;
  22033. var rotated;
  22034. var path = new Array();
  22035. ;
  22036. for (i = 0; i <= tessellation; i++) {
  22037. var path = [];
  22038. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22039. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22040. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22041. }
  22042. for (p = 0; p < shape.length; p++) {
  22043. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22044. path.push(rotated);
  22045. }
  22046. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22047. 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));
  22048. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22049. }
  22050. paths.push(path);
  22051. }
  22052. // lathe ribbon
  22053. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22054. return lathe;
  22055. };
  22056. /**
  22057. * Creates a plane mesh.
  22058. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22059. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22060. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22061. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22062. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22063. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22064. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22065. */
  22066. MeshBuilder.CreatePlane = function (name, options, scene) {
  22067. var plane = new BABYLON.Mesh(name, scene);
  22068. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22069. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22070. vertexData.applyToMesh(plane, options.updatable);
  22071. if (options.sourcePlane) {
  22072. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22073. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22074. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22075. plane.rotate(vectorProduct, product);
  22076. }
  22077. return plane;
  22078. };
  22079. /**
  22080. * Creates a ground mesh.
  22081. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22082. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22083. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22084. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22085. */
  22086. MeshBuilder.CreateGround = function (name, options, scene) {
  22087. var ground = new BABYLON.GroundMesh(name, scene);
  22088. ground._setReady(false);
  22089. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22090. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22091. ground._width = options.width || 1;
  22092. ground._height = options.height || 1;
  22093. ground._maxX = ground._width / 2;
  22094. ground._maxZ = ground._height / 2;
  22095. ground._minX = -ground._maxX;
  22096. ground._minZ = -ground._maxZ;
  22097. var vertexData = BABYLON.VertexData.CreateGround(options);
  22098. vertexData.applyToMesh(ground, options.updatable);
  22099. ground._setReady(true);
  22100. return ground;
  22101. };
  22102. /**
  22103. * Creates a tiled ground mesh.
  22104. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22105. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22106. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22107. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22108. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22109. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22110. * numbers of subdivisions on the ground width and height of each tile.
  22111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22112. */
  22113. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22114. var tiledGround = new BABYLON.Mesh(name, scene);
  22115. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22116. vertexData.applyToMesh(tiledGround, options.updatable);
  22117. return tiledGround;
  22118. };
  22119. /**
  22120. * Creates a ground mesh from a height map.
  22121. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22122. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22123. * The parameter `url` sets the URL of the height map image resource.
  22124. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22125. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22126. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22127. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22128. * 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).
  22129. * This function is passed the newly built mesh :
  22130. * ```javascript
  22131. * function(mesh) { // do things
  22132. * return; }
  22133. * ```
  22134. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22135. */
  22136. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22137. var width = options.width || 10.0;
  22138. var height = options.height || 10.0;
  22139. var subdivisions = options.subdivisions || 1 | 0;
  22140. var minHeight = options.minHeight || 0.0;
  22141. var maxHeight = options.maxHeight || 10.0;
  22142. var updatable = options.updatable;
  22143. var onReady = options.onReady;
  22144. var ground = new BABYLON.GroundMesh(name, scene);
  22145. ground._subdivisionsX = subdivisions;
  22146. ground._subdivisionsY = subdivisions;
  22147. ground._width = width;
  22148. ground._height = height;
  22149. ground._maxX = ground._width / 2.0;
  22150. ground._maxZ = ground._height / 2.0;
  22151. ground._minX = -ground._maxX;
  22152. ground._minZ = -ground._maxZ;
  22153. ground._setReady(false);
  22154. var onload = function (img) {
  22155. // Getting height map data
  22156. var canvas = document.createElement("canvas");
  22157. var context = canvas.getContext("2d");
  22158. var bufferWidth = img.width;
  22159. var bufferHeight = img.height;
  22160. canvas.width = bufferWidth;
  22161. canvas.height = bufferHeight;
  22162. context.drawImage(img, 0, 0);
  22163. // Create VertexData from map data
  22164. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22165. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22166. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22167. width: width, height: height,
  22168. subdivisions: subdivisions,
  22169. minHeight: minHeight, maxHeight: maxHeight,
  22170. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22171. });
  22172. vertexData.applyToMesh(ground, updatable);
  22173. ground._setReady(true);
  22174. //execute ready callback, if set
  22175. if (onReady) {
  22176. onReady(ground);
  22177. }
  22178. };
  22179. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22180. return ground;
  22181. };
  22182. /**
  22183. * Creates a tube mesh.
  22184. * 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.
  22185. *
  22186. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22187. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22188. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22189. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22190. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22191. * 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.
  22192. * It must return a radius value (positive float) :
  22193. * ```javascript
  22194. * var radiusFunction = function(i, distance) {
  22195. * // do things
  22196. * return radius; }
  22197. * ```
  22198. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22199. * 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
  22200. * 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
  22201. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22202. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22203. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22204. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22205. */
  22206. MeshBuilder.CreateTube = function (name, options, scene) {
  22207. var path = options.path;
  22208. var radius = options.radius || 1.0;
  22209. var tessellation = options.tessellation || 64 | 0;
  22210. var radiusFunction = options.radiusFunction;
  22211. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22212. var invertUV = options.invertUV || false;
  22213. var updatable = options.updatable;
  22214. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22215. var instance = options.instance;
  22216. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22217. // tube geometry
  22218. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22219. var tangents = path3D.getTangents();
  22220. var normals = path3D.getNormals();
  22221. var distances = path3D.getDistances();
  22222. var pi2 = Math.PI * 2;
  22223. var step = pi2 / tessellation * arc;
  22224. var returnRadius = function () { return radius; };
  22225. var radiusFunctionFinal = radiusFunction || returnRadius;
  22226. var circlePath;
  22227. var rad;
  22228. var normal;
  22229. var rotated;
  22230. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22231. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22232. for (var i = 0; i < path.length; i++) {
  22233. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22234. circlePath = Array(); // current circle array
  22235. normal = normals[i]; // current normal
  22236. for (var t = 0; t < tessellation; t++) {
  22237. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22238. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22239. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22240. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22241. circlePath[t] = rotated;
  22242. }
  22243. circlePaths[index] = circlePath;
  22244. index++;
  22245. }
  22246. // cap
  22247. var capPath = function (nbPoints, pathIndex) {
  22248. var pointCap = Array();
  22249. for (var i = 0; i < nbPoints; i++) {
  22250. pointCap.push(path[pathIndex]);
  22251. }
  22252. return pointCap;
  22253. };
  22254. switch (cap) {
  22255. case BABYLON.Mesh.NO_CAP:
  22256. break;
  22257. case BABYLON.Mesh.CAP_START:
  22258. circlePaths[0] = capPath(tessellation, 0);
  22259. circlePaths[1] = circlePaths[2].slice(0);
  22260. break;
  22261. case BABYLON.Mesh.CAP_END:
  22262. circlePaths[index] = circlePaths[index - 1].slice(0);
  22263. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22264. break;
  22265. case BABYLON.Mesh.CAP_ALL:
  22266. circlePaths[0] = capPath(tessellation, 0);
  22267. circlePaths[1] = circlePaths[2].slice(0);
  22268. circlePaths[index] = circlePaths[index - 1].slice(0);
  22269. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22270. break;
  22271. default:
  22272. break;
  22273. }
  22274. return circlePaths;
  22275. };
  22276. var path3D;
  22277. var pathArray;
  22278. if (instance) {
  22279. var arc = options.arc || instance.arc;
  22280. path3D = (instance.path3D).update(path);
  22281. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22282. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22283. instance.path3D = path3D;
  22284. instance.pathArray = pathArray;
  22285. instance.arc = arc;
  22286. return instance;
  22287. }
  22288. // tube creation
  22289. path3D = new BABYLON.Path3D(path);
  22290. var newPathArray = new Array();
  22291. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22292. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22293. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22294. tube.pathArray = pathArray;
  22295. tube.path3D = path3D;
  22296. tube.tessellation = tessellation;
  22297. tube.cap = cap;
  22298. tube.arc = options.arc;
  22299. return tube;
  22300. };
  22301. /**
  22302. * Creates a polyhedron mesh.
  22303. *
  22304. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22305. * 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
  22306. * to choose the wanted type.
  22307. * The parameter `size` (positive float, default 1) sets the polygon size.
  22308. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22309. * 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`.
  22310. * 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
  22311. * 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)`).
  22312. * 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
  22313. * 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.
  22314. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22315. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22316. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22317. */
  22318. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22319. var polyhedron = new BABYLON.Mesh(name, scene);
  22320. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22321. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22322. vertexData.applyToMesh(polyhedron, options.updatable);
  22323. return polyhedron;
  22324. };
  22325. /**
  22326. * Creates a decal mesh.
  22327. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22328. * 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.
  22329. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22330. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22331. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22332. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22333. */
  22334. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22335. var indices = sourceMesh.getIndices();
  22336. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22337. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22338. var position = options.position || BABYLON.Vector3.Zero();
  22339. var normal = options.normal || BABYLON.Vector3.Up();
  22340. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22341. var angle = options.angle || 0;
  22342. // Getting correct rotation
  22343. if (!normal) {
  22344. var target = new BABYLON.Vector3(0, 0, 1);
  22345. var camera = sourceMesh.getScene().activeCamera;
  22346. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22347. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22348. }
  22349. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22350. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22351. var pitch = Math.atan2(normal.y, len);
  22352. // Matrix
  22353. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22354. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22355. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22356. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22357. var vertexData = new BABYLON.VertexData();
  22358. vertexData.indices = [];
  22359. vertexData.positions = [];
  22360. vertexData.normals = [];
  22361. vertexData.uvs = [];
  22362. var currentVertexDataIndex = 0;
  22363. var extractDecalVector3 = function (indexId) {
  22364. var vertexId = indices[indexId];
  22365. var result = new BABYLON.PositionNormalVertex();
  22366. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  22367. // Send vector to decal local world
  22368. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  22369. // Get normal
  22370. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  22371. return result;
  22372. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  22373. var clip = function (vertices, axis) {
  22374. if (vertices.length === 0) {
  22375. return vertices;
  22376. }
  22377. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  22378. var clipVertices = function (v0, v1) {
  22379. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  22380. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  22381. };
  22382. var result = new Array();
  22383. for (var index = 0; index < vertices.length; index += 3) {
  22384. var v1Out;
  22385. var v2Out;
  22386. var v3Out;
  22387. var total = 0;
  22388. var nV1, nV2, nV3, nV4;
  22389. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  22390. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  22391. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  22392. v1Out = d1 > 0;
  22393. v2Out = d2 > 0;
  22394. v3Out = d3 > 0;
  22395. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  22396. switch (total) {
  22397. case 0:
  22398. result.push(vertices[index]);
  22399. result.push(vertices[index + 1]);
  22400. result.push(vertices[index + 2]);
  22401. break;
  22402. case 1:
  22403. if (v1Out) {
  22404. nV1 = vertices[index + 1];
  22405. nV2 = vertices[index + 2];
  22406. nV3 = clipVertices(vertices[index], nV1);
  22407. nV4 = clipVertices(vertices[index], nV2);
  22408. }
  22409. if (v2Out) {
  22410. nV1 = vertices[index];
  22411. nV2 = vertices[index + 2];
  22412. nV3 = clipVertices(vertices[index + 1], nV1);
  22413. nV4 = clipVertices(vertices[index + 1], nV2);
  22414. result.push(nV3);
  22415. result.push(nV2.clone());
  22416. result.push(nV1.clone());
  22417. result.push(nV2.clone());
  22418. result.push(nV3.clone());
  22419. result.push(nV4);
  22420. break;
  22421. }
  22422. if (v3Out) {
  22423. nV1 = vertices[index];
  22424. nV2 = vertices[index + 1];
  22425. nV3 = clipVertices(vertices[index + 2], nV1);
  22426. nV4 = clipVertices(vertices[index + 2], nV2);
  22427. }
  22428. result.push(nV1.clone());
  22429. result.push(nV2.clone());
  22430. result.push(nV3);
  22431. result.push(nV4);
  22432. result.push(nV3.clone());
  22433. result.push(nV2.clone());
  22434. break;
  22435. case 2:
  22436. if (!v1Out) {
  22437. nV1 = vertices[index].clone();
  22438. nV2 = clipVertices(nV1, vertices[index + 1]);
  22439. nV3 = clipVertices(nV1, vertices[index + 2]);
  22440. result.push(nV1);
  22441. result.push(nV2);
  22442. result.push(nV3);
  22443. }
  22444. if (!v2Out) {
  22445. nV1 = vertices[index + 1].clone();
  22446. nV2 = clipVertices(nV1, vertices[index + 2]);
  22447. nV3 = clipVertices(nV1, vertices[index]);
  22448. result.push(nV1);
  22449. result.push(nV2);
  22450. result.push(nV3);
  22451. }
  22452. if (!v3Out) {
  22453. nV1 = vertices[index + 2].clone();
  22454. nV2 = clipVertices(nV1, vertices[index]);
  22455. nV3 = clipVertices(nV1, vertices[index + 1]);
  22456. result.push(nV1);
  22457. result.push(nV2);
  22458. result.push(nV3);
  22459. }
  22460. break;
  22461. case 3:
  22462. break;
  22463. }
  22464. }
  22465. return result;
  22466. };
  22467. for (var index = 0; index < indices.length; index += 3) {
  22468. var faceVertices = new Array();
  22469. faceVertices.push(extractDecalVector3(index));
  22470. faceVertices.push(extractDecalVector3(index + 1));
  22471. faceVertices.push(extractDecalVector3(index + 2));
  22472. // Clip
  22473. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  22474. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  22475. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  22476. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  22477. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  22478. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  22479. if (faceVertices.length === 0) {
  22480. continue;
  22481. }
  22482. // Add UVs and get back to world
  22483. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  22484. var vertex = faceVertices[vIndex];
  22485. //TODO check for Int32Array
  22486. vertexData.indices.push(currentVertexDataIndex);
  22487. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  22488. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  22489. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  22490. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  22491. currentVertexDataIndex++;
  22492. }
  22493. }
  22494. // Return mesh
  22495. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  22496. vertexData.applyToMesh(decal);
  22497. decal.position = position.clone();
  22498. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  22499. return decal;
  22500. };
  22501. // Privates
  22502. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  22503. // extrusion geometry
  22504. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  22505. var tangents = path3D.getTangents();
  22506. var normals = path3D.getNormals();
  22507. var binormals = path3D.getBinormals();
  22508. var distances = path3D.getDistances();
  22509. var angle = 0;
  22510. var returnScale = function () { return scale; };
  22511. var returnRotation = function () { return rotation; };
  22512. var rotate = custom ? rotateFunction : returnRotation;
  22513. var scl = custom ? scaleFunction : returnScale;
  22514. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22515. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22516. for (var i = 0; i < curve.length; i++) {
  22517. var shapePath = new Array();
  22518. var angleStep = rotate(i, distances[i]);
  22519. var scaleRatio = scl(i, distances[i]);
  22520. for (var p = 0; p < shape.length; p++) {
  22521. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  22522. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  22523. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  22524. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  22525. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  22526. shapePath[p] = rotated;
  22527. }
  22528. shapePaths[index] = shapePath;
  22529. angle += angleStep;
  22530. index++;
  22531. }
  22532. // cap
  22533. var capPath = function (shapePath) {
  22534. var pointCap = Array();
  22535. var barycenter = BABYLON.Vector3.Zero();
  22536. var i;
  22537. for (i = 0; i < shapePath.length; i++) {
  22538. barycenter.addInPlace(shapePath[i]);
  22539. }
  22540. barycenter.scaleInPlace(1 / shapePath.length);
  22541. for (i = 0; i < shapePath.length; i++) {
  22542. pointCap.push(barycenter);
  22543. }
  22544. return pointCap;
  22545. };
  22546. switch (cap) {
  22547. case BABYLON.Mesh.NO_CAP:
  22548. break;
  22549. case BABYLON.Mesh.CAP_START:
  22550. shapePaths[0] = capPath(shapePaths[2]);
  22551. shapePaths[1] = shapePaths[2].slice(0);
  22552. break;
  22553. case BABYLON.Mesh.CAP_END:
  22554. shapePaths[index] = shapePaths[index - 1];
  22555. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22556. break;
  22557. case BABYLON.Mesh.CAP_ALL:
  22558. shapePaths[0] = capPath(shapePaths[2]);
  22559. shapePaths[1] = shapePaths[2].slice(0);
  22560. shapePaths[index] = shapePaths[index - 1];
  22561. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22562. break;
  22563. default:
  22564. break;
  22565. }
  22566. return shapePaths;
  22567. };
  22568. var path3D;
  22569. var pathArray;
  22570. if (instance) {
  22571. path3D = (instance.path3D).update(curve);
  22572. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22573. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  22574. return instance;
  22575. }
  22576. // extruded shape creation
  22577. path3D = new BABYLON.Path3D(curve);
  22578. var newShapePaths = new Array();
  22579. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22580. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22581. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22582. extrudedGeneric.pathArray = pathArray;
  22583. extrudedGeneric.path3D = path3D;
  22584. extrudedGeneric.cap = cap;
  22585. return extrudedGeneric;
  22586. };
  22587. return MeshBuilder;
  22588. }());
  22589. BABYLON.MeshBuilder = MeshBuilder;
  22590. })(BABYLON || (BABYLON = {}));
  22591. var BABYLON;
  22592. (function (BABYLON) {
  22593. var BaseTexture = (function () {
  22594. function BaseTexture(scene) {
  22595. this.hasAlpha = false;
  22596. this.getAlphaFromRGB = false;
  22597. this.level = 1;
  22598. this.coordinatesIndex = 0;
  22599. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22600. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22601. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22602. this.anisotropicFilteringLevel = 4;
  22603. this.isCube = false;
  22604. this.isRenderTarget = false;
  22605. this.animations = new Array();
  22606. /**
  22607. * An event triggered when the texture is disposed.
  22608. * @type {BABYLON.Observable}
  22609. */
  22610. this.onDisposeObservable = new BABYLON.Observable();
  22611. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22612. this._scene = scene;
  22613. this._scene.textures.push(this);
  22614. }
  22615. BaseTexture.prototype.toString = function () {
  22616. return this.name;
  22617. };
  22618. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22619. set: function (callback) {
  22620. if (this._onDisposeObserver) {
  22621. this.onDisposeObservable.remove(this._onDisposeObserver);
  22622. }
  22623. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22624. },
  22625. enumerable: true,
  22626. configurable: true
  22627. });
  22628. BaseTexture.prototype.getScene = function () {
  22629. return this._scene;
  22630. };
  22631. BaseTexture.prototype.getTextureMatrix = function () {
  22632. return null;
  22633. };
  22634. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22635. return null;
  22636. };
  22637. BaseTexture.prototype.getInternalTexture = function () {
  22638. return this._texture;
  22639. };
  22640. BaseTexture.prototype.isReady = function () {
  22641. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22642. return true;
  22643. }
  22644. if (this._texture) {
  22645. return this._texture.isReady;
  22646. }
  22647. return false;
  22648. };
  22649. BaseTexture.prototype.getSize = function () {
  22650. if (this._texture._width) {
  22651. return new BABYLON.Size(this._texture._width, this._texture._height);
  22652. }
  22653. if (this._texture._size) {
  22654. return new BABYLON.Size(this._texture._size, this._texture._size);
  22655. }
  22656. return BABYLON.Size.Zero();
  22657. };
  22658. BaseTexture.prototype.getBaseSize = function () {
  22659. if (!this.isReady() || !this._texture)
  22660. return BABYLON.Size.Zero();
  22661. if (this._texture._size) {
  22662. return new BABYLON.Size(this._texture._size, this._texture._size);
  22663. }
  22664. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22665. };
  22666. BaseTexture.prototype.scale = function (ratio) {
  22667. };
  22668. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22669. get: function () {
  22670. return false;
  22671. },
  22672. enumerable: true,
  22673. configurable: true
  22674. });
  22675. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22676. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22677. for (var index = 0; index < texturesCache.length; index++) {
  22678. var texturesCacheEntry = texturesCache[index];
  22679. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22680. texturesCache.splice(index, 1);
  22681. return;
  22682. }
  22683. }
  22684. };
  22685. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22686. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22687. for (var index = 0; index < texturesCache.length; index++) {
  22688. var texturesCacheEntry = texturesCache[index];
  22689. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22690. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22691. texturesCacheEntry.references++;
  22692. return texturesCacheEntry;
  22693. }
  22694. }
  22695. }
  22696. return null;
  22697. };
  22698. BaseTexture.prototype.delayLoad = function () {
  22699. };
  22700. BaseTexture.prototype.clone = function () {
  22701. return null;
  22702. };
  22703. BaseTexture.prototype.releaseInternalTexture = function () {
  22704. if (this._texture) {
  22705. this._scene.getEngine().releaseInternalTexture(this._texture);
  22706. delete this._texture;
  22707. }
  22708. };
  22709. BaseTexture.prototype.dispose = function () {
  22710. // Animations
  22711. this.getScene().stopAnimation(this);
  22712. // Remove from scene
  22713. var index = this._scene.textures.indexOf(this);
  22714. if (index >= 0) {
  22715. this._scene.textures.splice(index, 1);
  22716. }
  22717. if (this._texture === undefined) {
  22718. return;
  22719. }
  22720. // Release
  22721. this.releaseInternalTexture();
  22722. // Callback
  22723. this.onDisposeObservable.notifyObservers(this);
  22724. this.onDisposeObservable.clear();
  22725. };
  22726. BaseTexture.prototype.serialize = function () {
  22727. if (!this.name) {
  22728. return null;
  22729. }
  22730. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22731. // Animations
  22732. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22733. return serializationObject;
  22734. };
  22735. __decorate([
  22736. BABYLON.serialize()
  22737. ], BaseTexture.prototype, "name", void 0);
  22738. __decorate([
  22739. BABYLON.serialize()
  22740. ], BaseTexture.prototype, "hasAlpha", void 0);
  22741. __decorate([
  22742. BABYLON.serialize()
  22743. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22744. __decorate([
  22745. BABYLON.serialize()
  22746. ], BaseTexture.prototype, "level", void 0);
  22747. __decorate([
  22748. BABYLON.serialize()
  22749. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22750. __decorate([
  22751. BABYLON.serialize()
  22752. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22753. __decorate([
  22754. BABYLON.serialize()
  22755. ], BaseTexture.prototype, "wrapU", void 0);
  22756. __decorate([
  22757. BABYLON.serialize()
  22758. ], BaseTexture.prototype, "wrapV", void 0);
  22759. __decorate([
  22760. BABYLON.serialize()
  22761. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22762. __decorate([
  22763. BABYLON.serialize()
  22764. ], BaseTexture.prototype, "isCube", void 0);
  22765. __decorate([
  22766. BABYLON.serialize()
  22767. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22768. return BaseTexture;
  22769. }());
  22770. BABYLON.BaseTexture = BaseTexture;
  22771. })(BABYLON || (BABYLON = {}));
  22772. var BABYLON;
  22773. (function (BABYLON) {
  22774. var Texture = (function (_super) {
  22775. __extends(Texture, _super);
  22776. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22777. var _this = this;
  22778. if (noMipmap === void 0) { noMipmap = false; }
  22779. if (invertY === void 0) { invertY = true; }
  22780. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22781. if (onLoad === void 0) { onLoad = null; }
  22782. if (onError === void 0) { onError = null; }
  22783. if (buffer === void 0) { buffer = null; }
  22784. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22785. _super.call(this, scene);
  22786. this.uOffset = 0;
  22787. this.vOffset = 0;
  22788. this.uScale = 1.0;
  22789. this.vScale = 1.0;
  22790. this.uAng = 0;
  22791. this.vAng = 0;
  22792. this.wAng = 0;
  22793. this.name = url;
  22794. this.url = url;
  22795. this._noMipmap = noMipmap;
  22796. this._invertY = invertY;
  22797. this._samplingMode = samplingMode;
  22798. this._buffer = buffer;
  22799. this._deleteBuffer = deleteBuffer;
  22800. if (!url) {
  22801. return;
  22802. }
  22803. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  22804. var load = function () {
  22805. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  22806. _this.onLoadObservable.notifyObservers(true);
  22807. }
  22808. if (onLoad) {
  22809. onLoad();
  22810. }
  22811. };
  22812. if (!this._texture) {
  22813. if (!scene.useDelayedTextureLoading) {
  22814. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  22815. if (deleteBuffer) {
  22816. delete this._buffer;
  22817. }
  22818. }
  22819. else {
  22820. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22821. this._delayedOnLoad = load;
  22822. this._delayedOnError = onError;
  22823. }
  22824. }
  22825. else {
  22826. if (this._texture.isReady) {
  22827. BABYLON.Tools.SetImmediate(function () { return load(); });
  22828. }
  22829. else {
  22830. this._texture.onLoadedCallbacks.push(load);
  22831. }
  22832. }
  22833. }
  22834. Object.defineProperty(Texture.prototype, "noMipmap", {
  22835. get: function () {
  22836. return this._noMipmap;
  22837. },
  22838. enumerable: true,
  22839. configurable: true
  22840. });
  22841. Texture.prototype.delayLoad = function () {
  22842. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22843. return;
  22844. }
  22845. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22846. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22847. if (!this._texture) {
  22848. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  22849. if (this._deleteBuffer) {
  22850. delete this._buffer;
  22851. }
  22852. }
  22853. };
  22854. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22855. if (!this._texture) {
  22856. return;
  22857. }
  22858. this._samplingMode = samplingMode;
  22859. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22860. };
  22861. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22862. x *= this.uScale;
  22863. y *= this.vScale;
  22864. x -= 0.5 * this.uScale;
  22865. y -= 0.5 * this.vScale;
  22866. z -= 0.5;
  22867. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22868. t.x += 0.5 * this.uScale + this.uOffset;
  22869. t.y += 0.5 * this.vScale + this.vOffset;
  22870. t.z += 0.5;
  22871. };
  22872. Texture.prototype.getTextureMatrix = function () {
  22873. if (this.uOffset === this._cachedUOffset &&
  22874. this.vOffset === this._cachedVOffset &&
  22875. this.uScale === this._cachedUScale &&
  22876. this.vScale === this._cachedVScale &&
  22877. this.uAng === this._cachedUAng &&
  22878. this.vAng === this._cachedVAng &&
  22879. this.wAng === this._cachedWAng) {
  22880. return this._cachedTextureMatrix;
  22881. }
  22882. this._cachedUOffset = this.uOffset;
  22883. this._cachedVOffset = this.vOffset;
  22884. this._cachedUScale = this.uScale;
  22885. this._cachedVScale = this.vScale;
  22886. this._cachedUAng = this.uAng;
  22887. this._cachedVAng = this.vAng;
  22888. this._cachedWAng = this.wAng;
  22889. if (!this._cachedTextureMatrix) {
  22890. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22891. this._rowGenerationMatrix = new BABYLON.Matrix();
  22892. this._t0 = BABYLON.Vector3.Zero();
  22893. this._t1 = BABYLON.Vector3.Zero();
  22894. this._t2 = BABYLON.Vector3.Zero();
  22895. }
  22896. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22897. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22898. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22899. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22900. this._t1.subtractInPlace(this._t0);
  22901. this._t2.subtractInPlace(this._t0);
  22902. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22903. this._cachedTextureMatrix.m[0] = this._t1.x;
  22904. this._cachedTextureMatrix.m[1] = this._t1.y;
  22905. this._cachedTextureMatrix.m[2] = this._t1.z;
  22906. this._cachedTextureMatrix.m[4] = this._t2.x;
  22907. this._cachedTextureMatrix.m[5] = this._t2.y;
  22908. this._cachedTextureMatrix.m[6] = this._t2.z;
  22909. this._cachedTextureMatrix.m[8] = this._t0.x;
  22910. this._cachedTextureMatrix.m[9] = this._t0.y;
  22911. this._cachedTextureMatrix.m[10] = this._t0.z;
  22912. return this._cachedTextureMatrix;
  22913. };
  22914. Texture.prototype.getReflectionTextureMatrix = function () {
  22915. if (this.uOffset === this._cachedUOffset &&
  22916. this.vOffset === this._cachedVOffset &&
  22917. this.uScale === this._cachedUScale &&
  22918. this.vScale === this._cachedVScale &&
  22919. this.coordinatesMode === this._cachedCoordinatesMode) {
  22920. return this._cachedTextureMatrix;
  22921. }
  22922. if (!this._cachedTextureMatrix) {
  22923. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22924. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22925. }
  22926. this._cachedCoordinatesMode = this.coordinatesMode;
  22927. switch (this.coordinatesMode) {
  22928. case Texture.PLANAR_MODE:
  22929. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22930. this._cachedTextureMatrix[0] = this.uScale;
  22931. this._cachedTextureMatrix[5] = this.vScale;
  22932. this._cachedTextureMatrix[12] = this.uOffset;
  22933. this._cachedTextureMatrix[13] = this.vOffset;
  22934. break;
  22935. case Texture.PROJECTION_MODE:
  22936. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22937. this._projectionModeMatrix.m[0] = 0.5;
  22938. this._projectionModeMatrix.m[5] = -0.5;
  22939. this._projectionModeMatrix.m[10] = 0.0;
  22940. this._projectionModeMatrix.m[12] = 0.5;
  22941. this._projectionModeMatrix.m[13] = 0.5;
  22942. this._projectionModeMatrix.m[14] = 1.0;
  22943. this._projectionModeMatrix.m[15] = 1.0;
  22944. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22945. break;
  22946. default:
  22947. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22948. break;
  22949. }
  22950. return this._cachedTextureMatrix;
  22951. };
  22952. Texture.prototype.clone = function () {
  22953. var _this = this;
  22954. return BABYLON.SerializationHelper.Clone(function () {
  22955. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22956. }, this);
  22957. };
  22958. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22959. get: function () {
  22960. if (!this._onLoadObservarble) {
  22961. this._onLoadObservarble = new BABYLON.Observable();
  22962. }
  22963. return this._onLoadObservarble;
  22964. },
  22965. enumerable: true,
  22966. configurable: true
  22967. });
  22968. // Statics
  22969. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  22970. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22971. if (onLoad === void 0) { onLoad = null; }
  22972. if (onError === void 0) { onError = null; }
  22973. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  22974. };
  22975. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22976. if (parsedTexture.isCube) {
  22977. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22978. }
  22979. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22980. return null;
  22981. }
  22982. var texture = BABYLON.SerializationHelper.Parse(function () {
  22983. if (parsedTexture.customType) {
  22984. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22985. return customTexture.Parse(parsedTexture, scene, rootUrl);
  22986. }
  22987. else if (parsedTexture.mirrorPlane) {
  22988. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22989. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22990. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22991. return mirrorTexture;
  22992. }
  22993. else if (parsedTexture.isRenderTarget) {
  22994. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22995. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22996. return renderTargetTexture;
  22997. }
  22998. else {
  22999. var texture;
  23000. if (parsedTexture.base64String) {
  23001. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23002. }
  23003. else {
  23004. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23005. }
  23006. return texture;
  23007. }
  23008. }, parsedTexture, scene);
  23009. // Animations
  23010. if (parsedTexture.animations) {
  23011. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23012. var parsedAnimation = parsedTexture.animations[animationIndex];
  23013. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23014. }
  23015. }
  23016. return texture;
  23017. };
  23018. // Constants
  23019. Texture.NEAREST_SAMPLINGMODE = 1;
  23020. Texture.BILINEAR_SAMPLINGMODE = 2;
  23021. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23022. Texture.EXPLICIT_MODE = 0;
  23023. Texture.SPHERICAL_MODE = 1;
  23024. Texture.PLANAR_MODE = 2;
  23025. Texture.CUBIC_MODE = 3;
  23026. Texture.PROJECTION_MODE = 4;
  23027. Texture.SKYBOX_MODE = 5;
  23028. Texture.INVCUBIC_MODE = 6;
  23029. Texture.EQUIRECTANGULAR_MODE = 7;
  23030. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23031. Texture.CLAMP_ADDRESSMODE = 0;
  23032. Texture.WRAP_ADDRESSMODE = 1;
  23033. Texture.MIRROR_ADDRESSMODE = 2;
  23034. __decorate([
  23035. BABYLON.serialize()
  23036. ], Texture.prototype, "url", void 0);
  23037. __decorate([
  23038. BABYLON.serialize()
  23039. ], Texture.prototype, "uOffset", void 0);
  23040. __decorate([
  23041. BABYLON.serialize()
  23042. ], Texture.prototype, "vOffset", void 0);
  23043. __decorate([
  23044. BABYLON.serialize()
  23045. ], Texture.prototype, "uScale", void 0);
  23046. __decorate([
  23047. BABYLON.serialize()
  23048. ], Texture.prototype, "vScale", void 0);
  23049. __decorate([
  23050. BABYLON.serialize()
  23051. ], Texture.prototype, "uAng", void 0);
  23052. __decorate([
  23053. BABYLON.serialize()
  23054. ], Texture.prototype, "vAng", void 0);
  23055. __decorate([
  23056. BABYLON.serialize()
  23057. ], Texture.prototype, "wAng", void 0);
  23058. return Texture;
  23059. }(BABYLON.BaseTexture));
  23060. BABYLON.Texture = Texture;
  23061. })(BABYLON || (BABYLON = {}));
  23062. var BABYLON;
  23063. (function (BABYLON) {
  23064. var CubeTexture = (function (_super) {
  23065. __extends(CubeTexture, _super);
  23066. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23067. if (onLoad === void 0) { onLoad = null; }
  23068. if (onError === void 0) { onError = null; }
  23069. _super.call(this, scene);
  23070. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23071. this.name = rootUrl;
  23072. this.url = rootUrl;
  23073. this._noMipmap = noMipmap;
  23074. this.hasAlpha = false;
  23075. if (!rootUrl && !files) {
  23076. return;
  23077. }
  23078. this._texture = this._getFromCache(rootUrl, noMipmap);
  23079. if (!files) {
  23080. if (!extensions) {
  23081. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23082. }
  23083. files = [];
  23084. for (var index = 0; index < extensions.length; index++) {
  23085. files.push(rootUrl + extensions[index]);
  23086. }
  23087. this._extensions = extensions;
  23088. }
  23089. this._files = files;
  23090. if (!this._texture) {
  23091. if (!scene.useDelayedTextureLoading) {
  23092. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23093. }
  23094. else {
  23095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23096. }
  23097. }
  23098. else {
  23099. if (this._texture.isReady) {
  23100. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23101. }
  23102. else {
  23103. this._texture.onLoadedCallbacks.push(onLoad);
  23104. }
  23105. }
  23106. this.isCube = true;
  23107. this._textureMatrix = BABYLON.Matrix.Identity();
  23108. }
  23109. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23110. return new CubeTexture("", scene, null, noMipmap, files);
  23111. };
  23112. // Methods
  23113. CubeTexture.prototype.delayLoad = function () {
  23114. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23115. return;
  23116. }
  23117. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23118. this._texture = this._getFromCache(this.url, this._noMipmap);
  23119. if (!this._texture) {
  23120. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23121. }
  23122. };
  23123. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23124. return this._textureMatrix;
  23125. };
  23126. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23127. var texture = BABYLON.SerializationHelper.Parse(function () {
  23128. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23129. }, parsedTexture, scene);
  23130. // Animations
  23131. if (parsedTexture.animations) {
  23132. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23133. var parsedAnimation = parsedTexture.animations[animationIndex];
  23134. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23135. }
  23136. }
  23137. return texture;
  23138. };
  23139. CubeTexture.prototype.clone = function () {
  23140. var _this = this;
  23141. return BABYLON.SerializationHelper.Clone(function () {
  23142. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23143. }, this);
  23144. };
  23145. return CubeTexture;
  23146. }(BABYLON.BaseTexture));
  23147. BABYLON.CubeTexture = CubeTexture;
  23148. })(BABYLON || (BABYLON = {}));
  23149. var BABYLON;
  23150. (function (BABYLON) {
  23151. var RenderTargetTexture = (function (_super) {
  23152. __extends(RenderTargetTexture, _super);
  23153. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23154. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23155. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23156. if (isCube === void 0) { isCube = false; }
  23157. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23158. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23159. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23160. _super.call(this, null, scene, !generateMipMaps);
  23161. this.isCube = isCube;
  23162. /**
  23163. * Use this list to define the list of mesh you want to render.
  23164. */
  23165. this.renderList = new Array();
  23166. this.renderParticles = true;
  23167. this.renderSprites = false;
  23168. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23169. // Events
  23170. /**
  23171. * An event triggered when the texture is unbind.
  23172. * @type {BABYLON.Observable}
  23173. */
  23174. this.onAfterUnbindObservable = new BABYLON.Observable();
  23175. /**
  23176. * An event triggered before rendering the texture
  23177. * @type {BABYLON.Observable}
  23178. */
  23179. this.onBeforeRenderObservable = new BABYLON.Observable();
  23180. /**
  23181. * An event triggered after rendering the texture
  23182. * @type {BABYLON.Observable}
  23183. */
  23184. this.onAfterRenderObservable = new BABYLON.Observable();
  23185. /**
  23186. * An event triggered after the texture clear
  23187. * @type {BABYLON.Observable}
  23188. */
  23189. this.onClearObservable = new BABYLON.Observable();
  23190. this._currentRefreshId = -1;
  23191. this._refreshRate = 1;
  23192. this.name = name;
  23193. this.isRenderTarget = true;
  23194. this._size = size;
  23195. this._generateMipMaps = generateMipMaps;
  23196. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23197. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23198. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23199. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23200. }
  23201. if (isCube) {
  23202. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23203. generateMipMaps: generateMipMaps,
  23204. samplingMode: samplingMode,
  23205. generateDepthBuffer: generateDepthBuffer,
  23206. generateStencilBuffer: generateStencilBuffer
  23207. });
  23208. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23209. this._textureMatrix = BABYLON.Matrix.Identity();
  23210. }
  23211. else {
  23212. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23213. generateMipMaps: generateMipMaps,
  23214. type: type,
  23215. samplingMode: samplingMode,
  23216. generateDepthBuffer: generateDepthBuffer,
  23217. generateStencilBuffer: generateStencilBuffer
  23218. });
  23219. }
  23220. // Rendering groups
  23221. this._renderingManager = new BABYLON.RenderingManager(scene);
  23222. }
  23223. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23224. get: function () {
  23225. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23226. },
  23227. enumerable: true,
  23228. configurable: true
  23229. });
  23230. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23231. get: function () {
  23232. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23233. },
  23234. enumerable: true,
  23235. configurable: true
  23236. });
  23237. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23238. get: function () {
  23239. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23240. },
  23241. enumerable: true,
  23242. configurable: true
  23243. });
  23244. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23245. set: function (callback) {
  23246. if (this._onAfterUnbindObserver) {
  23247. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23248. }
  23249. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23250. },
  23251. enumerable: true,
  23252. configurable: true
  23253. });
  23254. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23255. set: function (callback) {
  23256. if (this._onBeforeRenderObserver) {
  23257. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23258. }
  23259. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23260. },
  23261. enumerable: true,
  23262. configurable: true
  23263. });
  23264. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23265. set: function (callback) {
  23266. if (this._onAfterRenderObserver) {
  23267. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23268. }
  23269. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23270. },
  23271. enumerable: true,
  23272. configurable: true
  23273. });
  23274. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23275. set: function (callback) {
  23276. if (this._onClearObserver) {
  23277. this.onClearObservable.remove(this._onClearObserver);
  23278. }
  23279. this._onClearObserver = this.onClearObservable.add(callback);
  23280. },
  23281. enumerable: true,
  23282. configurable: true
  23283. });
  23284. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23285. this._currentRefreshId = -1;
  23286. };
  23287. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23288. get: function () {
  23289. return this._refreshRate;
  23290. },
  23291. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23292. set: function (value) {
  23293. this._refreshRate = value;
  23294. this.resetRefreshCounter();
  23295. },
  23296. enumerable: true,
  23297. configurable: true
  23298. });
  23299. RenderTargetTexture.prototype._shouldRender = function () {
  23300. if (this._currentRefreshId === -1) {
  23301. this._currentRefreshId = 1;
  23302. return true;
  23303. }
  23304. if (this.refreshRate === this._currentRefreshId) {
  23305. this._currentRefreshId = 1;
  23306. return true;
  23307. }
  23308. this._currentRefreshId++;
  23309. return false;
  23310. };
  23311. RenderTargetTexture.prototype.isReady = function () {
  23312. if (!this.getScene().renderTargetsEnabled) {
  23313. return false;
  23314. }
  23315. return _super.prototype.isReady.call(this);
  23316. };
  23317. RenderTargetTexture.prototype.getRenderSize = function () {
  23318. return this._size;
  23319. };
  23320. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23321. get: function () {
  23322. return true;
  23323. },
  23324. enumerable: true,
  23325. configurable: true
  23326. });
  23327. RenderTargetTexture.prototype.scale = function (ratio) {
  23328. var newSize = this._size * ratio;
  23329. this.resize(newSize, this._generateMipMaps);
  23330. };
  23331. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23332. if (this.isCube) {
  23333. return this._textureMatrix;
  23334. }
  23335. return _super.prototype.getReflectionTextureMatrix.call(this);
  23336. };
  23337. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  23338. this.releaseInternalTexture();
  23339. if (this.isCube) {
  23340. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  23341. }
  23342. else {
  23343. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23344. }
  23345. };
  23346. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  23347. var scene = this.getScene();
  23348. if (this.useCameraPostProcesses !== undefined) {
  23349. useCameraPostProcess = this.useCameraPostProcesses;
  23350. }
  23351. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23352. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  23353. }
  23354. if (this._waitingRenderList) {
  23355. this.renderList = [];
  23356. for (var index = 0; index < this._waitingRenderList.length; index++) {
  23357. var id = this._waitingRenderList[index];
  23358. this.renderList.push(scene.getMeshByID(id));
  23359. }
  23360. delete this._waitingRenderList;
  23361. }
  23362. // Is predicate defined?
  23363. if (this.renderListPredicate) {
  23364. this.renderList.splice(0); // Clear previous renderList
  23365. var sceneMeshes = this.getScene().meshes;
  23366. for (var index = 0; index < sceneMeshes.length; index++) {
  23367. var mesh = sceneMeshes[index];
  23368. if (this.renderListPredicate(mesh)) {
  23369. this.renderList.push(mesh);
  23370. }
  23371. }
  23372. }
  23373. if (this.renderList && this.renderList.length === 0) {
  23374. return;
  23375. }
  23376. // Prepare renderingManager
  23377. this._renderingManager.reset();
  23378. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  23379. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  23380. var sceneRenderId = scene.getRenderId();
  23381. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  23382. var mesh = currentRenderList[meshIndex];
  23383. if (mesh) {
  23384. if (!mesh.isReady()) {
  23385. // Reset _currentRefreshId
  23386. this.resetRefreshCounter();
  23387. continue;
  23388. }
  23389. mesh._preActivateForIntermediateRendering(sceneRenderId);
  23390. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  23391. mesh._activate(sceneRenderId);
  23392. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23393. var subMesh = mesh.subMeshes[subIndex];
  23394. scene._activeIndices.addCount(subMesh.indexCount, false);
  23395. this._renderingManager.dispatch(subMesh);
  23396. }
  23397. }
  23398. }
  23399. }
  23400. if (this.isCube) {
  23401. for (var face = 0; face < 6; face++) {
  23402. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23403. scene.incrementRenderId();
  23404. scene.resetCachedMaterial();
  23405. }
  23406. }
  23407. else {
  23408. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23409. }
  23410. this.onAfterUnbindObservable.notifyObservers(this);
  23411. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23412. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  23413. }
  23414. scene.resetCachedMaterial();
  23415. };
  23416. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  23417. var scene = this.getScene();
  23418. var engine = scene.getEngine();
  23419. // Bind
  23420. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  23421. if (this.isCube) {
  23422. engine.bindFramebuffer(this._texture, faceIndex);
  23423. }
  23424. else {
  23425. engine.bindFramebuffer(this._texture);
  23426. }
  23427. }
  23428. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  23429. // Clear
  23430. if (this.onClearObservable.hasObservers()) {
  23431. this.onClearObservable.notifyObservers(engine);
  23432. }
  23433. else {
  23434. engine.clear(scene.clearColor, true, true, true);
  23435. }
  23436. if (!this._doNotChangeAspectRatio) {
  23437. scene.updateTransformMatrix(true);
  23438. }
  23439. // Render
  23440. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  23441. if (useCameraPostProcess) {
  23442. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  23443. }
  23444. if (!this._doNotChangeAspectRatio) {
  23445. scene.updateTransformMatrix(true);
  23446. }
  23447. this.onAfterRenderObservable.notifyObservers(faceIndex);
  23448. // Dump ?
  23449. if (dumpForDebug) {
  23450. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  23451. }
  23452. // Unbind
  23453. if (!this.isCube || faceIndex === 5) {
  23454. if (this.isCube) {
  23455. if (faceIndex === 5) {
  23456. engine.generateMipMapsForCubemap(this._texture);
  23457. }
  23458. }
  23459. engine.unBindFramebuffer(this._texture, this.isCube);
  23460. }
  23461. };
  23462. /**
  23463. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23464. * This allowed control for front to back rendering or reversly depending of the special needs.
  23465. *
  23466. * @param renderingGroupId The rendering group id corresponding to its index
  23467. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23468. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23469. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23470. */
  23471. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23472. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23473. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23474. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23475. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23476. };
  23477. /**
  23478. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23479. *
  23480. * @param renderingGroupId The rendering group id corresponding to its index
  23481. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23482. */
  23483. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  23484. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  23485. };
  23486. RenderTargetTexture.prototype.clone = function () {
  23487. var textureSize = this.getSize();
  23488. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23489. // Base texture
  23490. newTexture.hasAlpha = this.hasAlpha;
  23491. newTexture.level = this.level;
  23492. // RenderTarget Texture
  23493. newTexture.coordinatesMode = this.coordinatesMode;
  23494. newTexture.renderList = this.renderList.slice(0);
  23495. return newTexture;
  23496. };
  23497. RenderTargetTexture.prototype.serialize = function () {
  23498. if (!this.name) {
  23499. return null;
  23500. }
  23501. var serializationObject = _super.prototype.serialize.call(this);
  23502. serializationObject.renderTargetSize = this.getRenderSize();
  23503. serializationObject.renderList = [];
  23504. for (var index = 0; index < this.renderList.length; index++) {
  23505. serializationObject.renderList.push(this.renderList[index].id);
  23506. }
  23507. return serializationObject;
  23508. };
  23509. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  23510. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  23511. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  23512. return RenderTargetTexture;
  23513. }(BABYLON.Texture));
  23514. BABYLON.RenderTargetTexture = RenderTargetTexture;
  23515. })(BABYLON || (BABYLON = {}));
  23516. var BABYLON;
  23517. (function (BABYLON) {
  23518. var ProceduralTexture = (function (_super) {
  23519. __extends(ProceduralTexture, _super);
  23520. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  23521. if (generateMipMaps === void 0) { generateMipMaps = true; }
  23522. if (isCube === void 0) { isCube = false; }
  23523. _super.call(this, null, scene, !generateMipMaps);
  23524. this.isCube = isCube;
  23525. this.isEnabled = true;
  23526. this._currentRefreshId = -1;
  23527. this._refreshRate = 1;
  23528. this._vertexBuffers = {};
  23529. this._uniforms = new Array();
  23530. this._samplers = new Array();
  23531. this._textures = new Array();
  23532. this._floats = new Array();
  23533. this._floatsArrays = {};
  23534. this._colors3 = new Array();
  23535. this._colors4 = new Array();
  23536. this._vectors2 = new Array();
  23537. this._vectors3 = new Array();
  23538. this._matrices = new Array();
  23539. this._fallbackTextureUsed = false;
  23540. scene._proceduralTextures.push(this);
  23541. this.name = name;
  23542. this.isRenderTarget = true;
  23543. this._size = size;
  23544. this._generateMipMaps = generateMipMaps;
  23545. this.setFragment(fragment);
  23546. this._fallbackTexture = fallbackTexture;
  23547. var engine = scene.getEngine();
  23548. if (isCube) {
  23549. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23550. this.setFloat("face", 0);
  23551. }
  23552. else {
  23553. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23554. }
  23555. // VBO
  23556. var vertices = [];
  23557. vertices.push(1, 1);
  23558. vertices.push(-1, 1);
  23559. vertices.push(-1, -1);
  23560. vertices.push(1, -1);
  23561. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23562. // Indices
  23563. var indices = [];
  23564. indices.push(0);
  23565. indices.push(1);
  23566. indices.push(2);
  23567. indices.push(0);
  23568. indices.push(2);
  23569. indices.push(3);
  23570. this._indexBuffer = engine.createIndexBuffer(indices);
  23571. }
  23572. ProceduralTexture.prototype.reset = function () {
  23573. if (this._effect === undefined) {
  23574. return;
  23575. }
  23576. var engine = this.getScene().getEngine();
  23577. engine._releaseEffect(this._effect);
  23578. };
  23579. ProceduralTexture.prototype.isReady = function () {
  23580. var _this = this;
  23581. var engine = this.getScene().getEngine();
  23582. var shaders;
  23583. if (!this._fragment) {
  23584. return false;
  23585. }
  23586. if (this._fallbackTextureUsed) {
  23587. return true;
  23588. }
  23589. if (this._fragment.fragmentElement !== undefined) {
  23590. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23591. }
  23592. else {
  23593. shaders = { vertex: "procedural", fragment: this._fragment };
  23594. }
  23595. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23596. _this.releaseInternalTexture();
  23597. if (_this._fallbackTexture) {
  23598. _this._texture = _this._fallbackTexture._texture;
  23599. _this._texture.references++;
  23600. }
  23601. _this._fallbackTextureUsed = true;
  23602. });
  23603. return this._effect.isReady();
  23604. };
  23605. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23606. this._currentRefreshId = -1;
  23607. };
  23608. ProceduralTexture.prototype.setFragment = function (fragment) {
  23609. this._fragment = fragment;
  23610. };
  23611. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23612. get: function () {
  23613. return this._refreshRate;
  23614. },
  23615. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23616. set: function (value) {
  23617. this._refreshRate = value;
  23618. this.resetRefreshCounter();
  23619. },
  23620. enumerable: true,
  23621. configurable: true
  23622. });
  23623. ProceduralTexture.prototype._shouldRender = function () {
  23624. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23625. return false;
  23626. }
  23627. if (this._fallbackTextureUsed) {
  23628. return false;
  23629. }
  23630. if (this._currentRefreshId === -1) {
  23631. this._currentRefreshId = 1;
  23632. return true;
  23633. }
  23634. if (this.refreshRate === this._currentRefreshId) {
  23635. this._currentRefreshId = 1;
  23636. return true;
  23637. }
  23638. this._currentRefreshId++;
  23639. return false;
  23640. };
  23641. ProceduralTexture.prototype.getRenderSize = function () {
  23642. return this._size;
  23643. };
  23644. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23645. if (this._fallbackTextureUsed) {
  23646. return;
  23647. }
  23648. this.releaseInternalTexture();
  23649. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23650. };
  23651. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23652. if (this._uniforms.indexOf(uniformName) === -1) {
  23653. this._uniforms.push(uniformName);
  23654. }
  23655. };
  23656. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23657. if (this._samplers.indexOf(name) === -1) {
  23658. this._samplers.push(name);
  23659. }
  23660. this._textures[name] = texture;
  23661. return this;
  23662. };
  23663. ProceduralTexture.prototype.setFloat = function (name, value) {
  23664. this._checkUniform(name);
  23665. this._floats[name] = value;
  23666. return this;
  23667. };
  23668. ProceduralTexture.prototype.setFloats = function (name, value) {
  23669. this._checkUniform(name);
  23670. this._floatsArrays[name] = value;
  23671. return this;
  23672. };
  23673. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23674. this._checkUniform(name);
  23675. this._colors3[name] = value;
  23676. return this;
  23677. };
  23678. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23679. this._checkUniform(name);
  23680. this._colors4[name] = value;
  23681. return this;
  23682. };
  23683. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23684. this._checkUniform(name);
  23685. this._vectors2[name] = value;
  23686. return this;
  23687. };
  23688. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23689. this._checkUniform(name);
  23690. this._vectors3[name] = value;
  23691. return this;
  23692. };
  23693. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23694. this._checkUniform(name);
  23695. this._matrices[name] = value;
  23696. return this;
  23697. };
  23698. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23699. var scene = this.getScene();
  23700. var engine = scene.getEngine();
  23701. // Render
  23702. engine.enableEffect(this._effect);
  23703. engine.setState(false);
  23704. // Texture
  23705. for (var name in this._textures) {
  23706. this._effect.setTexture(name, this._textures[name]);
  23707. }
  23708. // Float
  23709. for (name in this._floats) {
  23710. this._effect.setFloat(name, this._floats[name]);
  23711. }
  23712. // Floats
  23713. for (name in this._floatsArrays) {
  23714. this._effect.setArray(name, this._floatsArrays[name]);
  23715. }
  23716. // Color3
  23717. for (name in this._colors3) {
  23718. this._effect.setColor3(name, this._colors3[name]);
  23719. }
  23720. // Color4
  23721. for (name in this._colors4) {
  23722. var color = this._colors4[name];
  23723. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23724. }
  23725. // Vector2
  23726. for (name in this._vectors2) {
  23727. this._effect.setVector2(name, this._vectors2[name]);
  23728. }
  23729. // Vector3
  23730. for (name in this._vectors3) {
  23731. this._effect.setVector3(name, this._vectors3[name]);
  23732. }
  23733. // Matrix
  23734. for (name in this._matrices) {
  23735. this._effect.setMatrix(name, this._matrices[name]);
  23736. }
  23737. // VBOs
  23738. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23739. if (this.isCube) {
  23740. for (var face = 0; face < 6; face++) {
  23741. engine.bindFramebuffer(this._texture, face);
  23742. this._effect.setFloat("face", face);
  23743. // Clear
  23744. engine.clear(scene.clearColor, true, true, true);
  23745. // Draw order
  23746. engine.draw(true, 0, 6);
  23747. // Mipmaps
  23748. if (face === 5) {
  23749. engine.generateMipMapsForCubemap(this._texture);
  23750. }
  23751. }
  23752. }
  23753. else {
  23754. engine.bindFramebuffer(this._texture);
  23755. // Clear
  23756. engine.clear(scene.clearColor, true, true, true);
  23757. // Draw order
  23758. engine.draw(true, 0, 6);
  23759. }
  23760. // Unbind
  23761. engine.unBindFramebuffer(this._texture, this.isCube);
  23762. if (this.onGenerated) {
  23763. this.onGenerated();
  23764. }
  23765. };
  23766. ProceduralTexture.prototype.clone = function () {
  23767. var textureSize = this.getSize();
  23768. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23769. // Base texture
  23770. newTexture.hasAlpha = this.hasAlpha;
  23771. newTexture.level = this.level;
  23772. // RenderTarget Texture
  23773. newTexture.coordinatesMode = this.coordinatesMode;
  23774. return newTexture;
  23775. };
  23776. ProceduralTexture.prototype.dispose = function () {
  23777. var index = this.getScene()._proceduralTextures.indexOf(this);
  23778. if (index >= 0) {
  23779. this.getScene()._proceduralTextures.splice(index, 1);
  23780. }
  23781. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23782. if (vertexBuffer) {
  23783. vertexBuffer.dispose();
  23784. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23785. }
  23786. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23787. this._indexBuffer = null;
  23788. }
  23789. _super.prototype.dispose.call(this);
  23790. };
  23791. return ProceduralTexture;
  23792. }(BABYLON.Texture));
  23793. BABYLON.ProceduralTexture = ProceduralTexture;
  23794. })(BABYLON || (BABYLON = {}));
  23795. var BABYLON;
  23796. (function (BABYLON) {
  23797. var MirrorTexture = (function (_super) {
  23798. __extends(MirrorTexture, _super);
  23799. function MirrorTexture(name, size, scene, generateMipMaps) {
  23800. var _this = this;
  23801. _super.call(this, name, size, scene, generateMipMaps, true);
  23802. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  23803. this._transformMatrix = BABYLON.Matrix.Zero();
  23804. this._mirrorMatrix = BABYLON.Matrix.Zero();
  23805. this.onBeforeRenderObservable.add(function () {
  23806. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  23807. _this._savedViewMatrix = scene.getViewMatrix();
  23808. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  23809. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  23810. scene.clipPlane = _this.mirrorPlane;
  23811. scene.getEngine().cullBackFaces = false;
  23812. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  23813. });
  23814. this.onAfterRenderObservable.add(function () {
  23815. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  23816. scene.getEngine().cullBackFaces = true;
  23817. scene._mirroredCameraPosition = null;
  23818. delete scene.clipPlane;
  23819. });
  23820. }
  23821. MirrorTexture.prototype.clone = function () {
  23822. var textureSize = this.getSize();
  23823. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23824. // Base texture
  23825. newTexture.hasAlpha = this.hasAlpha;
  23826. newTexture.level = this.level;
  23827. // Mirror Texture
  23828. newTexture.mirrorPlane = this.mirrorPlane.clone();
  23829. newTexture.renderList = this.renderList.slice(0);
  23830. return newTexture;
  23831. };
  23832. MirrorTexture.prototype.serialize = function () {
  23833. if (!this.name) {
  23834. return null;
  23835. }
  23836. var serializationObject = _super.prototype.serialize.call(this);
  23837. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  23838. return serializationObject;
  23839. };
  23840. return MirrorTexture;
  23841. }(BABYLON.RenderTargetTexture));
  23842. BABYLON.MirrorTexture = MirrorTexture;
  23843. })(BABYLON || (BABYLON = {}));
  23844. var BABYLON;
  23845. (function (BABYLON) {
  23846. /**
  23847. * Creates a refraction texture used by refraction channel of the standard material.
  23848. * @param name the texture name
  23849. * @param size size of the underlying texture
  23850. * @param scene root scene
  23851. */
  23852. var RefractionTexture = (function (_super) {
  23853. __extends(RefractionTexture, _super);
  23854. function RefractionTexture(name, size, scene, generateMipMaps) {
  23855. var _this = this;
  23856. _super.call(this, name, size, scene, generateMipMaps, true);
  23857. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  23858. this.depth = 2.0;
  23859. this.onBeforeRenderObservable.add(function () {
  23860. scene.clipPlane = _this.refractionPlane;
  23861. });
  23862. this.onAfterRenderObservable.add(function () {
  23863. delete scene.clipPlane;
  23864. });
  23865. }
  23866. RefractionTexture.prototype.clone = function () {
  23867. var textureSize = this.getSize();
  23868. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23869. // Base texture
  23870. newTexture.hasAlpha = this.hasAlpha;
  23871. newTexture.level = this.level;
  23872. // Refraction Texture
  23873. newTexture.refractionPlane = this.refractionPlane.clone();
  23874. newTexture.renderList = this.renderList.slice(0);
  23875. newTexture.depth = this.depth;
  23876. return newTexture;
  23877. };
  23878. RefractionTexture.prototype.serialize = function () {
  23879. if (!this.name) {
  23880. return null;
  23881. }
  23882. var serializationObject = _super.prototype.serialize.call(this);
  23883. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  23884. serializationObject.depth = this.depth;
  23885. return serializationObject;
  23886. };
  23887. return RefractionTexture;
  23888. }(BABYLON.RenderTargetTexture));
  23889. BABYLON.RefractionTexture = RefractionTexture;
  23890. })(BABYLON || (BABYLON = {}));
  23891. var BABYLON;
  23892. (function (BABYLON) {
  23893. var DynamicTexture = (function (_super) {
  23894. __extends(DynamicTexture, _super);
  23895. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  23896. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23897. _super.call(this, null, scene, !generateMipMaps);
  23898. this.name = name;
  23899. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23900. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23901. this._generateMipMaps = generateMipMaps;
  23902. if (options.getContext) {
  23903. this._canvas = options;
  23904. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23905. }
  23906. else {
  23907. this._canvas = document.createElement("canvas");
  23908. if (options.width) {
  23909. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23910. }
  23911. else {
  23912. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  23913. }
  23914. }
  23915. var textureSize = this.getSize();
  23916. this._canvas.width = textureSize.width;
  23917. this._canvas.height = textureSize.height;
  23918. this._context = this._canvas.getContext("2d");
  23919. }
  23920. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  23921. get: function () {
  23922. return true;
  23923. },
  23924. enumerable: true,
  23925. configurable: true
  23926. });
  23927. DynamicTexture.prototype.scale = function (ratio) {
  23928. var textureSize = this.getSize();
  23929. textureSize.width *= ratio;
  23930. textureSize.height *= ratio;
  23931. this._canvas.width = textureSize.width;
  23932. this._canvas.height = textureSize.height;
  23933. this.releaseInternalTexture();
  23934. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  23935. };
  23936. DynamicTexture.prototype.getContext = function () {
  23937. return this._context;
  23938. };
  23939. DynamicTexture.prototype.clear = function () {
  23940. var size = this.getSize();
  23941. this._context.fillRect(0, 0, size.width, size.height);
  23942. };
  23943. DynamicTexture.prototype.update = function (invertY) {
  23944. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  23945. };
  23946. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  23947. if (update === void 0) { update = true; }
  23948. var size = this.getSize();
  23949. if (clearColor) {
  23950. this._context.fillStyle = clearColor;
  23951. this._context.fillRect(0, 0, size.width, size.height);
  23952. }
  23953. this._context.font = font;
  23954. if (x === null) {
  23955. var textSize = this._context.measureText(text);
  23956. x = (size.width - textSize.width) / 2;
  23957. }
  23958. this._context.fillStyle = color;
  23959. this._context.fillText(text, x, y);
  23960. if (update) {
  23961. this.update(invertY);
  23962. }
  23963. };
  23964. DynamicTexture.prototype.clone = function () {
  23965. var textureSize = this.getSize();
  23966. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  23967. // Base texture
  23968. newTexture.hasAlpha = this.hasAlpha;
  23969. newTexture.level = this.level;
  23970. // Dynamic Texture
  23971. newTexture.wrapU = this.wrapU;
  23972. newTexture.wrapV = this.wrapV;
  23973. return newTexture;
  23974. };
  23975. return DynamicTexture;
  23976. }(BABYLON.Texture));
  23977. BABYLON.DynamicTexture = DynamicTexture;
  23978. })(BABYLON || (BABYLON = {}));
  23979. var BABYLON;
  23980. (function (BABYLON) {
  23981. var VideoTexture = (function (_super) {
  23982. __extends(VideoTexture, _super);
  23983. /**
  23984. * Creates a video texture.
  23985. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  23986. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  23987. * @param {BABYLON.Scene} scene is obviously the current scene.
  23988. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  23989. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  23990. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  23991. */
  23992. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  23993. var _this = this;
  23994. if (generateMipMaps === void 0) { generateMipMaps = false; }
  23995. if (invertY === void 0) { invertY = false; }
  23996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23997. _super.call(this, null, scene, !generateMipMaps, invertY);
  23998. this._autoLaunch = true;
  23999. var urls;
  24000. this.name = name;
  24001. if (urlsOrVideo instanceof HTMLVideoElement) {
  24002. this.video = urlsOrVideo;
  24003. }
  24004. else {
  24005. urls = urlsOrVideo;
  24006. this.video = document.createElement("video");
  24007. this.video.autoplay = false;
  24008. this.video.loop = true;
  24009. }
  24010. this._generateMipMaps = generateMipMaps;
  24011. this._samplingMode = samplingMode;
  24012. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  24013. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24014. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24015. }
  24016. else {
  24017. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24018. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24019. this._generateMipMaps = false;
  24020. }
  24021. if (urls) {
  24022. this.video.addEventListener("canplaythrough", function () {
  24023. _this._createTexture();
  24024. });
  24025. urls.forEach(function (url) {
  24026. var source = document.createElement("source");
  24027. source.src = url;
  24028. _this.video.appendChild(source);
  24029. });
  24030. }
  24031. else {
  24032. this._createTexture();
  24033. }
  24034. this._lastUpdate = BABYLON.Tools.Now;
  24035. }
  24036. VideoTexture.prototype._createTexture = function () {
  24037. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24038. this._texture.isReady = true;
  24039. };
  24040. VideoTexture.prototype.update = function () {
  24041. if (this._autoLaunch) {
  24042. this._autoLaunch = false;
  24043. this.video.play();
  24044. }
  24045. var now = BABYLON.Tools.Now;
  24046. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24047. return false;
  24048. }
  24049. this._lastUpdate = now;
  24050. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24051. return true;
  24052. };
  24053. return VideoTexture;
  24054. }(BABYLON.Texture));
  24055. BABYLON.VideoTexture = VideoTexture;
  24056. })(BABYLON || (BABYLON = {}));
  24057. var BABYLON;
  24058. (function (BABYLON) {
  24059. var CustomProceduralTexture = (function (_super) {
  24060. __extends(CustomProceduralTexture, _super);
  24061. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24062. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  24063. this._animate = true;
  24064. this._time = 0;
  24065. this._texturePath = texturePath;
  24066. //Try to load json
  24067. this.loadJson(texturePath);
  24068. this.refreshRate = 1;
  24069. }
  24070. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24071. var _this = this;
  24072. var that = this;
  24073. function noConfigFile() {
  24074. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24075. try {
  24076. that.setFragment(that._texturePath);
  24077. }
  24078. catch (ex) {
  24079. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24080. }
  24081. }
  24082. var configFileUrl = jsonUrl + "/config.json";
  24083. var xhr = new XMLHttpRequest();
  24084. xhr.open("GET", configFileUrl, true);
  24085. xhr.addEventListener("load", function () {
  24086. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24087. try {
  24088. _this._config = JSON.parse(xhr.response);
  24089. _this.updateShaderUniforms();
  24090. _this.updateTextures();
  24091. _this.setFragment(_this._texturePath + "/custom");
  24092. _this._animate = _this._config.animate;
  24093. _this.refreshRate = _this._config.refreshrate;
  24094. }
  24095. catch (ex) {
  24096. noConfigFile();
  24097. }
  24098. }
  24099. else {
  24100. noConfigFile();
  24101. }
  24102. }, false);
  24103. xhr.addEventListener("error", function () {
  24104. noConfigFile();
  24105. }, false);
  24106. try {
  24107. xhr.send();
  24108. }
  24109. catch (ex) {
  24110. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24111. }
  24112. };
  24113. CustomProceduralTexture.prototype.isReady = function () {
  24114. if (!_super.prototype.isReady.call(this)) {
  24115. return false;
  24116. }
  24117. for (var name in this._textures) {
  24118. var texture = this._textures[name];
  24119. if (!texture.isReady()) {
  24120. return false;
  24121. }
  24122. }
  24123. return true;
  24124. };
  24125. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24126. if (this._animate) {
  24127. this._time += this.getScene().getAnimationRatio() * 0.03;
  24128. this.updateShaderUniforms();
  24129. }
  24130. _super.prototype.render.call(this, useCameraPostProcess);
  24131. };
  24132. CustomProceduralTexture.prototype.updateTextures = function () {
  24133. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24134. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24135. }
  24136. };
  24137. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24138. if (this._config) {
  24139. for (var j = 0; j < this._config.uniforms.length; j++) {
  24140. var uniform = this._config.uniforms[j];
  24141. switch (uniform.type) {
  24142. case "float":
  24143. this.setFloat(uniform.name, uniform.value);
  24144. break;
  24145. case "color3":
  24146. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24147. break;
  24148. case "color4":
  24149. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24150. break;
  24151. case "vector2":
  24152. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24153. break;
  24154. case "vector3":
  24155. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24156. break;
  24157. }
  24158. }
  24159. }
  24160. this.setFloat("time", this._time);
  24161. };
  24162. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24163. get: function () {
  24164. return this._animate;
  24165. },
  24166. set: function (value) {
  24167. this._animate = value;
  24168. },
  24169. enumerable: true,
  24170. configurable: true
  24171. });
  24172. return CustomProceduralTexture;
  24173. }(BABYLON.ProceduralTexture));
  24174. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24175. })(BABYLON || (BABYLON = {}));
  24176. var BABYLON;
  24177. (function (BABYLON) {
  24178. var EffectFallbacks = (function () {
  24179. function EffectFallbacks() {
  24180. this._defines = {};
  24181. this._currentRank = 32;
  24182. this._maxRank = -1;
  24183. }
  24184. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24185. if (!this._defines[rank]) {
  24186. if (rank < this._currentRank) {
  24187. this._currentRank = rank;
  24188. }
  24189. if (rank > this._maxRank) {
  24190. this._maxRank = rank;
  24191. }
  24192. this._defines[rank] = new Array();
  24193. }
  24194. this._defines[rank].push(define);
  24195. };
  24196. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24197. this._meshRank = rank;
  24198. this._mesh = mesh;
  24199. if (rank > this._maxRank) {
  24200. this._maxRank = rank;
  24201. }
  24202. };
  24203. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24204. get: function () {
  24205. return this._currentRank <= this._maxRank;
  24206. },
  24207. enumerable: true,
  24208. configurable: true
  24209. });
  24210. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24211. var currentFallbacks = this._defines[this._currentRank];
  24212. for (var index = 0; index < currentFallbacks.length; index++) {
  24213. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24214. }
  24215. if (this._mesh && this._currentRank === this._meshRank) {
  24216. this._mesh.computeBonesUsingShaders = false;
  24217. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24218. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24219. }
  24220. this._currentRank++;
  24221. return currentDefines;
  24222. };
  24223. return EffectFallbacks;
  24224. }());
  24225. BABYLON.EffectFallbacks = EffectFallbacks;
  24226. var Effect = (function () {
  24227. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24228. var _this = this;
  24229. this._isReady = false;
  24230. this._compilationError = "";
  24231. this._valueCache = {};
  24232. this._engine = engine;
  24233. this.name = baseName;
  24234. this.defines = defines;
  24235. this._uniformsNames = uniformsNames.concat(samplers);
  24236. this._samplers = samplers;
  24237. this._attributesNames = attributesNames;
  24238. this.onError = onError;
  24239. this.onCompiled = onCompiled;
  24240. this._indexParameters = indexParameters;
  24241. var vertexSource;
  24242. var fragmentSource;
  24243. if (baseName.vertexElement) {
  24244. vertexSource = document.getElementById(baseName.vertexElement);
  24245. if (!vertexSource) {
  24246. vertexSource = baseName.vertexElement;
  24247. }
  24248. }
  24249. else {
  24250. vertexSource = baseName.vertex || baseName;
  24251. }
  24252. if (baseName.fragmentElement) {
  24253. fragmentSource = document.getElementById(baseName.fragmentElement);
  24254. if (!fragmentSource) {
  24255. fragmentSource = baseName.fragmentElement;
  24256. }
  24257. }
  24258. else {
  24259. fragmentSource = baseName.fragment || baseName;
  24260. }
  24261. this._loadVertexShader(vertexSource, function (vertexCode) {
  24262. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24263. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24264. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24265. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24266. });
  24267. });
  24268. });
  24269. });
  24270. }
  24271. // Properties
  24272. Effect.prototype.isReady = function () {
  24273. return this._isReady;
  24274. };
  24275. Effect.prototype.getProgram = function () {
  24276. return this._program;
  24277. };
  24278. Effect.prototype.getAttributesNames = function () {
  24279. return this._attributesNames;
  24280. };
  24281. Effect.prototype.getAttributeLocation = function (index) {
  24282. return this._attributes[index];
  24283. };
  24284. Effect.prototype.getAttributeLocationByName = function (name) {
  24285. var index = this._attributesNames.indexOf(name);
  24286. return this._attributes[index];
  24287. };
  24288. Effect.prototype.getAttributesCount = function () {
  24289. return this._attributes.length;
  24290. };
  24291. Effect.prototype.getUniformIndex = function (uniformName) {
  24292. return this._uniformsNames.indexOf(uniformName);
  24293. };
  24294. Effect.prototype.getUniform = function (uniformName) {
  24295. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24296. };
  24297. Effect.prototype.getSamplers = function () {
  24298. return this._samplers;
  24299. };
  24300. Effect.prototype.getCompilationError = function () {
  24301. return this._compilationError;
  24302. };
  24303. // Methods
  24304. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24305. // DOM element ?
  24306. if (vertex instanceof HTMLElement) {
  24307. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24308. callback(vertexCode);
  24309. return;
  24310. }
  24311. // Is in local store ?
  24312. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24313. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24314. return;
  24315. }
  24316. var vertexShaderUrl;
  24317. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24318. vertexShaderUrl = vertex;
  24319. }
  24320. else {
  24321. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24322. }
  24323. // Vertex shader
  24324. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24325. };
  24326. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24327. // DOM element ?
  24328. if (fragment instanceof HTMLElement) {
  24329. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24330. callback(fragmentCode);
  24331. return;
  24332. }
  24333. // Is in local store ?
  24334. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24335. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24336. return;
  24337. }
  24338. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24339. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24340. return;
  24341. }
  24342. var fragmentShaderUrl;
  24343. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24344. fragmentShaderUrl = fragment;
  24345. }
  24346. else {
  24347. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24348. }
  24349. // Fragment shader
  24350. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24351. };
  24352. Effect.prototype._dumpShadersName = function () {
  24353. if (this.name.vertexElement) {
  24354. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  24355. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  24356. }
  24357. else if (this.name.vertex) {
  24358. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  24359. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  24360. }
  24361. else {
  24362. BABYLON.Tools.Error("Vertex shader:" + this.name);
  24363. BABYLON.Tools.Error("Fragment shader:" + this.name);
  24364. }
  24365. };
  24366. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24367. var _this = this;
  24368. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24369. var match = regex.exec(sourceCode);
  24370. var returnValue = new String(sourceCode);
  24371. while (match != null) {
  24372. var includeFile = match[1];
  24373. if (Effect.IncludesShadersStore[includeFile]) {
  24374. // Substitution
  24375. var includeContent = Effect.IncludesShadersStore[includeFile];
  24376. if (match[2]) {
  24377. var splits = match[3].split(",");
  24378. for (var index = 0; index < splits.length; index += 2) {
  24379. var source = new RegExp(splits[index], "g");
  24380. var dest = splits[index + 1];
  24381. includeContent = includeContent.replace(source, dest);
  24382. }
  24383. }
  24384. if (match[4]) {
  24385. var indexString = match[5];
  24386. if (indexString.indexOf("..") !== -1) {
  24387. var indexSplits = indexString.split("..");
  24388. var minIndex = parseInt(indexSplits[0]);
  24389. var maxIndex = parseInt(indexSplits[1]);
  24390. var sourceIncludeContent = includeContent.slice(0);
  24391. includeContent = "";
  24392. if (isNaN(maxIndex)) {
  24393. maxIndex = this._indexParameters[indexSplits[1]];
  24394. }
  24395. for (var i = minIndex; i <= maxIndex; i++) {
  24396. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24397. }
  24398. }
  24399. else {
  24400. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24401. }
  24402. }
  24403. // Replace
  24404. returnValue = returnValue.replace(match[0], includeContent);
  24405. }
  24406. else {
  24407. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24408. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24409. Effect.IncludesShadersStore[includeFile] = fileContent;
  24410. _this._processIncludes(returnValue, callback);
  24411. });
  24412. return;
  24413. }
  24414. match = regex.exec(sourceCode);
  24415. }
  24416. callback(returnValue);
  24417. };
  24418. Effect.prototype._processPrecision = function (source) {
  24419. if (source.indexOf("precision highp float") === -1) {
  24420. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24421. source = "precision mediump float;\n" + source;
  24422. }
  24423. else {
  24424. source = "precision highp float;\n" + source;
  24425. }
  24426. }
  24427. else {
  24428. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24429. source = source.replace("precision highp float", "precision mediump float");
  24430. }
  24431. }
  24432. return source;
  24433. };
  24434. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  24435. try {
  24436. var engine = this._engine;
  24437. // Precision
  24438. vertexSourceCode = this._processPrecision(vertexSourceCode);
  24439. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  24440. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  24441. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24442. this._attributes = engine.getAttributes(this._program, attributesNames);
  24443. var index;
  24444. for (index = 0; index < this._samplers.length; index++) {
  24445. var sampler = this.getUniform(this._samplers[index]);
  24446. if (sampler == null) {
  24447. this._samplers.splice(index, 1);
  24448. index--;
  24449. }
  24450. }
  24451. engine.bindSamplers(this);
  24452. this._isReady = true;
  24453. if (this.onCompiled) {
  24454. this.onCompiled(this);
  24455. }
  24456. }
  24457. catch (e) {
  24458. // Let's go through fallbacks then
  24459. if (fallbacks && fallbacks.isMoreFallbacks) {
  24460. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  24461. this._dumpShadersName();
  24462. defines = fallbacks.reduce(defines);
  24463. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  24464. }
  24465. else {
  24466. BABYLON.Tools.Error("Unable to compile effect: ");
  24467. this._dumpShadersName();
  24468. BABYLON.Tools.Error("Defines: " + defines);
  24469. BABYLON.Tools.Error("Error: " + e.message);
  24470. this._compilationError = e.message;
  24471. if (this.onError) {
  24472. this.onError(this, this._compilationError);
  24473. }
  24474. }
  24475. }
  24476. };
  24477. Object.defineProperty(Effect.prototype, "isSupported", {
  24478. get: function () {
  24479. return this._compilationError === "";
  24480. },
  24481. enumerable: true,
  24482. configurable: true
  24483. });
  24484. Effect.prototype._bindTexture = function (channel, texture) {
  24485. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24486. };
  24487. Effect.prototype.setTexture = function (channel, texture) {
  24488. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24489. };
  24490. Effect.prototype.setTextureArray = function (channel, textures) {
  24491. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24492. var initialPos = this._samplers.indexOf(channel);
  24493. for (var index = 1; index < textures.length; index++) {
  24494. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24495. }
  24496. }
  24497. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24498. };
  24499. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24500. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24501. };
  24502. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24503. var changed = false;
  24504. var cache = this._valueCache[uniformName];
  24505. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  24506. changed = true;
  24507. cache = new BABYLON.Matrix();
  24508. }
  24509. var tm = cache.m;
  24510. var om = matrix.m;
  24511. for (var index = 0; index < 16; index++) {
  24512. if (tm[index] !== om[index]) {
  24513. tm[index] = om[index];
  24514. changed = true;
  24515. }
  24516. }
  24517. this._valueCache[uniformName] = cache;
  24518. return changed;
  24519. };
  24520. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24521. var cache = this._valueCache[uniformName];
  24522. if (!cache) {
  24523. cache = [x, y];
  24524. this._valueCache[uniformName] = cache;
  24525. return true;
  24526. }
  24527. var changed = false;
  24528. if (cache[0] !== x) {
  24529. cache[0] = x;
  24530. changed = true;
  24531. }
  24532. if (cache[1] !== y) {
  24533. cache[1] = y;
  24534. changed = true;
  24535. }
  24536. return changed;
  24537. };
  24538. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24539. var cache = this._valueCache[uniformName];
  24540. if (!cache) {
  24541. cache = [x, y, z];
  24542. this._valueCache[uniformName] = cache;
  24543. return true;
  24544. }
  24545. var changed = false;
  24546. if (cache[0] !== x) {
  24547. cache[0] = x;
  24548. changed = true;
  24549. }
  24550. if (cache[1] !== y) {
  24551. cache[1] = y;
  24552. changed = true;
  24553. }
  24554. if (cache[2] !== z) {
  24555. cache[2] = z;
  24556. changed = true;
  24557. }
  24558. return changed;
  24559. };
  24560. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24561. var cache = this._valueCache[uniformName];
  24562. if (!cache) {
  24563. cache = [x, y, z, w];
  24564. this._valueCache[uniformName] = cache;
  24565. return true;
  24566. }
  24567. var changed = false;
  24568. if (cache[0] !== x) {
  24569. cache[0] = x;
  24570. changed = true;
  24571. }
  24572. if (cache[1] !== y) {
  24573. cache[1] = y;
  24574. changed = true;
  24575. }
  24576. if (cache[2] !== z) {
  24577. cache[2] = z;
  24578. changed = true;
  24579. }
  24580. if (cache[3] !== w) {
  24581. cache[3] = w;
  24582. changed = true;
  24583. }
  24584. return changed;
  24585. };
  24586. Effect.prototype.setIntArray = function (uniformName, array) {
  24587. this._valueCache[uniformName] = null;
  24588. this._engine.setIntArray(this.getUniform(uniformName), array);
  24589. return this;
  24590. };
  24591. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24592. this._valueCache[uniformName] = null;
  24593. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24594. return this;
  24595. };
  24596. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24597. this._valueCache[uniformName] = null;
  24598. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24599. return this;
  24600. };
  24601. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24602. this._valueCache[uniformName] = null;
  24603. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24604. return this;
  24605. };
  24606. Effect.prototype.setFloatArray = function (uniformName, array) {
  24607. this._valueCache[uniformName] = null;
  24608. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24609. return this;
  24610. };
  24611. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24612. this._valueCache[uniformName] = null;
  24613. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24614. return this;
  24615. };
  24616. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24617. this._valueCache[uniformName] = null;
  24618. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24619. return this;
  24620. };
  24621. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24622. this._valueCache[uniformName] = null;
  24623. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24624. return this;
  24625. };
  24626. Effect.prototype.setArray = function (uniformName, array) {
  24627. this._valueCache[uniformName] = null;
  24628. this._engine.setArray(this.getUniform(uniformName), array);
  24629. return this;
  24630. };
  24631. Effect.prototype.setArray2 = function (uniformName, array) {
  24632. this._valueCache[uniformName] = null;
  24633. this._engine.setArray2(this.getUniform(uniformName), array);
  24634. return this;
  24635. };
  24636. Effect.prototype.setArray3 = function (uniformName, array) {
  24637. this._valueCache[uniformName] = null;
  24638. this._engine.setArray3(this.getUniform(uniformName), array);
  24639. return this;
  24640. };
  24641. Effect.prototype.setArray4 = function (uniformName, array) {
  24642. this._valueCache[uniformName] = null;
  24643. this._engine.setArray4(this.getUniform(uniformName), array);
  24644. return this;
  24645. };
  24646. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24647. this._valueCache[uniformName] = null;
  24648. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24649. return this;
  24650. };
  24651. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24652. if (this._cacheMatrix(uniformName, matrix)) {
  24653. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24654. }
  24655. return this;
  24656. };
  24657. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24658. this._valueCache[uniformName] = null;
  24659. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24660. return this;
  24661. };
  24662. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24663. this._valueCache[uniformName] = null;
  24664. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24665. return this;
  24666. };
  24667. Effect.prototype.setFloat = function (uniformName, value) {
  24668. var cache = this._valueCache[uniformName];
  24669. if (cache !== undefined && cache === value)
  24670. return this;
  24671. this._valueCache[uniformName] = value;
  24672. this._engine.setFloat(this.getUniform(uniformName), value);
  24673. return this;
  24674. };
  24675. Effect.prototype.setBool = function (uniformName, bool) {
  24676. var cache = this._valueCache[uniformName];
  24677. if (cache !== undefined && cache === bool)
  24678. return this;
  24679. this._valueCache[uniformName] = bool;
  24680. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24681. return this;
  24682. };
  24683. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24684. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24685. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24686. }
  24687. return this;
  24688. };
  24689. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24690. if (this._cacheFloat2(uniformName, x, y)) {
  24691. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24692. }
  24693. return this;
  24694. };
  24695. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24696. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24697. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24698. }
  24699. return this;
  24700. };
  24701. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24702. if (this._cacheFloat3(uniformName, x, y, z)) {
  24703. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24704. }
  24705. return this;
  24706. };
  24707. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24708. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24709. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24710. }
  24711. return this;
  24712. };
  24713. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24714. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24715. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24716. }
  24717. return this;
  24718. };
  24719. Effect.prototype.setColor3 = function (uniformName, color3) {
  24720. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24721. this._engine.setColor3(this.getUniform(uniformName), color3);
  24722. }
  24723. return this;
  24724. };
  24725. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24726. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24727. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24728. }
  24729. return this;
  24730. };
  24731. // Statics
  24732. Effect.ShadersStore = {};
  24733. Effect.IncludesShadersStore = {};
  24734. return Effect;
  24735. }());
  24736. BABYLON.Effect = Effect;
  24737. })(BABYLON || (BABYLON = {}));
  24738. var BABYLON;
  24739. (function (BABYLON) {
  24740. var MaterialHelper = (function () {
  24741. function MaterialHelper() {
  24742. }
  24743. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24744. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24745. var lightIndex = 0;
  24746. var needNormals = false;
  24747. var needRebuild = false;
  24748. var needShadows = false;
  24749. var lightmapMode = false;
  24750. for (var index = 0; index < scene.lights.length; index++) {
  24751. var light = scene.lights[index];
  24752. if (!light.isEnabled()) {
  24753. continue;
  24754. }
  24755. // Excluded check
  24756. if (light._excludedMeshesIds.length > 0) {
  24757. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24758. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24759. if (excludedMesh) {
  24760. light.excludedMeshes.push(excludedMesh);
  24761. }
  24762. }
  24763. light._excludedMeshesIds = [];
  24764. }
  24765. // Included check
  24766. if (light._includedOnlyMeshesIds.length > 0) {
  24767. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24768. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24769. if (includedOnlyMesh) {
  24770. light.includedOnlyMeshes.push(includedOnlyMesh);
  24771. }
  24772. }
  24773. light._includedOnlyMeshesIds = [];
  24774. }
  24775. if (!light.canAffectMesh(mesh)) {
  24776. continue;
  24777. }
  24778. needNormals = true;
  24779. if (defines["LIGHT" + lightIndex] === undefined) {
  24780. needRebuild = true;
  24781. }
  24782. defines["LIGHT" + lightIndex] = true;
  24783. var type;
  24784. if (light instanceof BABYLON.SpotLight) {
  24785. type = "SPOTLIGHT" + lightIndex;
  24786. }
  24787. else if (light instanceof BABYLON.HemisphericLight) {
  24788. type = "HEMILIGHT" + lightIndex;
  24789. }
  24790. else if (light instanceof BABYLON.PointLight) {
  24791. type = "POINTLIGHT" + lightIndex;
  24792. }
  24793. else {
  24794. type = "DIRLIGHT" + lightIndex;
  24795. }
  24796. if (defines[type] === undefined) {
  24797. needRebuild = true;
  24798. }
  24799. defines[type] = true;
  24800. // Specular
  24801. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  24802. defines["SPECULARTERM"] = true;
  24803. }
  24804. // Shadows
  24805. if (scene.shadowsEnabled) {
  24806. var shadowGenerator = light.getShadowGenerator();
  24807. if (mesh && mesh.receiveShadows && shadowGenerator) {
  24808. if (defines["SHADOW" + lightIndex] === undefined) {
  24809. needRebuild = true;
  24810. }
  24811. defines["SHADOW" + lightIndex] = true;
  24812. defines["SHADOWS"] = true;
  24813. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  24814. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  24815. needRebuild = true;
  24816. }
  24817. defines["SHADOWVSM" + lightIndex] = true;
  24818. }
  24819. if (shadowGenerator.usePoissonSampling) {
  24820. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  24821. needRebuild = true;
  24822. }
  24823. defines["SHADOWPCF" + lightIndex] = true;
  24824. }
  24825. needShadows = true;
  24826. }
  24827. }
  24828. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24829. lightmapMode = true;
  24830. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  24831. needRebuild = true;
  24832. }
  24833. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  24834. needRebuild = true;
  24835. }
  24836. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24837. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  24838. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  24839. }
  24840. }
  24841. lightIndex++;
  24842. if (lightIndex === maxSimultaneousLights)
  24843. break;
  24844. }
  24845. var caps = scene.getEngine().getCaps();
  24846. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  24847. if (defines["SHADOWFULLFLOAT"] === undefined) {
  24848. needRebuild = true;
  24849. }
  24850. defines["SHADOWFULLFLOAT"] = true;
  24851. }
  24852. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  24853. needRebuild = true;
  24854. }
  24855. if (lightmapMode) {
  24856. defines["LIGHTMAPEXCLUDED"] = true;
  24857. }
  24858. if (needRebuild) {
  24859. defines.rebuild();
  24860. }
  24861. return needNormals;
  24862. };
  24863. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  24864. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24865. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24866. if (!defines["LIGHT" + lightIndex]) {
  24867. break;
  24868. }
  24869. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  24870. samplersList.push("shadowSampler" + lightIndex);
  24871. }
  24872. };
  24873. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24874. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24875. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24876. if (!defines["LIGHT" + lightIndex]) {
  24877. break;
  24878. }
  24879. if (lightIndex > 0) {
  24880. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24881. }
  24882. if (defines["SHADOW" + lightIndex]) {
  24883. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24884. }
  24885. if (defines["SHADOWPCF" + lightIndex]) {
  24886. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24887. }
  24888. if (defines["SHADOWVSM" + lightIndex]) {
  24889. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  24890. }
  24891. }
  24892. };
  24893. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24894. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24895. fallbacks.addCPUSkinningFallback(0, mesh);
  24896. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24897. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24898. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24899. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24900. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24901. }
  24902. }
  24903. };
  24904. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24905. if (defines["INSTANCES"]) {
  24906. attribs.push("world0");
  24907. attribs.push("world1");
  24908. attribs.push("world2");
  24909. attribs.push("world3");
  24910. }
  24911. };
  24912. // Bindings
  24913. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  24914. var shadowGenerator = light.getShadowGenerator();
  24915. if (mesh.receiveShadows && shadowGenerator) {
  24916. if (!light.needCube()) {
  24917. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  24918. }
  24919. else {
  24920. if (!depthValuesAlreadySet) {
  24921. depthValuesAlreadySet = true;
  24922. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  24923. }
  24924. }
  24925. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  24926. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  24927. }
  24928. return depthValuesAlreadySet;
  24929. };
  24930. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24931. if (light instanceof BABYLON.PointLight) {
  24932. // Point Light
  24933. light.transferToEffect(effect, "vLightData" + lightIndex);
  24934. }
  24935. else if (light instanceof BABYLON.DirectionalLight) {
  24936. // Directional Light
  24937. light.transferToEffect(effect, "vLightData" + lightIndex);
  24938. }
  24939. else if (light instanceof BABYLON.SpotLight) {
  24940. // Spot Light
  24941. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  24942. }
  24943. else if (light instanceof BABYLON.HemisphericLight) {
  24944. // Hemispheric Light
  24945. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  24946. }
  24947. };
  24948. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  24949. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24950. var lightIndex = 0;
  24951. var depthValuesAlreadySet = false;
  24952. for (var index = 0; index < scene.lights.length; index++) {
  24953. var light = scene.lights[index];
  24954. if (!light.isEnabled()) {
  24955. continue;
  24956. }
  24957. if (!light.canAffectMesh(mesh)) {
  24958. continue;
  24959. }
  24960. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24961. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  24962. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  24963. if (defines["SPECULARTERM"]) {
  24964. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  24965. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  24966. }
  24967. // Shadows
  24968. if (scene.shadowsEnabled) {
  24969. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  24970. }
  24971. lightIndex++;
  24972. if (lightIndex === maxSimultaneousLights)
  24973. break;
  24974. }
  24975. };
  24976. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24977. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24978. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24979. effect.setColor3("vFogColor", scene.fogColor);
  24980. }
  24981. };
  24982. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24983. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24984. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  24985. if (matrices) {
  24986. effect.setMatrices("mBones", matrices);
  24987. }
  24988. }
  24989. };
  24990. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24991. if (defines["LOGARITHMICDEPTH"]) {
  24992. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24993. }
  24994. };
  24995. MaterialHelper.BindClipPlane = function (effect, scene) {
  24996. if (scene.clipPlane) {
  24997. var clipPlane = scene.clipPlane;
  24998. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24999. }
  25000. };
  25001. return MaterialHelper;
  25002. }());
  25003. BABYLON.MaterialHelper = MaterialHelper;
  25004. })(BABYLON || (BABYLON = {}));
  25005. var BABYLON;
  25006. (function (BABYLON) {
  25007. var FresnelParameters = (function () {
  25008. function FresnelParameters() {
  25009. this.isEnabled = true;
  25010. this.leftColor = BABYLON.Color3.White();
  25011. this.rightColor = BABYLON.Color3.Black();
  25012. this.bias = 0;
  25013. this.power = 1;
  25014. }
  25015. FresnelParameters.prototype.clone = function () {
  25016. var newFresnelParameters = new FresnelParameters();
  25017. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25018. return new FresnelParameters;
  25019. };
  25020. FresnelParameters.prototype.serialize = function () {
  25021. var serializationObject = {};
  25022. serializationObject.isEnabled = this.isEnabled;
  25023. serializationObject.leftColor = this.leftColor;
  25024. serializationObject.rightColor = this.rightColor;
  25025. serializationObject.bias = this.bias;
  25026. serializationObject.power = this.power;
  25027. return serializationObject;
  25028. };
  25029. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25030. var fresnelParameters = new FresnelParameters();
  25031. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25032. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25033. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25034. fresnelParameters.bias = parsedFresnelParameters.bias;
  25035. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25036. return fresnelParameters;
  25037. };
  25038. return FresnelParameters;
  25039. }());
  25040. BABYLON.FresnelParameters = FresnelParameters;
  25041. })(BABYLON || (BABYLON = {}));
  25042. var BABYLON;
  25043. (function (BABYLON) {
  25044. var MaterialDefines = (function () {
  25045. function MaterialDefines() {
  25046. }
  25047. MaterialDefines.prototype.rebuild = function () {
  25048. if (this._keys) {
  25049. delete this._keys;
  25050. }
  25051. this._keys = Object.keys(this);
  25052. };
  25053. MaterialDefines.prototype.isEqual = function (other) {
  25054. if (this._keys.length !== other._keys.length) {
  25055. return false;
  25056. }
  25057. for (var index = 0; index < this._keys.length; index++) {
  25058. var prop = this._keys[index];
  25059. if (this[prop] !== other[prop]) {
  25060. return false;
  25061. }
  25062. }
  25063. return true;
  25064. };
  25065. MaterialDefines.prototype.cloneTo = function (other) {
  25066. if (this._keys.length !== other._keys.length) {
  25067. other._keys = this._keys.slice(0);
  25068. }
  25069. for (var index = 0; index < this._keys.length; index++) {
  25070. var prop = this._keys[index];
  25071. other[prop] = this[prop];
  25072. }
  25073. };
  25074. MaterialDefines.prototype.reset = function () {
  25075. for (var index = 0; index < this._keys.length; index++) {
  25076. var prop = this._keys[index];
  25077. if (typeof (this[prop]) === "number") {
  25078. this[prop] = 0;
  25079. }
  25080. else {
  25081. this[prop] = false;
  25082. }
  25083. }
  25084. };
  25085. MaterialDefines.prototype.toString = function () {
  25086. var result = "";
  25087. for (var index = 0; index < this._keys.length; index++) {
  25088. var prop = this._keys[index];
  25089. if (typeof (this[prop]) === "number") {
  25090. result += "#define " + prop + " " + this[prop] + "\n";
  25091. }
  25092. else if (this[prop]) {
  25093. result += "#define " + prop + "\n";
  25094. }
  25095. }
  25096. return result;
  25097. };
  25098. return MaterialDefines;
  25099. }());
  25100. BABYLON.MaterialDefines = MaterialDefines;
  25101. var Material = (function () {
  25102. function Material(name, scene, doNotAdd) {
  25103. this.name = name;
  25104. this.checkReadyOnEveryCall = false;
  25105. this.checkReadyOnlyOnce = false;
  25106. this.state = "";
  25107. this.alpha = 1.0;
  25108. this.backFaceCulling = true;
  25109. /**
  25110. * An event triggered when the material is disposed.
  25111. * @type {BABYLON.Observable}
  25112. */
  25113. this.onDisposeObservable = new BABYLON.Observable();
  25114. /**
  25115. * An event triggered when the material is bound.
  25116. * @type {BABYLON.Observable}
  25117. */
  25118. this.onBindObservable = new BABYLON.Observable();
  25119. /**
  25120. * An event triggered when the material is unbound.
  25121. * @type {BABYLON.Observable}
  25122. */
  25123. this.onUnBindObservable = new BABYLON.Observable();
  25124. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25125. this.disableDepthWrite = false;
  25126. this.fogEnabled = true;
  25127. this.pointSize = 1.0;
  25128. this.zOffset = 0;
  25129. this._wasPreviouslyReady = false;
  25130. this._fillMode = Material.TriangleFillMode;
  25131. this.id = name;
  25132. this._scene = scene;
  25133. if (scene.useRightHandedSystem) {
  25134. this.sideOrientation = Material.ClockWiseSideOrientation;
  25135. }
  25136. else {
  25137. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25138. }
  25139. if (!doNotAdd) {
  25140. scene.materials.push(this);
  25141. }
  25142. }
  25143. Object.defineProperty(Material, "TriangleFillMode", {
  25144. get: function () {
  25145. return Material._TriangleFillMode;
  25146. },
  25147. enumerable: true,
  25148. configurable: true
  25149. });
  25150. Object.defineProperty(Material, "WireFrameFillMode", {
  25151. get: function () {
  25152. return Material._WireFrameFillMode;
  25153. },
  25154. enumerable: true,
  25155. configurable: true
  25156. });
  25157. Object.defineProperty(Material, "PointFillMode", {
  25158. get: function () {
  25159. return Material._PointFillMode;
  25160. },
  25161. enumerable: true,
  25162. configurable: true
  25163. });
  25164. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25165. get: function () {
  25166. return Material._ClockWiseSideOrientation;
  25167. },
  25168. enumerable: true,
  25169. configurable: true
  25170. });
  25171. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25172. get: function () {
  25173. return Material._CounterClockWiseSideOrientation;
  25174. },
  25175. enumerable: true,
  25176. configurable: true
  25177. });
  25178. Object.defineProperty(Material.prototype, "onDispose", {
  25179. set: function (callback) {
  25180. if (this._onDisposeObserver) {
  25181. this.onDisposeObservable.remove(this._onDisposeObserver);
  25182. }
  25183. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25184. },
  25185. enumerable: true,
  25186. configurable: true
  25187. });
  25188. Object.defineProperty(Material.prototype, "onBind", {
  25189. set: function (callback) {
  25190. if (this._onBindObserver) {
  25191. this.onBindObservable.remove(this._onBindObserver);
  25192. }
  25193. this._onBindObserver = this.onBindObservable.add(callback);
  25194. },
  25195. enumerable: true,
  25196. configurable: true
  25197. });
  25198. Object.defineProperty(Material.prototype, "wireframe", {
  25199. get: function () {
  25200. return this._fillMode === Material.WireFrameFillMode;
  25201. },
  25202. set: function (value) {
  25203. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25204. },
  25205. enumerable: true,
  25206. configurable: true
  25207. });
  25208. Object.defineProperty(Material.prototype, "pointsCloud", {
  25209. get: function () {
  25210. return this._fillMode === Material.PointFillMode;
  25211. },
  25212. set: function (value) {
  25213. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25214. },
  25215. enumerable: true,
  25216. configurable: true
  25217. });
  25218. Object.defineProperty(Material.prototype, "fillMode", {
  25219. get: function () {
  25220. return this._fillMode;
  25221. },
  25222. set: function (value) {
  25223. this._fillMode = value;
  25224. },
  25225. enumerable: true,
  25226. configurable: true
  25227. });
  25228. /**
  25229. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25230. * subclasses should override adding information pertainent to themselves
  25231. */
  25232. Material.prototype.toString = function (fullDetails) {
  25233. var ret = "Name: " + this.name;
  25234. if (fullDetails) {
  25235. }
  25236. return ret;
  25237. };
  25238. Object.defineProperty(Material.prototype, "isFrozen", {
  25239. get: function () {
  25240. return this.checkReadyOnlyOnce;
  25241. },
  25242. enumerable: true,
  25243. configurable: true
  25244. });
  25245. Material.prototype.freeze = function () {
  25246. this.checkReadyOnlyOnce = true;
  25247. };
  25248. Material.prototype.unfreeze = function () {
  25249. this.checkReadyOnlyOnce = false;
  25250. };
  25251. Material.prototype.isReady = function (mesh, useInstances) {
  25252. return true;
  25253. };
  25254. Material.prototype.getEffect = function () {
  25255. return this._effect;
  25256. };
  25257. Material.prototype.getScene = function () {
  25258. return this._scene;
  25259. };
  25260. Material.prototype.needAlphaBlending = function () {
  25261. return (this.alpha < 1.0);
  25262. };
  25263. Material.prototype.needAlphaTesting = function () {
  25264. return false;
  25265. };
  25266. Material.prototype.getAlphaTestTexture = function () {
  25267. return null;
  25268. };
  25269. Material.prototype.markDirty = function () {
  25270. this._wasPreviouslyReady = false;
  25271. };
  25272. Material.prototype._preBind = function () {
  25273. var engine = this._scene.getEngine();
  25274. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25275. engine.enableEffect(this._effect);
  25276. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25277. };
  25278. Material.prototype.bind = function (world, mesh) {
  25279. this._scene._cachedMaterial = this;
  25280. this.onBindObservable.notifyObservers(mesh);
  25281. if (this.disableDepthWrite) {
  25282. var engine = this._scene.getEngine();
  25283. this._cachedDepthWriteState = engine.getDepthWrite();
  25284. engine.setDepthWrite(false);
  25285. }
  25286. };
  25287. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25288. };
  25289. Material.prototype.unbind = function () {
  25290. this.onUnBindObservable.notifyObservers(this);
  25291. if (this.disableDepthWrite) {
  25292. var engine = this._scene.getEngine();
  25293. engine.setDepthWrite(this._cachedDepthWriteState);
  25294. }
  25295. };
  25296. Material.prototype.clone = function (name) {
  25297. return null;
  25298. };
  25299. Material.prototype.getBindedMeshes = function () {
  25300. var result = new Array();
  25301. for (var index = 0; index < this._scene.meshes.length; index++) {
  25302. var mesh = this._scene.meshes[index];
  25303. if (mesh.material === this) {
  25304. result.push(mesh);
  25305. }
  25306. }
  25307. return result;
  25308. };
  25309. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25310. // Animations
  25311. this.getScene().stopAnimation(this);
  25312. // Remove from scene
  25313. var index = this._scene.materials.indexOf(this);
  25314. if (index >= 0) {
  25315. this._scene.materials.splice(index, 1);
  25316. }
  25317. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25318. if (forceDisposeEffect && this._effect) {
  25319. this._scene.getEngine()._releaseEffect(this._effect);
  25320. this._effect = null;
  25321. }
  25322. // Remove from meshes
  25323. for (index = 0; index < this._scene.meshes.length; index++) {
  25324. var mesh = this._scene.meshes[index];
  25325. if (mesh.material === this) {
  25326. mesh.material = null;
  25327. }
  25328. }
  25329. // Callback
  25330. this.onDisposeObservable.notifyObservers(this);
  25331. this.onDisposeObservable.clear();
  25332. this.onBindObservable.clear();
  25333. this.onUnBindObservable.clear();
  25334. };
  25335. Material.prototype.serialize = function () {
  25336. return BABYLON.SerializationHelper.Serialize(this);
  25337. };
  25338. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25339. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25340. multiMaterial.id = parsedMultiMaterial.id;
  25341. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25342. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25343. var subMatId = parsedMultiMaterial.materials[matIndex];
  25344. if (subMatId) {
  25345. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25346. }
  25347. else {
  25348. multiMaterial.subMaterials.push(null);
  25349. }
  25350. }
  25351. return multiMaterial;
  25352. };
  25353. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25354. if (!parsedMaterial.customType) {
  25355. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25356. }
  25357. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25358. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25359. ;
  25360. };
  25361. Material._TriangleFillMode = 0;
  25362. Material._WireFrameFillMode = 1;
  25363. Material._PointFillMode = 2;
  25364. Material._ClockWiseSideOrientation = 0;
  25365. Material._CounterClockWiseSideOrientation = 1;
  25366. __decorate([
  25367. BABYLON.serialize()
  25368. ], Material.prototype, "id", void 0);
  25369. __decorate([
  25370. BABYLON.serialize()
  25371. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25372. __decorate([
  25373. BABYLON.serialize()
  25374. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25375. __decorate([
  25376. BABYLON.serialize()
  25377. ], Material.prototype, "state", void 0);
  25378. __decorate([
  25379. BABYLON.serialize()
  25380. ], Material.prototype, "alpha", void 0);
  25381. __decorate([
  25382. BABYLON.serialize()
  25383. ], Material.prototype, "backFaceCulling", void 0);
  25384. __decorate([
  25385. BABYLON.serialize()
  25386. ], Material.prototype, "sideOrientation", void 0);
  25387. __decorate([
  25388. BABYLON.serialize()
  25389. ], Material.prototype, "alphaMode", void 0);
  25390. __decorate([
  25391. BABYLON.serialize()
  25392. ], Material.prototype, "disableDepthWrite", void 0);
  25393. __decorate([
  25394. BABYLON.serialize()
  25395. ], Material.prototype, "fogEnabled", void 0);
  25396. __decorate([
  25397. BABYLON.serialize()
  25398. ], Material.prototype, "pointSize", void 0);
  25399. __decorate([
  25400. BABYLON.serialize()
  25401. ], Material.prototype, "zOffset", void 0);
  25402. __decorate([
  25403. BABYLON.serialize()
  25404. ], Material.prototype, "wireframe", null);
  25405. __decorate([
  25406. BABYLON.serialize()
  25407. ], Material.prototype, "pointsCloud", null);
  25408. __decorate([
  25409. BABYLON.serialize()
  25410. ], Material.prototype, "fillMode", null);
  25411. return Material;
  25412. }());
  25413. BABYLON.Material = Material;
  25414. })(BABYLON || (BABYLON = {}));
  25415. var BABYLON;
  25416. (function (BABYLON) {
  25417. var StandardMaterialDefines = (function (_super) {
  25418. __extends(StandardMaterialDefines, _super);
  25419. function StandardMaterialDefines() {
  25420. _super.call(this);
  25421. this.DIFFUSE = false;
  25422. this.AMBIENT = false;
  25423. this.OPACITY = false;
  25424. this.OPACITYRGB = false;
  25425. this.REFLECTION = false;
  25426. this.EMISSIVE = false;
  25427. this.SPECULAR = false;
  25428. this.BUMP = false;
  25429. this.PARALLAX = false;
  25430. this.PARALLAXOCCLUSION = false;
  25431. this.SPECULAROVERALPHA = false;
  25432. this.CLIPPLANE = false;
  25433. this.ALPHATEST = false;
  25434. this.ALPHAFROMDIFFUSE = false;
  25435. this.POINTSIZE = false;
  25436. this.FOG = false;
  25437. this.SPECULARTERM = false;
  25438. this.DIFFUSEFRESNEL = false;
  25439. this.OPACITYFRESNEL = false;
  25440. this.REFLECTIONFRESNEL = false;
  25441. this.REFRACTIONFRESNEL = false;
  25442. this.EMISSIVEFRESNEL = false;
  25443. this.FRESNEL = false;
  25444. this.NORMAL = false;
  25445. this.UV1 = false;
  25446. this.UV2 = false;
  25447. this.VERTEXCOLOR = false;
  25448. this.VERTEXALPHA = false;
  25449. this.NUM_BONE_INFLUENCERS = 0;
  25450. this.BonesPerMesh = 0;
  25451. this.INSTANCES = false;
  25452. this.GLOSSINESS = false;
  25453. this.ROUGHNESS = false;
  25454. this.EMISSIVEASILLUMINATION = false;
  25455. this.LINKEMISSIVEWITHDIFFUSE = false;
  25456. this.REFLECTIONFRESNELFROMSPECULAR = false;
  25457. this.LIGHTMAP = false;
  25458. this.USELIGHTMAPASSHADOWMAP = false;
  25459. this.REFLECTIONMAP_3D = false;
  25460. this.REFLECTIONMAP_SPHERICAL = false;
  25461. this.REFLECTIONMAP_PLANAR = false;
  25462. this.REFLECTIONMAP_CUBIC = false;
  25463. this.REFLECTIONMAP_PROJECTION = false;
  25464. this.REFLECTIONMAP_SKYBOX = false;
  25465. this.REFLECTIONMAP_EXPLICIT = false;
  25466. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  25467. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  25468. this.INVERTCUBICMAP = false;
  25469. this.LOGARITHMICDEPTH = false;
  25470. this.REFRACTION = false;
  25471. this.REFRACTIONMAP_3D = false;
  25472. this.REFLECTIONOVERALPHA = false;
  25473. this.INVERTNORMALMAPX = false;
  25474. this.INVERTNORMALMAPY = false;
  25475. this.SHADOWFULLFLOAT = false;
  25476. this.CAMERACOLORGRADING = false;
  25477. this.CAMERACOLORCURVES = false;
  25478. this.rebuild();
  25479. }
  25480. return StandardMaterialDefines;
  25481. }(BABYLON.MaterialDefines));
  25482. var StandardMaterial = (function (_super) {
  25483. __extends(StandardMaterial, _super);
  25484. function StandardMaterial(name, scene) {
  25485. var _this = this;
  25486. _super.call(this, name, scene);
  25487. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25488. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  25489. this.specularColor = new BABYLON.Color3(1, 1, 1);
  25490. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  25491. this.specularPower = 64;
  25492. this.useAlphaFromDiffuseTexture = false;
  25493. this.useEmissiveAsIllumination = false;
  25494. this.linkEmissiveWithDiffuse = false;
  25495. this.useReflectionFresnelFromSpecular = false;
  25496. this.useSpecularOverAlpha = false;
  25497. this.useReflectionOverAlpha = false;
  25498. this.disableLighting = false;
  25499. this.useParallax = false;
  25500. this.useParallaxOcclusion = false;
  25501. this.parallaxScaleBias = 0.05;
  25502. this.roughness = 0;
  25503. this.indexOfRefraction = 0.98;
  25504. this.invertRefractionY = true;
  25505. this.useLightmapAsShadowmap = false;
  25506. this.useGlossinessFromSpecularMapAlpha = false;
  25507. this.maxSimultaneousLights = 4;
  25508. /**
  25509. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  25510. */
  25511. this.invertNormalMapX = false;
  25512. /**
  25513. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  25514. */
  25515. this.invertNormalMapY = false;
  25516. /**
  25517. * Color Grading 2D Lookup Texture.
  25518. * This allows special effects like sepia, black and white to sixties rendering style.
  25519. */
  25520. this.cameraColorGradingTexture = null;
  25521. /**
  25522. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  25523. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  25524. * 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;
  25525. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  25526. */
  25527. this.cameraColorCurves = null;
  25528. this._renderTargets = new BABYLON.SmartArray(16);
  25529. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  25530. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  25531. this._defines = new StandardMaterialDefines();
  25532. this._cachedDefines = new StandardMaterialDefines();
  25533. this._cachedDefines.BonesPerMesh = -1;
  25534. this.getRenderTargetTextures = function () {
  25535. _this._renderTargets.reset();
  25536. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  25537. _this._renderTargets.push(_this.reflectionTexture);
  25538. }
  25539. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  25540. _this._renderTargets.push(_this.refractionTexture);
  25541. }
  25542. return _this._renderTargets;
  25543. };
  25544. }
  25545. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  25546. get: function () {
  25547. return this._useLogarithmicDepth;
  25548. },
  25549. set: function (value) {
  25550. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  25551. },
  25552. enumerable: true,
  25553. configurable: true
  25554. });
  25555. StandardMaterial.prototype.needAlphaBlending = function () {
  25556. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  25557. };
  25558. StandardMaterial.prototype.needAlphaTesting = function () {
  25559. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  25560. };
  25561. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  25562. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  25563. };
  25564. StandardMaterial.prototype.getAlphaTestTexture = function () {
  25565. return this.diffuseTexture;
  25566. };
  25567. // Methods
  25568. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  25569. if (!mesh) {
  25570. return true;
  25571. }
  25572. if (this._defines.INSTANCES !== useInstances) {
  25573. return false;
  25574. }
  25575. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25576. return true;
  25577. }
  25578. return false;
  25579. };
  25580. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25581. if (this.isFrozen) {
  25582. if (this._wasPreviouslyReady) {
  25583. return true;
  25584. }
  25585. }
  25586. var scene = this.getScene();
  25587. if (!this.checkReadyOnEveryCall) {
  25588. if (this._renderId === scene.getRenderId()) {
  25589. if (this._checkCache(scene, mesh, useInstances)) {
  25590. return true;
  25591. }
  25592. }
  25593. }
  25594. var engine = scene.getEngine();
  25595. var needNormals = false;
  25596. var needUVs = false;
  25597. this._defines.reset();
  25598. // Textures
  25599. if (scene.texturesEnabled) {
  25600. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25601. if (!this.diffuseTexture.isReady()) {
  25602. return false;
  25603. }
  25604. else {
  25605. needUVs = true;
  25606. this._defines.DIFFUSE = true;
  25607. }
  25608. }
  25609. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25610. if (!this.ambientTexture.isReady()) {
  25611. return false;
  25612. }
  25613. else {
  25614. needUVs = true;
  25615. this._defines.AMBIENT = true;
  25616. }
  25617. }
  25618. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25619. if (!this.opacityTexture.isReady()) {
  25620. return false;
  25621. }
  25622. else {
  25623. needUVs = true;
  25624. this._defines.OPACITY = true;
  25625. if (this.opacityTexture.getAlphaFromRGB) {
  25626. this._defines.OPACITYRGB = true;
  25627. }
  25628. }
  25629. }
  25630. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25631. if (!this.reflectionTexture.isReady()) {
  25632. return false;
  25633. }
  25634. else {
  25635. needNormals = true;
  25636. this._defines.REFLECTION = true;
  25637. if (this.roughness > 0) {
  25638. this._defines.ROUGHNESS = true;
  25639. }
  25640. if (this.useReflectionOverAlpha) {
  25641. this._defines.REFLECTIONOVERALPHA = true;
  25642. }
  25643. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25644. this._defines.INVERTCUBICMAP = true;
  25645. }
  25646. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25647. switch (this.reflectionTexture.coordinatesMode) {
  25648. case BABYLON.Texture.CUBIC_MODE:
  25649. case BABYLON.Texture.INVCUBIC_MODE:
  25650. this._defines.REFLECTIONMAP_CUBIC = true;
  25651. break;
  25652. case BABYLON.Texture.EXPLICIT_MODE:
  25653. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25654. break;
  25655. case BABYLON.Texture.PLANAR_MODE:
  25656. this._defines.REFLECTIONMAP_PLANAR = true;
  25657. break;
  25658. case BABYLON.Texture.PROJECTION_MODE:
  25659. this._defines.REFLECTIONMAP_PROJECTION = true;
  25660. break;
  25661. case BABYLON.Texture.SKYBOX_MODE:
  25662. this._defines.REFLECTIONMAP_SKYBOX = true;
  25663. break;
  25664. case BABYLON.Texture.SPHERICAL_MODE:
  25665. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25666. break;
  25667. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25668. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25669. break;
  25670. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25671. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25672. break;
  25673. }
  25674. }
  25675. }
  25676. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25677. if (!this.emissiveTexture.isReady()) {
  25678. return false;
  25679. }
  25680. else {
  25681. needUVs = true;
  25682. this._defines.EMISSIVE = true;
  25683. }
  25684. }
  25685. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25686. if (!this.lightmapTexture.isReady()) {
  25687. return false;
  25688. }
  25689. else {
  25690. needUVs = true;
  25691. this._defines.LIGHTMAP = true;
  25692. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25693. }
  25694. }
  25695. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25696. if (!this.specularTexture.isReady()) {
  25697. return false;
  25698. }
  25699. else {
  25700. needUVs = true;
  25701. this._defines.SPECULAR = true;
  25702. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25703. }
  25704. }
  25705. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25706. if (!this.bumpTexture.isReady()) {
  25707. return false;
  25708. }
  25709. else {
  25710. needUVs = true;
  25711. this._defines.BUMP = true;
  25712. if (this.useParallax) {
  25713. this._defines.PARALLAX = true;
  25714. if (this.useParallaxOcclusion) {
  25715. this._defines.PARALLAXOCCLUSION = true;
  25716. }
  25717. }
  25718. if (this.invertNormalMapX) {
  25719. this._defines.INVERTNORMALMAPX = true;
  25720. }
  25721. if (this.invertNormalMapY) {
  25722. this._defines.INVERTNORMALMAPY = true;
  25723. }
  25724. }
  25725. }
  25726. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25727. if (!this.refractionTexture.isReady()) {
  25728. return false;
  25729. }
  25730. else {
  25731. needUVs = true;
  25732. this._defines.REFRACTION = true;
  25733. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25734. }
  25735. }
  25736. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25737. if (!this.cameraColorGradingTexture.isReady()) {
  25738. return false;
  25739. }
  25740. else {
  25741. this._defines.CAMERACOLORGRADING = true;
  25742. }
  25743. }
  25744. }
  25745. // Effect
  25746. if (scene.clipPlane) {
  25747. this._defines.CLIPPLANE = true;
  25748. }
  25749. if (engine.getAlphaTesting()) {
  25750. this._defines.ALPHATEST = true;
  25751. }
  25752. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25753. this._defines.ALPHAFROMDIFFUSE = true;
  25754. }
  25755. if (this.useEmissiveAsIllumination) {
  25756. this._defines.EMISSIVEASILLUMINATION = true;
  25757. }
  25758. if (this.linkEmissiveWithDiffuse) {
  25759. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25760. }
  25761. if (this.useLogarithmicDepth) {
  25762. this._defines.LOGARITHMICDEPTH = true;
  25763. }
  25764. if (this.cameraColorCurves) {
  25765. this._defines.CAMERACOLORCURVES = true;
  25766. }
  25767. // Point size
  25768. if (this.pointsCloud || scene.forcePointsCloud) {
  25769. this._defines.POINTSIZE = true;
  25770. }
  25771. // Fog
  25772. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25773. this._defines.FOG = true;
  25774. }
  25775. if (scene.lightsEnabled && !this.disableLighting) {
  25776. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25777. }
  25778. if (StandardMaterial.FresnelEnabled) {
  25779. // Fresnel
  25780. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25781. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25782. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25783. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25784. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25785. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25786. this._defines.DIFFUSEFRESNEL = true;
  25787. }
  25788. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25789. this._defines.OPACITYFRESNEL = true;
  25790. }
  25791. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25792. this._defines.REFLECTIONFRESNEL = true;
  25793. if (this.useReflectionFresnelFromSpecular) {
  25794. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  25795. }
  25796. }
  25797. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25798. this._defines.REFRACTIONFRESNEL = true;
  25799. }
  25800. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25801. this._defines.EMISSIVEFRESNEL = true;
  25802. }
  25803. needNormals = true;
  25804. this._defines.FRESNEL = true;
  25805. }
  25806. }
  25807. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  25808. this._defines.SPECULAROVERALPHA = true;
  25809. }
  25810. // Attribs
  25811. if (mesh) {
  25812. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25813. this._defines.NORMAL = true;
  25814. }
  25815. if (needUVs) {
  25816. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25817. this._defines.UV1 = true;
  25818. }
  25819. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25820. this._defines.UV2 = true;
  25821. }
  25822. }
  25823. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25824. this._defines.VERTEXCOLOR = true;
  25825. if (mesh.hasVertexAlpha) {
  25826. this._defines.VERTEXALPHA = true;
  25827. }
  25828. }
  25829. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25830. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  25831. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  25832. }
  25833. // Instances
  25834. if (useInstances) {
  25835. this._defines.INSTANCES = true;
  25836. }
  25837. }
  25838. // Get correct effect
  25839. if (!this._defines.isEqual(this._cachedDefines)) {
  25840. this._defines.cloneTo(this._cachedDefines);
  25841. scene.resetCachedMaterial();
  25842. // Fallbacks
  25843. var fallbacks = new BABYLON.EffectFallbacks();
  25844. if (this._defines.REFLECTION) {
  25845. fallbacks.addFallback(0, "REFLECTION");
  25846. }
  25847. if (this._defines.SPECULAR) {
  25848. fallbacks.addFallback(0, "SPECULAR");
  25849. }
  25850. if (this._defines.BUMP) {
  25851. fallbacks.addFallback(0, "BUMP");
  25852. }
  25853. if (this._defines.PARALLAX) {
  25854. fallbacks.addFallback(1, "PARALLAX");
  25855. }
  25856. if (this._defines.PARALLAXOCCLUSION) {
  25857. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  25858. }
  25859. if (this._defines.SPECULAROVERALPHA) {
  25860. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  25861. }
  25862. if (this._defines.FOG) {
  25863. fallbacks.addFallback(1, "FOG");
  25864. }
  25865. if (this._defines.POINTSIZE) {
  25866. fallbacks.addFallback(0, "POINTSIZE");
  25867. }
  25868. if (this._defines.LOGARITHMICDEPTH) {
  25869. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  25870. }
  25871. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  25872. if (this._defines.SPECULARTERM) {
  25873. fallbacks.addFallback(0, "SPECULARTERM");
  25874. }
  25875. if (this._defines.DIFFUSEFRESNEL) {
  25876. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  25877. }
  25878. if (this._defines.OPACITYFRESNEL) {
  25879. fallbacks.addFallback(2, "OPACITYFRESNEL");
  25880. }
  25881. if (this._defines.REFLECTIONFRESNEL) {
  25882. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  25883. }
  25884. if (this._defines.EMISSIVEFRESNEL) {
  25885. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  25886. }
  25887. if (this._defines.FRESNEL) {
  25888. fallbacks.addFallback(4, "FRESNEL");
  25889. }
  25890. //Attributes
  25891. var attribs = [BABYLON.VertexBuffer.PositionKind];
  25892. if (this._defines.NORMAL) {
  25893. attribs.push(BABYLON.VertexBuffer.NormalKind);
  25894. }
  25895. if (this._defines.UV1) {
  25896. attribs.push(BABYLON.VertexBuffer.UVKind);
  25897. }
  25898. if (this._defines.UV2) {
  25899. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25900. }
  25901. if (this._defines.VERTEXCOLOR) {
  25902. attribs.push(BABYLON.VertexBuffer.ColorKind);
  25903. }
  25904. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  25905. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  25906. var shaderName = "default";
  25907. var join = this._defines.toString();
  25908. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  25909. "vFogInfos", "vFogColor", "pointSize",
  25910. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  25911. "mBones",
  25912. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  25913. "depthValues",
  25914. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  25915. "logarithmicDepthConstant"
  25916. ];
  25917. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  25918. if (this._defines.CAMERACOLORCURVES) {
  25919. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  25920. }
  25921. if (this._defines.CAMERACOLORGRADING) {
  25922. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  25923. }
  25924. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  25925. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  25926. }
  25927. if (!this._effect.isReady()) {
  25928. return false;
  25929. }
  25930. this._renderId = scene.getRenderId();
  25931. this._wasPreviouslyReady = true;
  25932. if (mesh) {
  25933. if (!mesh._materialDefines) {
  25934. mesh._materialDefines = new StandardMaterialDefines();
  25935. }
  25936. this._defines.cloneTo(mesh._materialDefines);
  25937. }
  25938. return true;
  25939. };
  25940. StandardMaterial.prototype.unbind = function () {
  25941. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  25942. this._effect.setTexture("reflection2DSampler", null);
  25943. }
  25944. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  25945. this._effect.setTexture("refraction2DSampler", null);
  25946. }
  25947. _super.prototype.unbind.call(this);
  25948. };
  25949. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25950. this._effect.setMatrix("world", world);
  25951. };
  25952. StandardMaterial.prototype.bind = function (world, mesh) {
  25953. var scene = this.getScene();
  25954. // Matrices
  25955. this.bindOnlyWorldMatrix(world);
  25956. // Bones
  25957. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  25958. if (scene.getCachedMaterial() !== this) {
  25959. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25960. if (StandardMaterial.FresnelEnabled) {
  25961. // Fresnel
  25962. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25963. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  25964. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  25965. }
  25966. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25967. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  25968. }
  25969. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25970. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  25971. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  25972. }
  25973. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25974. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  25975. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  25976. }
  25977. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25978. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  25979. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  25980. }
  25981. }
  25982. // Textures
  25983. if (scene.texturesEnabled) {
  25984. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25985. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  25986. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  25987. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  25988. }
  25989. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25990. this._effect.setTexture("ambientSampler", this.ambientTexture);
  25991. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  25992. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  25993. }
  25994. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25995. this._effect.setTexture("opacitySampler", this.opacityTexture);
  25996. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  25997. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  25998. }
  25999. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26000. if (this.reflectionTexture.isCube) {
  26001. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26002. }
  26003. else {
  26004. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26005. }
  26006. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26007. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26008. }
  26009. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26010. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26011. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26012. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26013. }
  26014. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26015. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26016. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26017. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26018. }
  26019. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26020. this._effect.setTexture("specularSampler", this.specularTexture);
  26021. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26022. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26023. }
  26024. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26025. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26026. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26027. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26028. }
  26029. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26030. var depth = 1.0;
  26031. if (this.refractionTexture.isCube) {
  26032. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26033. }
  26034. else {
  26035. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26036. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26037. if (this.refractionTexture.depth) {
  26038. depth = this.refractionTexture.depth;
  26039. }
  26040. }
  26041. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26042. }
  26043. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26044. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26045. }
  26046. }
  26047. // Clip plane
  26048. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26049. // Point size
  26050. if (this.pointsCloud) {
  26051. this._effect.setFloat("pointSize", this.pointSize);
  26052. }
  26053. // Colors
  26054. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26055. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26056. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26057. if (this._defines.SPECULARTERM) {
  26058. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26059. }
  26060. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26061. }
  26062. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26063. // Diffuse
  26064. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26065. // Lights
  26066. if (scene.lightsEnabled && !this.disableLighting) {
  26067. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26068. }
  26069. // View
  26070. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26071. this._effect.setMatrix("view", scene.getViewMatrix());
  26072. }
  26073. // Fog
  26074. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26075. // Log. depth
  26076. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26077. // Color Curves
  26078. if (this.cameraColorCurves) {
  26079. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26080. }
  26081. }
  26082. _super.prototype.bind.call(this, world, mesh);
  26083. };
  26084. StandardMaterial.prototype.getAnimatables = function () {
  26085. var results = [];
  26086. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26087. results.push(this.diffuseTexture);
  26088. }
  26089. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26090. results.push(this.ambientTexture);
  26091. }
  26092. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26093. results.push(this.opacityTexture);
  26094. }
  26095. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26096. results.push(this.reflectionTexture);
  26097. }
  26098. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26099. results.push(this.emissiveTexture);
  26100. }
  26101. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26102. results.push(this.specularTexture);
  26103. }
  26104. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26105. results.push(this.bumpTexture);
  26106. }
  26107. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26108. results.push(this.lightmapTexture);
  26109. }
  26110. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26111. results.push(this.refractionTexture);
  26112. }
  26113. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26114. results.push(this.cameraColorGradingTexture);
  26115. }
  26116. return results;
  26117. };
  26118. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26119. if (forceDisposeTextures) {
  26120. if (this.diffuseTexture) {
  26121. this.diffuseTexture.dispose();
  26122. }
  26123. if (this.ambientTexture) {
  26124. this.ambientTexture.dispose();
  26125. }
  26126. if (this.opacityTexture) {
  26127. this.opacityTexture.dispose();
  26128. }
  26129. if (this.reflectionTexture) {
  26130. this.reflectionTexture.dispose();
  26131. }
  26132. if (this.emissiveTexture) {
  26133. this.emissiveTexture.dispose();
  26134. }
  26135. if (this.specularTexture) {
  26136. this.specularTexture.dispose();
  26137. }
  26138. if (this.bumpTexture) {
  26139. this.bumpTexture.dispose();
  26140. }
  26141. if (this.lightmapTexture) {
  26142. this.lightmapTexture.dispose();
  26143. }
  26144. if (this.refractionTexture) {
  26145. this.refractionTexture.dispose();
  26146. }
  26147. if (this.cameraColorGradingTexture) {
  26148. this.cameraColorGradingTexture.dispose();
  26149. }
  26150. }
  26151. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  26152. };
  26153. StandardMaterial.prototype.clone = function (name) {
  26154. var _this = this;
  26155. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  26156. };
  26157. StandardMaterial.prototype.serialize = function () {
  26158. return BABYLON.SerializationHelper.Serialize(this);
  26159. };
  26160. // Statics
  26161. StandardMaterial.Parse = function (source, scene, rootUrl) {
  26162. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  26163. };
  26164. // Flags used to enable or disable a type of texture for all Standard Materials
  26165. StandardMaterial.DiffuseTextureEnabled = true;
  26166. StandardMaterial.AmbientTextureEnabled = true;
  26167. StandardMaterial.OpacityTextureEnabled = true;
  26168. StandardMaterial.ReflectionTextureEnabled = true;
  26169. StandardMaterial.EmissiveTextureEnabled = true;
  26170. StandardMaterial.SpecularTextureEnabled = true;
  26171. StandardMaterial.BumpTextureEnabled = true;
  26172. StandardMaterial.FresnelEnabled = true;
  26173. StandardMaterial.LightmapTextureEnabled = true;
  26174. StandardMaterial.RefractionTextureEnabled = true;
  26175. StandardMaterial.ColorGradingTextureEnabled = true;
  26176. __decorate([
  26177. BABYLON.serializeAsTexture()
  26178. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  26179. __decorate([
  26180. BABYLON.serializeAsTexture()
  26181. ], StandardMaterial.prototype, "ambientTexture", void 0);
  26182. __decorate([
  26183. BABYLON.serializeAsTexture()
  26184. ], StandardMaterial.prototype, "opacityTexture", void 0);
  26185. __decorate([
  26186. BABYLON.serializeAsTexture()
  26187. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  26188. __decorate([
  26189. BABYLON.serializeAsTexture()
  26190. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  26191. __decorate([
  26192. BABYLON.serializeAsTexture()
  26193. ], StandardMaterial.prototype, "specularTexture", void 0);
  26194. __decorate([
  26195. BABYLON.serializeAsTexture()
  26196. ], StandardMaterial.prototype, "bumpTexture", void 0);
  26197. __decorate([
  26198. BABYLON.serializeAsTexture()
  26199. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  26200. __decorate([
  26201. BABYLON.serializeAsTexture()
  26202. ], StandardMaterial.prototype, "refractionTexture", void 0);
  26203. __decorate([
  26204. BABYLON.serializeAsColor3("ambient")
  26205. ], StandardMaterial.prototype, "ambientColor", void 0);
  26206. __decorate([
  26207. BABYLON.serializeAsColor3("diffuse")
  26208. ], StandardMaterial.prototype, "diffuseColor", void 0);
  26209. __decorate([
  26210. BABYLON.serializeAsColor3("specular")
  26211. ], StandardMaterial.prototype, "specularColor", void 0);
  26212. __decorate([
  26213. BABYLON.serializeAsColor3("emissive")
  26214. ], StandardMaterial.prototype, "emissiveColor", void 0);
  26215. __decorate([
  26216. BABYLON.serialize()
  26217. ], StandardMaterial.prototype, "specularPower", void 0);
  26218. __decorate([
  26219. BABYLON.serialize()
  26220. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  26221. __decorate([
  26222. BABYLON.serialize()
  26223. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  26224. __decorate([
  26225. BABYLON.serialize()
  26226. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  26227. __decorate([
  26228. BABYLON.serialize()
  26229. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  26230. __decorate([
  26231. BABYLON.serialize()
  26232. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  26233. __decorate([
  26234. BABYLON.serialize()
  26235. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  26236. __decorate([
  26237. BABYLON.serialize()
  26238. ], StandardMaterial.prototype, "disableLighting", void 0);
  26239. __decorate([
  26240. BABYLON.serialize()
  26241. ], StandardMaterial.prototype, "useParallax", void 0);
  26242. __decorate([
  26243. BABYLON.serialize()
  26244. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  26245. __decorate([
  26246. BABYLON.serialize()
  26247. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  26248. __decorate([
  26249. BABYLON.serialize()
  26250. ], StandardMaterial.prototype, "roughness", void 0);
  26251. __decorate([
  26252. BABYLON.serialize()
  26253. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  26254. __decorate([
  26255. BABYLON.serialize()
  26256. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  26257. __decorate([
  26258. BABYLON.serialize()
  26259. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  26260. __decorate([
  26261. BABYLON.serializeAsFresnelParameters()
  26262. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  26263. __decorate([
  26264. BABYLON.serializeAsFresnelParameters()
  26265. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  26266. __decorate([
  26267. BABYLON.serializeAsFresnelParameters()
  26268. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  26269. __decorate([
  26270. BABYLON.serializeAsFresnelParameters()
  26271. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  26272. __decorate([
  26273. BABYLON.serializeAsFresnelParameters()
  26274. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  26275. __decorate([
  26276. BABYLON.serialize()
  26277. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  26278. __decorate([
  26279. BABYLON.serialize()
  26280. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  26281. __decorate([
  26282. BABYLON.serialize()
  26283. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  26284. __decorate([
  26285. BABYLON.serialize()
  26286. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  26287. __decorate([
  26288. BABYLON.serializeAsTexture()
  26289. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  26290. __decorate([
  26291. BABYLON.serializeAsColorCurves()
  26292. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  26293. __decorate([
  26294. BABYLON.serialize()
  26295. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  26296. return StandardMaterial;
  26297. }(BABYLON.Material));
  26298. BABYLON.StandardMaterial = StandardMaterial;
  26299. })(BABYLON || (BABYLON = {}));
  26300. var BABYLON;
  26301. (function (BABYLON) {
  26302. var MultiMaterial = (function (_super) {
  26303. __extends(MultiMaterial, _super);
  26304. function MultiMaterial(name, scene) {
  26305. _super.call(this, name, scene, true);
  26306. this.subMaterials = new Array();
  26307. scene.multiMaterials.push(this);
  26308. }
  26309. // Properties
  26310. MultiMaterial.prototype.getSubMaterial = function (index) {
  26311. if (index < 0 || index >= this.subMaterials.length) {
  26312. return this.getScene().defaultMaterial;
  26313. }
  26314. return this.subMaterials[index];
  26315. };
  26316. // Methods
  26317. MultiMaterial.prototype.isReady = function (mesh) {
  26318. for (var index = 0; index < this.subMaterials.length; index++) {
  26319. var subMaterial = this.subMaterials[index];
  26320. if (subMaterial) {
  26321. if (!this.subMaterials[index].isReady(mesh)) {
  26322. return false;
  26323. }
  26324. }
  26325. }
  26326. return true;
  26327. };
  26328. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  26329. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  26330. for (var index = 0; index < this.subMaterials.length; index++) {
  26331. var subMaterial = null;
  26332. if (cloneChildren) {
  26333. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  26334. }
  26335. else {
  26336. subMaterial = this.subMaterials[index];
  26337. }
  26338. newMultiMaterial.subMaterials.push(subMaterial);
  26339. }
  26340. return newMultiMaterial;
  26341. };
  26342. MultiMaterial.prototype.serialize = function () {
  26343. var serializationObject = {};
  26344. serializationObject.name = this.name;
  26345. serializationObject.id = this.id;
  26346. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26347. serializationObject.materials = [];
  26348. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  26349. var subMat = this.subMaterials[matIndex];
  26350. if (subMat) {
  26351. serializationObject.materials.push(subMat.id);
  26352. }
  26353. else {
  26354. serializationObject.materials.push(null);
  26355. }
  26356. }
  26357. return serializationObject;
  26358. };
  26359. return MultiMaterial;
  26360. }(BABYLON.Material));
  26361. BABYLON.MultiMaterial = MultiMaterial;
  26362. })(BABYLON || (BABYLON = {}));
  26363. var BABYLON;
  26364. (function (BABYLON) {
  26365. var SceneLoader = (function () {
  26366. function SceneLoader() {
  26367. }
  26368. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  26369. get: function () {
  26370. return 0;
  26371. },
  26372. enumerable: true,
  26373. configurable: true
  26374. });
  26375. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  26376. get: function () {
  26377. return 1;
  26378. },
  26379. enumerable: true,
  26380. configurable: true
  26381. });
  26382. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  26383. get: function () {
  26384. return 2;
  26385. },
  26386. enumerable: true,
  26387. configurable: true
  26388. });
  26389. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  26390. get: function () {
  26391. return 3;
  26392. },
  26393. enumerable: true,
  26394. configurable: true
  26395. });
  26396. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  26397. get: function () {
  26398. return SceneLoader._ForceFullSceneLoadingForIncremental;
  26399. },
  26400. set: function (value) {
  26401. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  26402. },
  26403. enumerable: true,
  26404. configurable: true
  26405. });
  26406. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  26407. get: function () {
  26408. return SceneLoader._ShowLoadingScreen;
  26409. },
  26410. set: function (value) {
  26411. SceneLoader._ShowLoadingScreen = value;
  26412. },
  26413. enumerable: true,
  26414. configurable: true
  26415. });
  26416. Object.defineProperty(SceneLoader, "loggingLevel", {
  26417. get: function () {
  26418. return SceneLoader._loggingLevel;
  26419. },
  26420. set: function (value) {
  26421. SceneLoader._loggingLevel = value;
  26422. },
  26423. enumerable: true,
  26424. configurable: true
  26425. });
  26426. SceneLoader._getDefaultPlugin = function () {
  26427. return SceneLoader._registeredPlugins[".babylon"];
  26428. };
  26429. SceneLoader._getPluginForExtension = function (extension) {
  26430. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  26431. if (registeredPlugin) {
  26432. return registeredPlugin;
  26433. }
  26434. return SceneLoader._getDefaultPlugin();
  26435. };
  26436. SceneLoader._getPluginForFilename = function (sceneFilename) {
  26437. if (sceneFilename.name) {
  26438. sceneFilename = sceneFilename.name;
  26439. }
  26440. var dotPosition = sceneFilename.lastIndexOf(".");
  26441. var queryStringPosition = sceneFilename.indexOf("?");
  26442. if (queryStringPosition === -1) {
  26443. queryStringPosition = sceneFilename.length;
  26444. }
  26445. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  26446. return SceneLoader._getPluginForExtension(extension);
  26447. };
  26448. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  26449. SceneLoader._getDirectLoad = function (sceneFilename) {
  26450. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26451. return sceneFilename.substr(5);
  26452. }
  26453. return null;
  26454. };
  26455. // Public functions
  26456. SceneLoader.GetPluginForExtension = function (extension) {
  26457. return SceneLoader._getPluginForExtension(extension).plugin;
  26458. };
  26459. SceneLoader.RegisterPlugin = function (plugin) {
  26460. if (typeof plugin.extensions === "string") {
  26461. var extension = plugin.extensions;
  26462. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26463. plugin: plugin,
  26464. isBinary: false
  26465. };
  26466. }
  26467. else {
  26468. var extensions = plugin.extensions;
  26469. Object.keys(extensions).forEach(function (extension) {
  26470. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26471. plugin: plugin,
  26472. isBinary: extensions[extension].isBinary
  26473. };
  26474. });
  26475. }
  26476. };
  26477. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26478. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26479. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26480. return;
  26481. }
  26482. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26483. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26484. return;
  26485. }
  26486. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26487. var loadingToken = {};
  26488. scene._addPendingData(loadingToken);
  26489. var manifestChecked = function (success) {
  26490. scene.database = database;
  26491. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26492. var plugin = registeredPlugin.plugin;
  26493. var useArrayBuffer = registeredPlugin.isBinary;
  26494. var importMeshFromData = function (data) {
  26495. var meshes = [];
  26496. var particleSystems = [];
  26497. var skeletons = [];
  26498. try {
  26499. if (plugin.importMesh) {
  26500. var syncedPlugin = plugin;
  26501. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  26502. if (onerror) {
  26503. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26504. }
  26505. scene._removePendingData(loadingToken);
  26506. return;
  26507. }
  26508. if (onsuccess) {
  26509. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26510. onsuccess(meshes, particleSystems, skeletons);
  26511. scene._removePendingData(loadingToken);
  26512. }
  26513. }
  26514. else {
  26515. var asyncedPlugin = plugin;
  26516. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  26517. if (onsuccess) {
  26518. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26519. onsuccess(meshes, particleSystems, skeletons);
  26520. scene._removePendingData(loadingToken);
  26521. }
  26522. }, function () {
  26523. if (onerror) {
  26524. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26525. }
  26526. scene._removePendingData(loadingToken);
  26527. });
  26528. }
  26529. }
  26530. catch (e) {
  26531. if (onerror) {
  26532. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  26533. }
  26534. scene._removePendingData(loadingToken);
  26535. }
  26536. };
  26537. if (directLoad) {
  26538. importMeshFromData(directLoad);
  26539. return;
  26540. }
  26541. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  26542. importMeshFromData(data);
  26543. }, progressCallBack, database, useArrayBuffer);
  26544. };
  26545. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  26546. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26547. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26548. }
  26549. else {
  26550. // If the scene is a data stream or offline support is not enabled, it's a direct load
  26551. manifestChecked(true);
  26552. }
  26553. };
  26554. /**
  26555. * Load a scene
  26556. * @param rootUrl a string that defines the root url for scene and resources
  26557. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26558. * @param engine is the instance of BABYLON.Engine to use to create the scene
  26559. */
  26560. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  26561. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  26562. };
  26563. /**
  26564. * Append a scene
  26565. * @param rootUrl a string that defines the root url for scene and resources
  26566. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26567. * @param scene is the instance of BABYLON.Scene to append to
  26568. */
  26569. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26570. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26571. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26572. return;
  26573. }
  26574. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26575. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26576. var plugin = registeredPlugin.plugin;
  26577. var useArrayBuffer = registeredPlugin.isBinary;
  26578. var database;
  26579. var loadingToken = {};
  26580. scene._addPendingData(loadingToken);
  26581. if (SceneLoader.ShowLoadingScreen) {
  26582. scene.getEngine().displayLoadingUI();
  26583. }
  26584. var loadSceneFromData = function (data) {
  26585. scene.database = database;
  26586. if (plugin.load) {
  26587. var syncedPlugin = plugin;
  26588. if (!syncedPlugin.load(scene, data, rootUrl)) {
  26589. if (onerror) {
  26590. onerror(scene);
  26591. }
  26592. scene._removePendingData(loadingToken);
  26593. scene.getEngine().hideLoadingUI();
  26594. return;
  26595. }
  26596. if (onsuccess) {
  26597. onsuccess(scene);
  26598. }
  26599. scene._removePendingData(loadingToken);
  26600. }
  26601. else {
  26602. var asyncedPlugin = plugin;
  26603. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26604. if (onsuccess) {
  26605. onsuccess(scene);
  26606. }
  26607. scene._removePendingData(loadingToken);
  26608. }, function () {
  26609. if (onerror) {
  26610. onerror(scene);
  26611. }
  26612. scene._removePendingData(loadingToken);
  26613. scene.getEngine().hideLoadingUI();
  26614. });
  26615. }
  26616. if (SceneLoader.ShowLoadingScreen) {
  26617. scene.executeWhenReady(function () {
  26618. scene.getEngine().hideLoadingUI();
  26619. });
  26620. }
  26621. };
  26622. var manifestChecked = function (success) {
  26623. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  26624. };
  26625. if (directLoad) {
  26626. loadSceneFromData(directLoad);
  26627. return;
  26628. }
  26629. if (rootUrl.indexOf("file:") === -1) {
  26630. if (scene.getEngine().enableOfflineSupport) {
  26631. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26632. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26633. }
  26634. else {
  26635. manifestChecked(true);
  26636. }
  26637. }
  26638. else {
  26639. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  26640. }
  26641. };
  26642. // Flags
  26643. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26644. SceneLoader._ShowLoadingScreen = true;
  26645. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26646. // Members
  26647. SceneLoader._registeredPlugins = {};
  26648. return SceneLoader;
  26649. }());
  26650. BABYLON.SceneLoader = SceneLoader;
  26651. ;
  26652. })(BABYLON || (BABYLON = {}));
  26653. var BABYLON;
  26654. (function (BABYLON) {
  26655. var Internals;
  26656. (function (Internals) {
  26657. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26658. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26659. var parsedMaterial = parsedData.materials[index];
  26660. if (parsedMaterial.id === id) {
  26661. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26662. }
  26663. }
  26664. return null;
  26665. };
  26666. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26667. names = (names instanceof Array) ? names : [names];
  26668. for (var i in names) {
  26669. if (mesh.name === names[i]) {
  26670. hierarchyIds.push(mesh.id);
  26671. return true;
  26672. }
  26673. }
  26674. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26675. hierarchyIds.push(mesh.id);
  26676. return true;
  26677. }
  26678. return false;
  26679. };
  26680. var logOperation = function (operation, producer) {
  26681. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26682. };
  26683. BABYLON.SceneLoader.RegisterPlugin({
  26684. extensions: ".babylon",
  26685. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26686. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26687. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26688. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26689. // and avoid problems with multiple concurrent .babylon loads.
  26690. var log = "importMesh has failed JSON parse";
  26691. try {
  26692. var parsedData = JSON.parse(data);
  26693. log = "";
  26694. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26695. var loadedSkeletonsIds = [];
  26696. var loadedMaterialsIds = [];
  26697. var hierarchyIds = [];
  26698. var index;
  26699. var cache;
  26700. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26701. var parsedMesh = parsedData.meshes[index];
  26702. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26703. if (meshesNames instanceof Array) {
  26704. // Remove found mesh name from list.
  26705. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26706. }
  26707. //Geometry?
  26708. if (parsedMesh.geometryId) {
  26709. //does the file contain geometries?
  26710. if (parsedData.geometries) {
  26711. //find the correct geometry and add it to the scene
  26712. var found = false;
  26713. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  26714. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  26715. return;
  26716. }
  26717. else {
  26718. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  26719. if (parsedGeometryData.id === parsedMesh.geometryId) {
  26720. switch (geometryType) {
  26721. case "boxes":
  26722. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  26723. break;
  26724. case "spheres":
  26725. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  26726. break;
  26727. case "cylinders":
  26728. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  26729. break;
  26730. case "toruses":
  26731. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26732. break;
  26733. case "grounds":
  26734. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26735. break;
  26736. case "planes":
  26737. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26738. break;
  26739. case "torusKnots":
  26740. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26741. break;
  26742. case "vertexData":
  26743. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26744. break;
  26745. }
  26746. found = true;
  26747. }
  26748. });
  26749. }
  26750. });
  26751. if (!found) {
  26752. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26753. }
  26754. }
  26755. }
  26756. // Material ?
  26757. if (parsedMesh.materialId) {
  26758. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26759. if (!materialFound && parsedData.multiMaterials) {
  26760. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26761. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26762. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26763. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26764. var subMatId = parsedMultiMaterial.materials[matIndex];
  26765. loadedMaterialsIds.push(subMatId);
  26766. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26767. log += "\n\tMaterial " + mat.toString(fullDetails);
  26768. }
  26769. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26770. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26771. materialFound = true;
  26772. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26773. break;
  26774. }
  26775. }
  26776. }
  26777. if (!materialFound) {
  26778. loadedMaterialsIds.push(parsedMesh.materialId);
  26779. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26780. if (!mat) {
  26781. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26782. }
  26783. else {
  26784. log += "\n\tMaterial " + mat.toString(fullDetails);
  26785. }
  26786. }
  26787. }
  26788. // Skeleton ?
  26789. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  26790. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  26791. if (!skeletonAlreadyLoaded) {
  26792. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  26793. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  26794. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  26795. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26796. skeletons.push(skeleton);
  26797. loadedSkeletonsIds.push(parsedSkeleton.id);
  26798. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  26799. }
  26800. }
  26801. }
  26802. }
  26803. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26804. meshes.push(mesh);
  26805. log += "\n\tMesh " + mesh.toString(fullDetails);
  26806. }
  26807. }
  26808. // Connecting parents
  26809. var currentMesh;
  26810. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26811. currentMesh = scene.meshes[index];
  26812. if (currentMesh._waitingParentId) {
  26813. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  26814. currentMesh._waitingParentId = undefined;
  26815. }
  26816. }
  26817. // freeze and compute world matrix application
  26818. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26819. currentMesh = scene.meshes[index];
  26820. if (currentMesh._waitingFreezeWorldMatrix) {
  26821. currentMesh.freezeWorldMatrix();
  26822. currentMesh._waitingFreezeWorldMatrix = undefined;
  26823. }
  26824. else {
  26825. currentMesh.computeWorldMatrix(true);
  26826. }
  26827. }
  26828. // Particles
  26829. if (parsedData.particleSystems) {
  26830. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26831. var parsedParticleSystem = parsedData.particleSystems[index];
  26832. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  26833. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  26834. }
  26835. }
  26836. }
  26837. return true;
  26838. }
  26839. catch (err) {
  26840. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  26841. log = null;
  26842. throw err;
  26843. }
  26844. finally {
  26845. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26846. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26847. }
  26848. }
  26849. },
  26850. load: function (scene, data, rootUrl) {
  26851. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26852. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26853. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26854. // and avoid problems with multiple concurrent .babylon loads.
  26855. var log = "importScene has failed JSON parse";
  26856. try {
  26857. var parsedData = JSON.parse(data);
  26858. log = "";
  26859. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26860. // Scene
  26861. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  26862. scene.autoClear = parsedData.autoClear;
  26863. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  26864. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  26865. if (parsedData.gravity) {
  26866. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  26867. }
  26868. // Fog
  26869. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  26870. scene.fogMode = parsedData.fogMode;
  26871. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  26872. scene.fogStart = parsedData.fogStart;
  26873. scene.fogEnd = parsedData.fogEnd;
  26874. scene.fogDensity = parsedData.fogDensity;
  26875. log += "\tFog mode for scene: ";
  26876. switch (scene.fogMode) {
  26877. // getters not compiling, so using hardcoded
  26878. case 1:
  26879. log += "exp\n";
  26880. break;
  26881. case 2:
  26882. log += "exp2\n";
  26883. break;
  26884. case 3:
  26885. log += "linear\n";
  26886. break;
  26887. }
  26888. }
  26889. //Physics
  26890. if (parsedData.physicsEnabled) {
  26891. var physicsPlugin;
  26892. if (parsedData.physicsEngine === "cannon") {
  26893. physicsPlugin = new BABYLON.CannonJSPlugin();
  26894. }
  26895. else if (parsedData.physicsEngine === "oimo") {
  26896. physicsPlugin = new BABYLON.OimoJSPlugin();
  26897. }
  26898. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  26899. //else - default engine, which is currently oimo
  26900. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  26901. scene.enablePhysics(physicsGravity, physicsPlugin);
  26902. }
  26903. //collisions, if defined. otherwise, default is true
  26904. if (parsedData.collisionsEnabled != undefined) {
  26905. scene.collisionsEnabled = parsedData.collisionsEnabled;
  26906. }
  26907. scene.workerCollisions = !!parsedData.workerCollisions;
  26908. var index;
  26909. var cache;
  26910. // Lights
  26911. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  26912. var parsedLight = parsedData.lights[index];
  26913. var light = BABYLON.Light.Parse(parsedLight, scene);
  26914. log += (index === 0 ? "\n\tLights:" : "");
  26915. log += "\n\t\t" + light.toString(fullDetails);
  26916. }
  26917. // Animations
  26918. if (parsedData.animations) {
  26919. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  26920. var parsedAnimation = parsedData.animations[index];
  26921. var animation = BABYLON.Animation.Parse(parsedAnimation);
  26922. scene.animations.push(animation);
  26923. log += (index === 0 ? "\n\tAnimations:" : "");
  26924. log += "\n\t\t" + animation.toString(fullDetails);
  26925. }
  26926. }
  26927. if (parsedData.autoAnimate) {
  26928. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  26929. }
  26930. // Materials
  26931. if (parsedData.materials) {
  26932. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26933. var parsedMaterial = parsedData.materials[index];
  26934. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26935. log += (index === 0 ? "\n\tMaterials:" : "");
  26936. log += "\n\t\t" + mat.toString(fullDetails);
  26937. }
  26938. }
  26939. if (parsedData.multiMaterials) {
  26940. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  26941. var parsedMultiMaterial = parsedData.multiMaterials[index];
  26942. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26943. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  26944. log += "\n\t\t" + mmat.toString(fullDetails);
  26945. }
  26946. }
  26947. // Skeletons
  26948. if (parsedData.skeletons) {
  26949. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  26950. var parsedSkeleton = parsedData.skeletons[index];
  26951. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26952. log += (index === 0 ? "\n\tSkeletons:" : "");
  26953. log += "\n\t\t" + skeleton.toString(fullDetails);
  26954. }
  26955. }
  26956. // Geometries
  26957. var geometries = parsedData.geometries;
  26958. if (geometries) {
  26959. // Boxes
  26960. var boxes = geometries.boxes;
  26961. if (boxes) {
  26962. for (index = 0, cache = boxes.length; index < cache; index++) {
  26963. var parsedBox = boxes[index];
  26964. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  26965. }
  26966. }
  26967. // Spheres
  26968. var spheres = geometries.spheres;
  26969. if (spheres) {
  26970. for (index = 0, cache = spheres.length; index < cache; index++) {
  26971. var parsedSphere = spheres[index];
  26972. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  26973. }
  26974. }
  26975. // Cylinders
  26976. var cylinders = geometries.cylinders;
  26977. if (cylinders) {
  26978. for (index = 0, cache = cylinders.length; index < cache; index++) {
  26979. var parsedCylinder = cylinders[index];
  26980. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  26981. }
  26982. }
  26983. // Toruses
  26984. var toruses = geometries.toruses;
  26985. if (toruses) {
  26986. for (index = 0, cache = toruses.length; index < cache; index++) {
  26987. var parsedTorus = toruses[index];
  26988. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  26989. }
  26990. }
  26991. // Grounds
  26992. var grounds = geometries.grounds;
  26993. if (grounds) {
  26994. for (index = 0, cache = grounds.length; index < cache; index++) {
  26995. var parsedGround = grounds[index];
  26996. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  26997. }
  26998. }
  26999. // Planes
  27000. var planes = geometries.planes;
  27001. if (planes) {
  27002. for (index = 0, cache = planes.length; index < cache; index++) {
  27003. var parsedPlane = planes[index];
  27004. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27005. }
  27006. }
  27007. // TorusKnots
  27008. var torusKnots = geometries.torusKnots;
  27009. if (torusKnots) {
  27010. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27011. var parsedTorusKnot = torusKnots[index];
  27012. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27013. }
  27014. }
  27015. // VertexData
  27016. var vertexData = geometries.vertexData;
  27017. if (vertexData) {
  27018. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27019. var parsedVertexData = vertexData[index];
  27020. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27021. }
  27022. }
  27023. }
  27024. // Meshes
  27025. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27026. var parsedMesh = parsedData.meshes[index];
  27027. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27028. log += (index === 0 ? "\n\tMeshes:" : "");
  27029. log += "\n\t\t" + mesh.toString(fullDetails);
  27030. }
  27031. // Cameras
  27032. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27033. var parsedCamera = parsedData.cameras[index];
  27034. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27035. log += (index === 0 ? "\n\tCameras:" : "");
  27036. log += "\n\t\t" + camera.toString(fullDetails);
  27037. }
  27038. if (parsedData.activeCameraID) {
  27039. scene.setActiveCameraByID(parsedData.activeCameraID);
  27040. }
  27041. // Browsing all the graph to connect the dots
  27042. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27043. var camera = scene.cameras[index];
  27044. if (camera._waitingParentId) {
  27045. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27046. camera._waitingParentId = undefined;
  27047. }
  27048. }
  27049. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27050. var light = scene.lights[index];
  27051. if (light._waitingParentId) {
  27052. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27053. light._waitingParentId = undefined;
  27054. }
  27055. }
  27056. // Sounds
  27057. var loadedSounds = [];
  27058. var loadedSound;
  27059. if (BABYLON.AudioEngine && parsedData.sounds) {
  27060. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27061. var parsedSound = parsedData.sounds[index];
  27062. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27063. if (!parsedSound.url)
  27064. parsedSound.url = parsedSound.name;
  27065. if (!loadedSounds[parsedSound.url]) {
  27066. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27067. loadedSounds[parsedSound.url] = loadedSound;
  27068. }
  27069. else {
  27070. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27071. }
  27072. }
  27073. else {
  27074. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27075. }
  27076. }
  27077. }
  27078. loadedSounds = [];
  27079. // Connect parents & children and parse actions
  27080. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27081. var mesh = scene.meshes[index];
  27082. if (mesh._waitingParentId) {
  27083. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27084. mesh._waitingParentId = undefined;
  27085. }
  27086. if (mesh._waitingActions) {
  27087. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27088. mesh._waitingActions = undefined;
  27089. }
  27090. }
  27091. // freeze world matrix application
  27092. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27093. var currentMesh = scene.meshes[index];
  27094. if (currentMesh._waitingFreezeWorldMatrix) {
  27095. currentMesh.freezeWorldMatrix();
  27096. currentMesh._waitingFreezeWorldMatrix = undefined;
  27097. }
  27098. else {
  27099. currentMesh.computeWorldMatrix(true);
  27100. }
  27101. }
  27102. // Particles Systems
  27103. if (parsedData.particleSystems) {
  27104. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27105. var parsedParticleSystem = parsedData.particleSystems[index];
  27106. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27107. }
  27108. }
  27109. // Lens flares
  27110. if (parsedData.lensFlareSystems) {
  27111. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27112. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27113. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27114. }
  27115. }
  27116. // Shadows
  27117. if (parsedData.shadowGenerators) {
  27118. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27119. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27120. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27121. }
  27122. }
  27123. // Actions (scene)
  27124. if (parsedData.actions) {
  27125. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27126. }
  27127. // Finish
  27128. return true;
  27129. }
  27130. catch (err) {
  27131. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  27132. log = null;
  27133. throw err;
  27134. }
  27135. finally {
  27136. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27137. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27138. }
  27139. }
  27140. }
  27141. });
  27142. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27143. })(BABYLON || (BABYLON = {}));
  27144. var BABYLON;
  27145. (function (BABYLON) {
  27146. var SpriteManager = (function () {
  27147. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  27148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27149. this.name = name;
  27150. this.sprites = new Array();
  27151. this.renderingGroupId = 0;
  27152. this.layerMask = 0x0FFFFFFF;
  27153. this.fogEnabled = true;
  27154. this.isPickable = false;
  27155. /**
  27156. * An event triggered when the manager is disposed.
  27157. * @type {BABYLON.Observable}
  27158. */
  27159. this.onDisposeObservable = new BABYLON.Observable();
  27160. this._vertexBuffers = {};
  27161. this._capacity = capacity;
  27162. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  27163. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27164. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27165. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  27166. if (cellSize.width) {
  27167. this.cellWidth = cellSize.width;
  27168. this.cellHeight = cellSize.height;
  27169. }
  27170. else {
  27171. this.cellWidth = cellSize;
  27172. this.cellHeight = cellSize;
  27173. }
  27174. this._scene = scene;
  27175. this._scene.spriteManagers.push(this);
  27176. var indices = [];
  27177. var index = 0;
  27178. for (var count = 0; count < capacity; count++) {
  27179. indices.push(index);
  27180. indices.push(index + 1);
  27181. indices.push(index + 2);
  27182. indices.push(index);
  27183. indices.push(index + 2);
  27184. indices.push(index + 3);
  27185. index += 4;
  27186. }
  27187. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27188. // VBO
  27189. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  27190. this._vertexData = new Float32Array(capacity * 16 * 4);
  27191. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  27192. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  27193. var options = this._buffer.createVertexBuffer("options", 4, 4);
  27194. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  27195. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  27196. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27197. this._vertexBuffers["options"] = options;
  27198. this._vertexBuffers["cellInfo"] = cellInfo;
  27199. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27200. // Effects
  27201. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  27202. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  27203. }
  27204. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  27205. set: function (callback) {
  27206. if (this._onDisposeObserver) {
  27207. this.onDisposeObservable.remove(this._onDisposeObserver);
  27208. }
  27209. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27210. },
  27211. enumerable: true,
  27212. configurable: true
  27213. });
  27214. Object.defineProperty(SpriteManager.prototype, "texture", {
  27215. get: function () {
  27216. return this._spriteTexture;
  27217. },
  27218. set: function (value) {
  27219. this._spriteTexture = value;
  27220. },
  27221. enumerable: true,
  27222. configurable: true
  27223. });
  27224. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  27225. var arrayOffset = index * 16;
  27226. if (offsetX === 0)
  27227. offsetX = this._epsilon;
  27228. else if (offsetX === 1)
  27229. offsetX = 1 - this._epsilon;
  27230. if (offsetY === 0)
  27231. offsetY = this._epsilon;
  27232. else if (offsetY === 1)
  27233. offsetY = 1 - this._epsilon;
  27234. this._vertexData[arrayOffset] = sprite.position.x;
  27235. this._vertexData[arrayOffset + 1] = sprite.position.y;
  27236. this._vertexData[arrayOffset + 2] = sprite.position.z;
  27237. this._vertexData[arrayOffset + 3] = sprite.angle;
  27238. this._vertexData[arrayOffset + 4] = sprite.width;
  27239. this._vertexData[arrayOffset + 5] = sprite.height;
  27240. this._vertexData[arrayOffset + 6] = offsetX;
  27241. this._vertexData[arrayOffset + 7] = offsetY;
  27242. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  27243. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  27244. var offset = (sprite.cellIndex / rowSize) >> 0;
  27245. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  27246. this._vertexData[arrayOffset + 11] = offset;
  27247. // Color
  27248. this._vertexData[arrayOffset + 12] = sprite.color.r;
  27249. this._vertexData[arrayOffset + 13] = sprite.color.g;
  27250. this._vertexData[arrayOffset + 14] = sprite.color.b;
  27251. this._vertexData[arrayOffset + 15] = sprite.color.a;
  27252. };
  27253. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  27254. var count = Math.min(this._capacity, this.sprites.length);
  27255. var min = BABYLON.Vector3.Zero();
  27256. var max = BABYLON.Vector3.Zero();
  27257. var distance = Number.MAX_VALUE;
  27258. var currentSprite;
  27259. var cameraSpacePosition = BABYLON.Vector3.Zero();
  27260. var cameraView = camera.getViewMatrix();
  27261. for (var index = 0; index < count; index++) {
  27262. var sprite = this.sprites[index];
  27263. if (!sprite) {
  27264. continue;
  27265. }
  27266. if (predicate) {
  27267. if (!predicate(sprite)) {
  27268. continue;
  27269. }
  27270. }
  27271. else if (!sprite.isPickable) {
  27272. continue;
  27273. }
  27274. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  27275. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  27276. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  27277. if (ray.intersectsBoxMinMax(min, max)) {
  27278. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  27279. if (distance > currentDistance) {
  27280. distance = currentDistance;
  27281. currentSprite = sprite;
  27282. if (fastCheck) {
  27283. break;
  27284. }
  27285. }
  27286. }
  27287. }
  27288. if (currentSprite) {
  27289. var result = new BABYLON.PickingInfo();
  27290. result.hit = true;
  27291. result.pickedSprite = currentSprite;
  27292. result.distance = distance;
  27293. return result;
  27294. }
  27295. return null;
  27296. };
  27297. SpriteManager.prototype.render = function () {
  27298. // Check
  27299. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  27300. return;
  27301. var engine = this._scene.getEngine();
  27302. var baseSize = this._spriteTexture.getBaseSize();
  27303. // Sprites
  27304. var deltaTime = engine.getDeltaTime();
  27305. var max = Math.min(this._capacity, this.sprites.length);
  27306. var rowSize = baseSize.width / this.cellWidth;
  27307. var offset = 0;
  27308. for (var index = 0; index < max; index++) {
  27309. var sprite = this.sprites[index];
  27310. if (!sprite) {
  27311. continue;
  27312. }
  27313. sprite._animate(deltaTime);
  27314. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  27315. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  27316. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  27317. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  27318. }
  27319. this._buffer.update(this._vertexData);
  27320. // Render
  27321. var effect = this._effectBase;
  27322. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27323. effect = this._effectFog;
  27324. }
  27325. engine.enableEffect(effect);
  27326. var viewMatrix = this._scene.getViewMatrix();
  27327. effect.setTexture("diffuseSampler", this._spriteTexture);
  27328. effect.setMatrix("view", viewMatrix);
  27329. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27330. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  27331. // Fog
  27332. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27333. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  27334. effect.setColor3("vFogColor", this._scene.fogColor);
  27335. }
  27336. // VBOs
  27337. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27338. // Draw order
  27339. engine.setDepthFunctionToLessOrEqual();
  27340. effect.setBool("alphaTest", true);
  27341. engine.setColorWrite(false);
  27342. engine.draw(true, 0, max * 6);
  27343. engine.setColorWrite(true);
  27344. effect.setBool("alphaTest", false);
  27345. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27346. engine.draw(true, 0, max * 6);
  27347. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27348. };
  27349. SpriteManager.prototype.dispose = function () {
  27350. if (this._buffer) {
  27351. this._buffer.dispose();
  27352. this._buffer = null;
  27353. }
  27354. if (this._indexBuffer) {
  27355. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27356. this._indexBuffer = null;
  27357. }
  27358. if (this._spriteTexture) {
  27359. this._spriteTexture.dispose();
  27360. this._spriteTexture = null;
  27361. }
  27362. // Remove from scene
  27363. var index = this._scene.spriteManagers.indexOf(this);
  27364. this._scene.spriteManagers.splice(index, 1);
  27365. // Callback
  27366. this.onDisposeObservable.notifyObservers(this);
  27367. this.onDisposeObservable.clear();
  27368. };
  27369. return SpriteManager;
  27370. }());
  27371. BABYLON.SpriteManager = SpriteManager;
  27372. })(BABYLON || (BABYLON = {}));
  27373. var BABYLON;
  27374. (function (BABYLON) {
  27375. var Sprite = (function () {
  27376. function Sprite(name, manager) {
  27377. this.name = name;
  27378. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27379. this.width = 1.0;
  27380. this.height = 1.0;
  27381. this.angle = 0;
  27382. this.cellIndex = 0;
  27383. this.invertU = 0;
  27384. this.invertV = 0;
  27385. this.animations = new Array();
  27386. this.isPickable = false;
  27387. this._animationStarted = false;
  27388. this._loopAnimation = false;
  27389. this._fromIndex = 0;
  27390. this._toIndex = 0;
  27391. this._delay = 0;
  27392. this._direction = 1;
  27393. this._frameCount = 0;
  27394. this._time = 0;
  27395. this._manager = manager;
  27396. this._manager.sprites.push(this);
  27397. this.position = BABYLON.Vector3.Zero();
  27398. }
  27399. Object.defineProperty(Sprite.prototype, "size", {
  27400. get: function () {
  27401. return this.width;
  27402. },
  27403. set: function (value) {
  27404. this.width = value;
  27405. this.height = value;
  27406. },
  27407. enumerable: true,
  27408. configurable: true
  27409. });
  27410. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  27411. this._fromIndex = from;
  27412. this._toIndex = to;
  27413. this._loopAnimation = loop;
  27414. this._delay = delay;
  27415. this._animationStarted = true;
  27416. this._direction = from < to ? 1 : -1;
  27417. this.cellIndex = from;
  27418. this._time = 0;
  27419. this._onAnimationEnd = onAnimationEnd;
  27420. };
  27421. Sprite.prototype.stopAnimation = function () {
  27422. this._animationStarted = false;
  27423. };
  27424. Sprite.prototype._animate = function (deltaTime) {
  27425. if (!this._animationStarted)
  27426. return;
  27427. this._time += deltaTime;
  27428. if (this._time > this._delay) {
  27429. this._time = this._time % this._delay;
  27430. this.cellIndex += this._direction;
  27431. if (this.cellIndex === this._toIndex) {
  27432. if (this._loopAnimation) {
  27433. this.cellIndex = this._fromIndex;
  27434. }
  27435. else {
  27436. this._animationStarted = false;
  27437. if (this._onAnimationEnd) {
  27438. this._onAnimationEnd();
  27439. }
  27440. if (this.disposeWhenFinishedAnimating) {
  27441. this.dispose();
  27442. }
  27443. }
  27444. }
  27445. }
  27446. };
  27447. Sprite.prototype.dispose = function () {
  27448. for (var i = 0; i < this._manager.sprites.length; i++) {
  27449. if (this._manager.sprites[i] == this) {
  27450. this._manager.sprites.splice(i, 1);
  27451. }
  27452. }
  27453. };
  27454. return Sprite;
  27455. }());
  27456. BABYLON.Sprite = Sprite;
  27457. })(BABYLON || (BABYLON = {}));
  27458. var BABYLON;
  27459. (function (BABYLON) {
  27460. var Layer = (function () {
  27461. function Layer(name, imgUrl, scene, isBackground, color) {
  27462. this.name = name;
  27463. this.scale = new BABYLON.Vector2(1, 1);
  27464. this.offset = new BABYLON.Vector2(0, 0);
  27465. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  27466. this._vertexBuffers = {};
  27467. // Events
  27468. /**
  27469. * An event triggered when the layer is disposed.
  27470. * @type {BABYLON.Observable}
  27471. */
  27472. this.onDisposeObservable = new BABYLON.Observable();
  27473. /**
  27474. * An event triggered before rendering the scene
  27475. * @type {BABYLON.Observable}
  27476. */
  27477. this.onBeforeRenderObservable = new BABYLON.Observable();
  27478. /**
  27479. * An event triggered after rendering the scene
  27480. * @type {BABYLON.Observable}
  27481. */
  27482. this.onAfterRenderObservable = new BABYLON.Observable();
  27483. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  27484. this.isBackground = isBackground === undefined ? true : isBackground;
  27485. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  27486. this._scene = scene;
  27487. this._scene.layers.push(this);
  27488. var engine = scene.getEngine();
  27489. // VBO
  27490. var vertices = [];
  27491. vertices.push(1, 1);
  27492. vertices.push(-1, 1);
  27493. vertices.push(-1, -1);
  27494. vertices.push(1, -1);
  27495. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27496. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  27497. // Indices
  27498. var indices = [];
  27499. indices.push(0);
  27500. indices.push(1);
  27501. indices.push(2);
  27502. indices.push(0);
  27503. indices.push(2);
  27504. indices.push(3);
  27505. this._indexBuffer = engine.createIndexBuffer(indices);
  27506. // Effects
  27507. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  27508. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  27509. }
  27510. Object.defineProperty(Layer.prototype, "onDispose", {
  27511. set: function (callback) {
  27512. if (this._onDisposeObserver) {
  27513. this.onDisposeObservable.remove(this._onDisposeObserver);
  27514. }
  27515. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27516. },
  27517. enumerable: true,
  27518. configurable: true
  27519. });
  27520. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  27521. set: function (callback) {
  27522. if (this._onBeforeRenderObserver) {
  27523. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27524. }
  27525. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27526. },
  27527. enumerable: true,
  27528. configurable: true
  27529. });
  27530. Object.defineProperty(Layer.prototype, "onAfterRender", {
  27531. set: function (callback) {
  27532. if (this._onAfterRenderObserver) {
  27533. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27534. }
  27535. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27536. },
  27537. enumerable: true,
  27538. configurable: true
  27539. });
  27540. Layer.prototype.render = function () {
  27541. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  27542. // Check
  27543. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  27544. return;
  27545. var engine = this._scene.getEngine();
  27546. this.onBeforeRenderObservable.notifyObservers(this);
  27547. // Render
  27548. engine.enableEffect(currentEffect);
  27549. engine.setState(false);
  27550. // Texture
  27551. currentEffect.setTexture("textureSampler", this.texture);
  27552. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  27553. // Color
  27554. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  27555. // Scale / offset
  27556. currentEffect.setVector2("offset", this.offset);
  27557. currentEffect.setVector2("scale", this.scale);
  27558. // VBOs
  27559. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  27560. // Draw order
  27561. if (!this.alphaTest) {
  27562. engine.setAlphaMode(this.alphaBlendingMode);
  27563. engine.draw(true, 0, 6);
  27564. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27565. }
  27566. else {
  27567. engine.draw(true, 0, 6);
  27568. }
  27569. this.onAfterRenderObservable.notifyObservers(this);
  27570. };
  27571. Layer.prototype.dispose = function () {
  27572. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27573. if (vertexBuffer) {
  27574. vertexBuffer.dispose();
  27575. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27576. }
  27577. if (this._indexBuffer) {
  27578. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27579. this._indexBuffer = null;
  27580. }
  27581. if (this.texture) {
  27582. this.texture.dispose();
  27583. this.texture = null;
  27584. }
  27585. // Remove from scene
  27586. var index = this._scene.layers.indexOf(this);
  27587. this._scene.layers.splice(index, 1);
  27588. // Callback
  27589. this.onDisposeObservable.notifyObservers(this);
  27590. this.onDisposeObservable.clear();
  27591. this.onAfterRenderObservable.clear();
  27592. this.onBeforeRenderObservable.clear();
  27593. };
  27594. return Layer;
  27595. }());
  27596. BABYLON.Layer = Layer;
  27597. })(BABYLON || (BABYLON = {}));
  27598. var BABYLON;
  27599. (function (BABYLON) {
  27600. var Particle = (function () {
  27601. function Particle() {
  27602. this.position = BABYLON.Vector3.Zero();
  27603. this.direction = BABYLON.Vector3.Zero();
  27604. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27605. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27606. this.lifeTime = 1.0;
  27607. this.age = 0;
  27608. this.size = 0;
  27609. this.angle = 0;
  27610. this.angularSpeed = 0;
  27611. }
  27612. Particle.prototype.copyTo = function (other) {
  27613. other.position.copyFrom(this.position);
  27614. other.direction.copyFrom(this.direction);
  27615. other.color.copyFrom(this.color);
  27616. other.colorStep.copyFrom(this.colorStep);
  27617. other.lifeTime = this.lifeTime;
  27618. other.age = this.age;
  27619. other.size = this.size;
  27620. other.angle = this.angle;
  27621. other.angularSpeed = this.angularSpeed;
  27622. };
  27623. return Particle;
  27624. }());
  27625. BABYLON.Particle = Particle;
  27626. })(BABYLON || (BABYLON = {}));
  27627. var BABYLON;
  27628. (function (BABYLON) {
  27629. var randomNumber = function (min, max) {
  27630. if (min === max) {
  27631. return (min);
  27632. }
  27633. var random = Math.random();
  27634. return ((random * (max - min)) + min);
  27635. };
  27636. var ParticleSystem = (function () {
  27637. function ParticleSystem(name, capacity, scene, customEffect) {
  27638. var _this = this;
  27639. this.name = name;
  27640. // Members
  27641. this.animations = [];
  27642. this.renderingGroupId = 0;
  27643. this.emitter = null;
  27644. this.emitRate = 10;
  27645. this.manualEmitCount = -1;
  27646. this.updateSpeed = 0.01;
  27647. this.targetStopDuration = 0;
  27648. this.disposeOnStop = false;
  27649. this.minEmitPower = 1;
  27650. this.maxEmitPower = 1;
  27651. this.minLifeTime = 1;
  27652. this.maxLifeTime = 1;
  27653. this.minSize = 1;
  27654. this.maxSize = 1;
  27655. this.minAngularSpeed = 0;
  27656. this.maxAngularSpeed = 0;
  27657. this.layerMask = 0x0FFFFFFF;
  27658. /**
  27659. * An event triggered when the system is disposed.
  27660. * @type {BABYLON.Observable}
  27661. */
  27662. this.onDisposeObservable = new BABYLON.Observable();
  27663. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27664. this.forceDepthWrite = false;
  27665. this.gravity = BABYLON.Vector3.Zero();
  27666. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27667. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27668. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27669. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27670. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27671. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27672. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27673. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27674. this.particles = new Array();
  27675. this._stockParticles = new Array();
  27676. this._newPartsExcess = 0;
  27677. this._vertexBuffers = {};
  27678. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27679. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27680. this._scaledDirection = BABYLON.Vector3.Zero();
  27681. this._scaledGravity = BABYLON.Vector3.Zero();
  27682. this._currentRenderId = -1;
  27683. this._started = false;
  27684. this._stopped = false;
  27685. this._actualFrame = 0;
  27686. this.id = name;
  27687. this._capacity = capacity;
  27688. this._scene = scene;
  27689. this._customEffect = customEffect;
  27690. scene.particleSystems.push(this);
  27691. var indices = [];
  27692. var index = 0;
  27693. for (var count = 0; count < capacity; count++) {
  27694. indices.push(index);
  27695. indices.push(index + 1);
  27696. indices.push(index + 2);
  27697. indices.push(index);
  27698. indices.push(index + 2);
  27699. indices.push(index + 3);
  27700. index += 4;
  27701. }
  27702. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27703. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  27704. this._vertexData = new Float32Array(capacity * 11 * 4);
  27705. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  27706. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  27707. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  27708. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  27709. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27710. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27711. this._vertexBuffers["options"] = options;
  27712. // Default behaviors
  27713. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  27714. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  27715. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  27716. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  27717. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  27718. };
  27719. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  27720. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  27721. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  27722. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  27723. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  27724. };
  27725. this.updateFunction = function (particles) {
  27726. for (var index = 0; index < particles.length; index++) {
  27727. var particle = particles[index];
  27728. particle.age += _this._scaledUpdateSpeed;
  27729. if (particle.age >= particle.lifeTime) {
  27730. _this.recycleParticle(particle);
  27731. index--;
  27732. continue;
  27733. }
  27734. else {
  27735. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27736. particle.color.addInPlace(_this._scaledColorStep);
  27737. if (particle.color.a < 0)
  27738. particle.color.a = 0;
  27739. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27740. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27741. particle.position.addInPlace(_this._scaledDirection);
  27742. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27743. particle.direction.addInPlace(_this._scaledGravity);
  27744. }
  27745. }
  27746. };
  27747. }
  27748. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27749. set: function (callback) {
  27750. if (this._onDisposeObserver) {
  27751. this.onDisposeObservable.remove(this._onDisposeObserver);
  27752. }
  27753. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27754. },
  27755. enumerable: true,
  27756. configurable: true
  27757. });
  27758. ParticleSystem.prototype.recycleParticle = function (particle) {
  27759. var lastParticle = this.particles.pop();
  27760. if (lastParticle !== particle) {
  27761. lastParticle.copyTo(particle);
  27762. this._stockParticles.push(lastParticle);
  27763. }
  27764. };
  27765. ParticleSystem.prototype.getCapacity = function () {
  27766. return this._capacity;
  27767. };
  27768. ParticleSystem.prototype.isAlive = function () {
  27769. return this._alive;
  27770. };
  27771. ParticleSystem.prototype.isStarted = function () {
  27772. return this._started;
  27773. };
  27774. ParticleSystem.prototype.start = function () {
  27775. this._started = true;
  27776. this._stopped = false;
  27777. this._actualFrame = 0;
  27778. };
  27779. ParticleSystem.prototype.stop = function () {
  27780. this._stopped = true;
  27781. };
  27782. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27783. var offset = index * 11;
  27784. this._vertexData[offset] = particle.position.x;
  27785. this._vertexData[offset + 1] = particle.position.y;
  27786. this._vertexData[offset + 2] = particle.position.z;
  27787. this._vertexData[offset + 3] = particle.color.r;
  27788. this._vertexData[offset + 4] = particle.color.g;
  27789. this._vertexData[offset + 5] = particle.color.b;
  27790. this._vertexData[offset + 6] = particle.color.a;
  27791. this._vertexData[offset + 7] = particle.angle;
  27792. this._vertexData[offset + 8] = particle.size;
  27793. this._vertexData[offset + 9] = offsetX;
  27794. this._vertexData[offset + 10] = offsetY;
  27795. };
  27796. ParticleSystem.prototype._update = function (newParticles) {
  27797. // Update current
  27798. this._alive = this.particles.length > 0;
  27799. this.updateFunction(this.particles);
  27800. // Add new ones
  27801. var worldMatrix;
  27802. if (this.emitter.position) {
  27803. worldMatrix = this.emitter.getWorldMatrix();
  27804. }
  27805. else {
  27806. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  27807. }
  27808. var particle;
  27809. for (var index = 0; index < newParticles; index++) {
  27810. if (this.particles.length === this._capacity) {
  27811. break;
  27812. }
  27813. if (this._stockParticles.length !== 0) {
  27814. particle = this._stockParticles.pop();
  27815. particle.age = 0;
  27816. }
  27817. else {
  27818. particle = new BABYLON.Particle();
  27819. }
  27820. this.particles.push(particle);
  27821. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  27822. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  27823. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  27824. particle.size = randomNumber(this.minSize, this.maxSize);
  27825. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  27826. this.startPositionFunction(worldMatrix, particle.position, particle);
  27827. var step = randomNumber(0, 1.0);
  27828. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  27829. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  27830. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  27831. }
  27832. };
  27833. ParticleSystem.prototype._getEffect = function () {
  27834. if (this._customEffect) {
  27835. return this._customEffect;
  27836. }
  27837. ;
  27838. var defines = [];
  27839. if (this._scene.clipPlane) {
  27840. defines.push("#define CLIPPLANE");
  27841. }
  27842. // Effect
  27843. var join = defines.join("\n");
  27844. if (this._cachedDefines !== join) {
  27845. this._cachedDefines = join;
  27846. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  27847. }
  27848. return this._effect;
  27849. };
  27850. ParticleSystem.prototype.animate = function () {
  27851. if (!this._started)
  27852. return;
  27853. var effect = this._getEffect();
  27854. // Check
  27855. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  27856. return;
  27857. if (this._currentRenderId === this._scene.getRenderId()) {
  27858. return;
  27859. }
  27860. this._currentRenderId = this._scene.getRenderId();
  27861. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  27862. // determine the number of particles we need to create
  27863. var newParticles;
  27864. if (this.manualEmitCount > -1) {
  27865. newParticles = this.manualEmitCount;
  27866. this._newPartsExcess = 0;
  27867. this.manualEmitCount = 0;
  27868. }
  27869. else {
  27870. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  27871. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  27872. }
  27873. if (this._newPartsExcess > 1.0) {
  27874. newParticles += this._newPartsExcess >> 0;
  27875. this._newPartsExcess -= this._newPartsExcess >> 0;
  27876. }
  27877. this._alive = false;
  27878. if (!this._stopped) {
  27879. this._actualFrame += this._scaledUpdateSpeed;
  27880. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  27881. this.stop();
  27882. }
  27883. else {
  27884. newParticles = 0;
  27885. }
  27886. this._update(newParticles);
  27887. // Stopped?
  27888. if (this._stopped) {
  27889. if (!this._alive) {
  27890. this._started = false;
  27891. if (this.disposeOnStop) {
  27892. this._scene._toBeDisposed.push(this);
  27893. }
  27894. }
  27895. }
  27896. // Update VBO
  27897. var offset = 0;
  27898. for (var index = 0; index < this.particles.length; index++) {
  27899. var particle = this.particles[index];
  27900. this._appendParticleVertex(offset++, particle, 0, 0);
  27901. this._appendParticleVertex(offset++, particle, 1, 0);
  27902. this._appendParticleVertex(offset++, particle, 1, 1);
  27903. this._appendParticleVertex(offset++, particle, 0, 1);
  27904. }
  27905. this._vertexBuffer.update(this._vertexData);
  27906. };
  27907. ParticleSystem.prototype.render = function () {
  27908. var effect = this._getEffect();
  27909. // Check
  27910. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  27911. return 0;
  27912. var engine = this._scene.getEngine();
  27913. // Render
  27914. engine.enableEffect(effect);
  27915. engine.setState(false);
  27916. var viewMatrix = this._scene.getViewMatrix();
  27917. effect.setTexture("diffuseSampler", this.particleTexture);
  27918. effect.setMatrix("view", viewMatrix);
  27919. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27920. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  27921. if (this._scene.clipPlane) {
  27922. var clipPlane = this._scene.clipPlane;
  27923. var invView = viewMatrix.clone();
  27924. invView.invert();
  27925. effect.setMatrix("invView", invView);
  27926. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27927. }
  27928. // VBOs
  27929. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27930. // Draw order
  27931. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  27932. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  27933. }
  27934. else {
  27935. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27936. }
  27937. if (this.forceDepthWrite) {
  27938. engine.setDepthWrite(true);
  27939. }
  27940. engine.draw(true, 0, this.particles.length * 6);
  27941. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27942. return this.particles.length;
  27943. };
  27944. ParticleSystem.prototype.dispose = function () {
  27945. if (this._vertexBuffer) {
  27946. this._vertexBuffer.dispose();
  27947. this._vertexBuffer = null;
  27948. }
  27949. if (this._indexBuffer) {
  27950. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27951. this._indexBuffer = null;
  27952. }
  27953. if (this.particleTexture) {
  27954. this.particleTexture.dispose();
  27955. this.particleTexture = null;
  27956. }
  27957. // Remove from scene
  27958. var index = this._scene.particleSystems.indexOf(this);
  27959. this._scene.particleSystems.splice(index, 1);
  27960. // Callback
  27961. this.onDisposeObservable.notifyObservers(this);
  27962. this.onDisposeObservable.clear();
  27963. };
  27964. // Clone
  27965. ParticleSystem.prototype.clone = function (name, newEmitter) {
  27966. var result = new ParticleSystem(name, this._capacity, this._scene);
  27967. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  27968. if (newEmitter === undefined) {
  27969. newEmitter = this.emitter;
  27970. }
  27971. result.emitter = newEmitter;
  27972. if (this.particleTexture) {
  27973. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  27974. }
  27975. result.start();
  27976. return result;
  27977. };
  27978. ParticleSystem.prototype.serialize = function () {
  27979. var serializationObject = {};
  27980. serializationObject.name = this.name;
  27981. serializationObject.id = this.id;
  27982. // Emitter
  27983. if (this.emitter.position) {
  27984. serializationObject.emitterId = this.emitter.id;
  27985. }
  27986. else {
  27987. serializationObject.emitter = this.emitter.asArray();
  27988. }
  27989. serializationObject.capacity = this.getCapacity();
  27990. if (this.particleTexture) {
  27991. serializationObject.textureName = this.particleTexture.name;
  27992. }
  27993. // Animations
  27994. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27995. // Particle system
  27996. serializationObject.minAngularSpeed = this.minAngularSpeed;
  27997. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  27998. serializationObject.minSize = this.minSize;
  27999. serializationObject.maxSize = this.maxSize;
  28000. serializationObject.minEmitPower = this.minEmitPower;
  28001. serializationObject.maxEmitPower = this.maxEmitPower;
  28002. serializationObject.minLifeTime = this.minLifeTime;
  28003. serializationObject.maxLifeTime = this.maxLifeTime;
  28004. serializationObject.emitRate = this.emitRate;
  28005. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28006. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28007. serializationObject.gravity = this.gravity.asArray();
  28008. serializationObject.direction1 = this.direction1.asArray();
  28009. serializationObject.direction2 = this.direction2.asArray();
  28010. serializationObject.color1 = this.color1.asArray();
  28011. serializationObject.color2 = this.color2.asArray();
  28012. serializationObject.colorDead = this.colorDead.asArray();
  28013. serializationObject.updateSpeed = this.updateSpeed;
  28014. serializationObject.targetStopDuration = this.targetStopDuration;
  28015. serializationObject.textureMask = this.textureMask.asArray();
  28016. serializationObject.blendMode = this.blendMode;
  28017. return serializationObject;
  28018. };
  28019. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28020. var name = parsedParticleSystem.name;
  28021. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28022. if (parsedParticleSystem.id) {
  28023. particleSystem.id = parsedParticleSystem.id;
  28024. }
  28025. // Texture
  28026. if (parsedParticleSystem.textureName) {
  28027. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28028. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28029. }
  28030. // Emitter
  28031. if (parsedParticleSystem.emitterId) {
  28032. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28033. }
  28034. else {
  28035. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28036. }
  28037. // Animations
  28038. if (parsedParticleSystem.animations) {
  28039. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28040. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28041. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28042. }
  28043. }
  28044. if (parsedParticleSystem.autoAnimate) {
  28045. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28046. }
  28047. // Particle system
  28048. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28049. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28050. particleSystem.minSize = parsedParticleSystem.minSize;
  28051. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28052. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28053. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28054. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28055. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28056. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28057. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28058. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28059. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28060. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28061. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28062. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28063. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28064. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28065. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28066. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28067. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28068. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28069. if (!parsedParticleSystem.preventAutoStart) {
  28070. particleSystem.start();
  28071. }
  28072. return particleSystem;
  28073. };
  28074. // Statics
  28075. ParticleSystem.BLENDMODE_ONEONE = 0;
  28076. ParticleSystem.BLENDMODE_STANDARD = 1;
  28077. return ParticleSystem;
  28078. }());
  28079. BABYLON.ParticleSystem = ParticleSystem;
  28080. })(BABYLON || (BABYLON = {}));
  28081. var BABYLON;
  28082. (function (BABYLON) {
  28083. var AnimationRange = (function () {
  28084. function AnimationRange(name, from, to) {
  28085. this.name = name;
  28086. this.from = from;
  28087. this.to = to;
  28088. }
  28089. AnimationRange.prototype.clone = function () {
  28090. return new AnimationRange(this.name, this.from, this.to);
  28091. };
  28092. return AnimationRange;
  28093. }());
  28094. BABYLON.AnimationRange = AnimationRange;
  28095. /**
  28096. * Composed of a frame, and an action function
  28097. */
  28098. var AnimationEvent = (function () {
  28099. function AnimationEvent(frame, action, onlyOnce) {
  28100. this.frame = frame;
  28101. this.action = action;
  28102. this.onlyOnce = onlyOnce;
  28103. this.isDone = false;
  28104. }
  28105. return AnimationEvent;
  28106. }());
  28107. BABYLON.AnimationEvent = AnimationEvent;
  28108. var PathCursor = (function () {
  28109. function PathCursor(path) {
  28110. this.path = path;
  28111. this._onchange = new Array();
  28112. this.value = 0;
  28113. this.animations = new Array();
  28114. }
  28115. PathCursor.prototype.getPoint = function () {
  28116. var point = this.path.getPointAtLengthPosition(this.value);
  28117. return new BABYLON.Vector3(point.x, 0, point.y);
  28118. };
  28119. PathCursor.prototype.moveAhead = function (step) {
  28120. if (step === void 0) { step = 0.002; }
  28121. this.move(step);
  28122. return this;
  28123. };
  28124. PathCursor.prototype.moveBack = function (step) {
  28125. if (step === void 0) { step = 0.002; }
  28126. this.move(-step);
  28127. return this;
  28128. };
  28129. PathCursor.prototype.move = function (step) {
  28130. if (Math.abs(step) > 1) {
  28131. throw "step size should be less than 1.";
  28132. }
  28133. this.value += step;
  28134. this.ensureLimits();
  28135. this.raiseOnChange();
  28136. return this;
  28137. };
  28138. PathCursor.prototype.ensureLimits = function () {
  28139. while (this.value > 1) {
  28140. this.value -= 1;
  28141. }
  28142. while (this.value < 0) {
  28143. this.value += 1;
  28144. }
  28145. return this;
  28146. };
  28147. // used by animation engine
  28148. PathCursor.prototype.markAsDirty = function (propertyName) {
  28149. this.ensureLimits();
  28150. this.raiseOnChange();
  28151. return this;
  28152. };
  28153. PathCursor.prototype.raiseOnChange = function () {
  28154. var _this = this;
  28155. this._onchange.forEach(function (f) { return f(_this); });
  28156. return this;
  28157. };
  28158. PathCursor.prototype.onchange = function (f) {
  28159. this._onchange.push(f);
  28160. return this;
  28161. };
  28162. return PathCursor;
  28163. }());
  28164. BABYLON.PathCursor = PathCursor;
  28165. var Animation = (function () {
  28166. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28167. this.name = name;
  28168. this.targetProperty = targetProperty;
  28169. this.framePerSecond = framePerSecond;
  28170. this.dataType = dataType;
  28171. this.loopMode = loopMode;
  28172. this.enableBlending = enableBlending;
  28173. this._offsetsCache = {};
  28174. this._highLimitsCache = {};
  28175. this._stopped = false;
  28176. this._blendingFactor = 0;
  28177. // The set of event that will be linked to this animation
  28178. this._events = new Array();
  28179. this.allowMatricesInterpolation = false;
  28180. this.blendingSpeed = 0.01;
  28181. this._ranges = {};
  28182. this.targetPropertyPath = targetProperty.split(".");
  28183. this.dataType = dataType;
  28184. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28185. }
  28186. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28187. var dataType = undefined;
  28188. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28189. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28190. }
  28191. else if (from instanceof BABYLON.Quaternion) {
  28192. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28193. }
  28194. else if (from instanceof BABYLON.Vector3) {
  28195. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28196. }
  28197. else if (from instanceof BABYLON.Vector2) {
  28198. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28199. }
  28200. else if (from instanceof BABYLON.Color3) {
  28201. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28202. }
  28203. else if (from instanceof BABYLON.Size) {
  28204. dataType = Animation.ANIMATIONTYPE_SIZE;
  28205. }
  28206. if (dataType == undefined) {
  28207. return null;
  28208. }
  28209. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28210. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28211. animation.setKeys(keys);
  28212. if (easingFunction !== undefined) {
  28213. animation.setEasingFunction(easingFunction);
  28214. }
  28215. return animation;
  28216. };
  28217. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28218. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28219. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28220. };
  28221. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28222. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28223. node.animations.push(animation);
  28224. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28225. };
  28226. // Methods
  28227. /**
  28228. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28229. */
  28230. Animation.prototype.toString = function (fullDetails) {
  28231. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28232. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28233. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28234. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28235. if (fullDetails) {
  28236. ret += ", Ranges: {";
  28237. var first = true;
  28238. for (var name in this._ranges) {
  28239. if (first) {
  28240. ret += ", ";
  28241. first = false;
  28242. }
  28243. ret += name;
  28244. }
  28245. ret += "}";
  28246. }
  28247. return ret;
  28248. };
  28249. /**
  28250. * Add an event to this animation.
  28251. */
  28252. Animation.prototype.addEvent = function (event) {
  28253. this._events.push(event);
  28254. };
  28255. /**
  28256. * Remove all events found at the given frame
  28257. * @param frame
  28258. */
  28259. Animation.prototype.removeEvents = function (frame) {
  28260. for (var index = 0; index < this._events.length; index++) {
  28261. if (this._events[index].frame === frame) {
  28262. this._events.splice(index, 1);
  28263. index--;
  28264. }
  28265. }
  28266. };
  28267. Animation.prototype.createRange = function (name, from, to) {
  28268. // check name not already in use; could happen for bones after serialized
  28269. if (!this._ranges[name]) {
  28270. this._ranges[name] = new AnimationRange(name, from, to);
  28271. }
  28272. };
  28273. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28274. if (deleteFrames === void 0) { deleteFrames = true; }
  28275. if (this._ranges[name]) {
  28276. if (deleteFrames) {
  28277. var from = this._ranges[name].from;
  28278. var to = this._ranges[name].to;
  28279. // this loop MUST go high to low for multiple splices to work
  28280. for (var key = this._keys.length - 1; key >= 0; key--) {
  28281. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28282. this._keys.splice(key, 1);
  28283. }
  28284. }
  28285. }
  28286. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28287. }
  28288. };
  28289. Animation.prototype.getRange = function (name) {
  28290. return this._ranges[name];
  28291. };
  28292. Animation.prototype.reset = function () {
  28293. this._offsetsCache = {};
  28294. this._highLimitsCache = {};
  28295. this.currentFrame = 0;
  28296. this._blendingFactor = 0;
  28297. this._originalBlendValue = null;
  28298. };
  28299. Animation.prototype.isStopped = function () {
  28300. return this._stopped;
  28301. };
  28302. Animation.prototype.getKeys = function () {
  28303. return this._keys;
  28304. };
  28305. Animation.prototype.getHighestFrame = function () {
  28306. var ret = 0;
  28307. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28308. if (ret < this._keys[key].frame) {
  28309. ret = this._keys[key].frame;
  28310. }
  28311. }
  28312. return ret;
  28313. };
  28314. Animation.prototype.getEasingFunction = function () {
  28315. return this._easingFunction;
  28316. };
  28317. Animation.prototype.setEasingFunction = function (easingFunction) {
  28318. this._easingFunction = easingFunction;
  28319. };
  28320. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28321. return startValue + (endValue - startValue) * gradient;
  28322. };
  28323. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28324. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28325. };
  28326. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28327. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28328. };
  28329. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28330. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28331. };
  28332. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28333. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28334. };
  28335. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28336. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28337. };
  28338. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28339. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28340. };
  28341. Animation.prototype.clone = function () {
  28342. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28343. if (this._keys) {
  28344. clone.setKeys(this._keys);
  28345. }
  28346. if (this._ranges) {
  28347. clone._ranges = {};
  28348. for (var name in this._ranges) {
  28349. clone._ranges[name] = this._ranges[name].clone();
  28350. }
  28351. }
  28352. return clone;
  28353. };
  28354. Animation.prototype.setKeys = function (values) {
  28355. this._keys = values.slice(0);
  28356. this._offsetsCache = {};
  28357. this._highLimitsCache = {};
  28358. };
  28359. Animation.prototype._getKeyValue = function (value) {
  28360. if (typeof value === "function") {
  28361. return value();
  28362. }
  28363. return value;
  28364. };
  28365. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28366. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28367. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28368. }
  28369. this.currentFrame = currentFrame;
  28370. // Try to get a hash to find the right key
  28371. 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));
  28372. if (this._keys[startKey].frame >= currentFrame) {
  28373. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  28374. startKey--;
  28375. }
  28376. }
  28377. for (var key = startKey; key < this._keys.length; key++) {
  28378. if (this._keys[key + 1].frame >= currentFrame) {
  28379. var startValue = this._getKeyValue(this._keys[key].value);
  28380. var endValue = this._getKeyValue(this._keys[key + 1].value);
  28381. // gradient : percent of currentFrame between the frame inf and the frame sup
  28382. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  28383. // check for easingFunction and correction of gradient
  28384. if (this._easingFunction != null) {
  28385. gradient = this._easingFunction.ease(gradient);
  28386. }
  28387. switch (this.dataType) {
  28388. // Float
  28389. case Animation.ANIMATIONTYPE_FLOAT:
  28390. switch (loopMode) {
  28391. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28392. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28393. return this.floatInterpolateFunction(startValue, endValue, gradient);
  28394. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28395. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  28396. }
  28397. break;
  28398. // Quaternion
  28399. case Animation.ANIMATIONTYPE_QUATERNION:
  28400. var quaternion = null;
  28401. switch (loopMode) {
  28402. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28403. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28404. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28405. break;
  28406. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28407. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28408. break;
  28409. }
  28410. return quaternion;
  28411. // Vector3
  28412. case Animation.ANIMATIONTYPE_VECTOR3:
  28413. switch (loopMode) {
  28414. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28415. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28416. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  28417. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28418. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28419. }
  28420. // Vector2
  28421. case Animation.ANIMATIONTYPE_VECTOR2:
  28422. switch (loopMode) {
  28423. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28424. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28425. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  28426. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28427. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28428. }
  28429. // Size
  28430. case Animation.ANIMATIONTYPE_SIZE:
  28431. switch (loopMode) {
  28432. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28433. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28434. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28435. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28436. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28437. }
  28438. // Color3
  28439. case Animation.ANIMATIONTYPE_COLOR3:
  28440. switch (loopMode) {
  28441. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28442. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28443. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28444. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28445. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28446. }
  28447. // Matrix
  28448. case Animation.ANIMATIONTYPE_MATRIX:
  28449. switch (loopMode) {
  28450. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28451. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28452. if (this.allowMatricesInterpolation) {
  28453. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28454. }
  28455. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28456. return startValue;
  28457. }
  28458. default:
  28459. break;
  28460. }
  28461. break;
  28462. }
  28463. }
  28464. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28465. };
  28466. Animation.prototype.setValue = function (currentValue, blend) {
  28467. if (blend === void 0) { blend = false; }
  28468. // Set value
  28469. var path;
  28470. var destination;
  28471. if (this.targetPropertyPath.length > 1) {
  28472. var property = this._target[this.targetPropertyPath[0]];
  28473. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28474. property = property[this.targetPropertyPath[index]];
  28475. }
  28476. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28477. destination = property;
  28478. }
  28479. else {
  28480. path = this.targetPropertyPath[0];
  28481. destination = this._target;
  28482. }
  28483. // Blending
  28484. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28485. if (!this._originalBlendValue) {
  28486. if (destination[path].clone) {
  28487. this._originalBlendValue = destination[path].clone();
  28488. }
  28489. else {
  28490. this._originalBlendValue = destination[path];
  28491. }
  28492. }
  28493. if (this._originalBlendValue.prototype) {
  28494. if (this._originalBlendValue.prototype.Lerp) {
  28495. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28496. }
  28497. else {
  28498. destination[path] = currentValue;
  28499. }
  28500. }
  28501. else if (this._originalBlendValue.m) {
  28502. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28503. }
  28504. else {
  28505. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28506. }
  28507. this._blendingFactor += this.blendingSpeed;
  28508. }
  28509. else {
  28510. destination[path] = currentValue;
  28511. }
  28512. if (this._target.markAsDirty) {
  28513. this._target.markAsDirty(this.targetProperty);
  28514. }
  28515. };
  28516. Animation.prototype.goToFrame = function (frame) {
  28517. if (frame < this._keys[0].frame) {
  28518. frame = this._keys[0].frame;
  28519. }
  28520. else if (frame > this._keys[this._keys.length - 1].frame) {
  28521. frame = this._keys[this._keys.length - 1].frame;
  28522. }
  28523. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28524. this.setValue(currentValue);
  28525. };
  28526. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28527. if (blend === void 0) { blend = false; }
  28528. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28529. this._stopped = true;
  28530. return false;
  28531. }
  28532. var returnValue = true;
  28533. // Adding a start key at frame 0 if missing
  28534. if (this._keys[0].frame !== 0) {
  28535. var newKey = { frame: 0, value: this._keys[0].value };
  28536. this._keys.splice(0, 0, newKey);
  28537. }
  28538. // Check limits
  28539. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28540. from = this._keys[0].frame;
  28541. }
  28542. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28543. to = this._keys[this._keys.length - 1].frame;
  28544. }
  28545. // Compute ratio
  28546. var range = to - from;
  28547. var offsetValue;
  28548. // ratio represents the frame delta between from and to
  28549. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28550. var highLimitValue = 0;
  28551. if (ratio > range && !loop) {
  28552. returnValue = false;
  28553. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28554. }
  28555. else {
  28556. // Get max value if required
  28557. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28558. var keyOffset = to.toString() + from.toString();
  28559. if (!this._offsetsCache[keyOffset]) {
  28560. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28561. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28562. switch (this.dataType) {
  28563. // Float
  28564. case Animation.ANIMATIONTYPE_FLOAT:
  28565. this._offsetsCache[keyOffset] = toValue - fromValue;
  28566. break;
  28567. // Quaternion
  28568. case Animation.ANIMATIONTYPE_QUATERNION:
  28569. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28570. break;
  28571. // Vector3
  28572. case Animation.ANIMATIONTYPE_VECTOR3:
  28573. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28574. // Vector2
  28575. case Animation.ANIMATIONTYPE_VECTOR2:
  28576. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28577. // Size
  28578. case Animation.ANIMATIONTYPE_SIZE:
  28579. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28580. // Color3
  28581. case Animation.ANIMATIONTYPE_COLOR3:
  28582. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28583. default:
  28584. break;
  28585. }
  28586. this._highLimitsCache[keyOffset] = toValue;
  28587. }
  28588. highLimitValue = this._highLimitsCache[keyOffset];
  28589. offsetValue = this._offsetsCache[keyOffset];
  28590. }
  28591. }
  28592. if (offsetValue === undefined) {
  28593. switch (this.dataType) {
  28594. // Float
  28595. case Animation.ANIMATIONTYPE_FLOAT:
  28596. offsetValue = 0;
  28597. break;
  28598. // Quaternion
  28599. case Animation.ANIMATIONTYPE_QUATERNION:
  28600. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28601. break;
  28602. // Vector3
  28603. case Animation.ANIMATIONTYPE_VECTOR3:
  28604. offsetValue = BABYLON.Vector3.Zero();
  28605. break;
  28606. // Vector2
  28607. case Animation.ANIMATIONTYPE_VECTOR2:
  28608. offsetValue = BABYLON.Vector2.Zero();
  28609. break;
  28610. // Size
  28611. case Animation.ANIMATIONTYPE_SIZE:
  28612. offsetValue = BABYLON.Size.Zero();
  28613. break;
  28614. // Color3
  28615. case Animation.ANIMATIONTYPE_COLOR3:
  28616. offsetValue = BABYLON.Color3.Black();
  28617. }
  28618. }
  28619. // Compute value
  28620. var repeatCount = (ratio / range) >> 0;
  28621. var currentFrame = returnValue ? from + ratio % range : to;
  28622. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28623. // Set value
  28624. this.setValue(currentValue);
  28625. // Check events
  28626. for (var index = 0; index < this._events.length; index++) {
  28627. if (currentFrame >= this._events[index].frame) {
  28628. var event = this._events[index];
  28629. if (!event.isDone) {
  28630. // If event should be done only once, remove it.
  28631. if (event.onlyOnce) {
  28632. this._events.splice(index, 1);
  28633. index--;
  28634. }
  28635. event.isDone = true;
  28636. event.action();
  28637. } // Don't do anything if the event has already be done.
  28638. }
  28639. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28640. // reset event, the animation is looping
  28641. this._events[index].isDone = false;
  28642. }
  28643. }
  28644. if (!returnValue) {
  28645. this._stopped = true;
  28646. }
  28647. return returnValue;
  28648. };
  28649. Animation.prototype.serialize = function () {
  28650. var serializationObject = {};
  28651. serializationObject.name = this.name;
  28652. serializationObject.property = this.targetProperty;
  28653. serializationObject.framePerSecond = this.framePerSecond;
  28654. serializationObject.dataType = this.dataType;
  28655. serializationObject.loopBehavior = this.loopMode;
  28656. var dataType = this.dataType;
  28657. serializationObject.keys = [];
  28658. var keys = this.getKeys();
  28659. for (var index = 0; index < keys.length; index++) {
  28660. var animationKey = keys[index];
  28661. var key = {};
  28662. key.frame = animationKey.frame;
  28663. switch (dataType) {
  28664. case Animation.ANIMATIONTYPE_FLOAT:
  28665. key.values = [animationKey.value];
  28666. break;
  28667. case Animation.ANIMATIONTYPE_QUATERNION:
  28668. case Animation.ANIMATIONTYPE_MATRIX:
  28669. case Animation.ANIMATIONTYPE_VECTOR3:
  28670. case Animation.ANIMATIONTYPE_COLOR3:
  28671. key.values = animationKey.value.asArray();
  28672. break;
  28673. }
  28674. serializationObject.keys.push(key);
  28675. }
  28676. serializationObject.ranges = [];
  28677. for (var name in this._ranges) {
  28678. var range = {};
  28679. range.name = name;
  28680. range.from = this._ranges[name].from;
  28681. range.to = this._ranges[name].to;
  28682. serializationObject.ranges.push(range);
  28683. }
  28684. return serializationObject;
  28685. };
  28686. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28687. get: function () {
  28688. return Animation._ANIMATIONTYPE_FLOAT;
  28689. },
  28690. enumerable: true,
  28691. configurable: true
  28692. });
  28693. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28694. get: function () {
  28695. return Animation._ANIMATIONTYPE_VECTOR3;
  28696. },
  28697. enumerable: true,
  28698. configurable: true
  28699. });
  28700. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28701. get: function () {
  28702. return Animation._ANIMATIONTYPE_VECTOR2;
  28703. },
  28704. enumerable: true,
  28705. configurable: true
  28706. });
  28707. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28708. get: function () {
  28709. return Animation._ANIMATIONTYPE_SIZE;
  28710. },
  28711. enumerable: true,
  28712. configurable: true
  28713. });
  28714. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28715. get: function () {
  28716. return Animation._ANIMATIONTYPE_QUATERNION;
  28717. },
  28718. enumerable: true,
  28719. configurable: true
  28720. });
  28721. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28722. get: function () {
  28723. return Animation._ANIMATIONTYPE_MATRIX;
  28724. },
  28725. enumerable: true,
  28726. configurable: true
  28727. });
  28728. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28729. get: function () {
  28730. return Animation._ANIMATIONTYPE_COLOR3;
  28731. },
  28732. enumerable: true,
  28733. configurable: true
  28734. });
  28735. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28736. get: function () {
  28737. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28738. },
  28739. enumerable: true,
  28740. configurable: true
  28741. });
  28742. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28743. get: function () {
  28744. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28745. },
  28746. enumerable: true,
  28747. configurable: true
  28748. });
  28749. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28750. get: function () {
  28751. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28752. },
  28753. enumerable: true,
  28754. configurable: true
  28755. });
  28756. Animation.Parse = function (parsedAnimation) {
  28757. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28758. var dataType = parsedAnimation.dataType;
  28759. var keys = [];
  28760. var data;
  28761. var index;
  28762. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28763. var key = parsedAnimation.keys[index];
  28764. switch (dataType) {
  28765. case Animation.ANIMATIONTYPE_FLOAT:
  28766. data = key.values[0];
  28767. break;
  28768. case Animation.ANIMATIONTYPE_QUATERNION:
  28769. data = BABYLON.Quaternion.FromArray(key.values);
  28770. break;
  28771. case Animation.ANIMATIONTYPE_MATRIX:
  28772. data = BABYLON.Matrix.FromArray(key.values);
  28773. break;
  28774. case Animation.ANIMATIONTYPE_COLOR3:
  28775. data = BABYLON.Color3.FromArray(key.values);
  28776. break;
  28777. case Animation.ANIMATIONTYPE_VECTOR3:
  28778. default:
  28779. data = BABYLON.Vector3.FromArray(key.values);
  28780. break;
  28781. }
  28782. keys.push({
  28783. frame: key.frame,
  28784. value: data
  28785. });
  28786. }
  28787. animation.setKeys(keys);
  28788. if (parsedAnimation.ranges) {
  28789. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28790. data = parsedAnimation.ranges[index];
  28791. animation.createRange(data.name, data.from, data.to);
  28792. }
  28793. }
  28794. return animation;
  28795. };
  28796. Animation.AppendSerializedAnimations = function (source, destination) {
  28797. if (source.animations) {
  28798. destination.animations = [];
  28799. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28800. var animation = source.animations[animationIndex];
  28801. destination.animations.push(animation.serialize());
  28802. }
  28803. }
  28804. };
  28805. // Statics
  28806. Animation._ANIMATIONTYPE_FLOAT = 0;
  28807. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28808. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28809. Animation._ANIMATIONTYPE_MATRIX = 3;
  28810. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28811. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28812. Animation._ANIMATIONTYPE_SIZE = 6;
  28813. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28814. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28815. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28816. return Animation;
  28817. }());
  28818. BABYLON.Animation = Animation;
  28819. })(BABYLON || (BABYLON = {}));
  28820. var BABYLON;
  28821. (function (BABYLON) {
  28822. var Animatable = (function () {
  28823. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28824. if (fromFrame === void 0) { fromFrame = 0; }
  28825. if (toFrame === void 0) { toFrame = 100; }
  28826. if (loopAnimation === void 0) { loopAnimation = false; }
  28827. if (speedRatio === void 0) { speedRatio = 1.0; }
  28828. this.target = target;
  28829. this.fromFrame = fromFrame;
  28830. this.toFrame = toFrame;
  28831. this.loopAnimation = loopAnimation;
  28832. this.speedRatio = speedRatio;
  28833. this.onAnimationEnd = onAnimationEnd;
  28834. this._animations = new Array();
  28835. this._paused = false;
  28836. this.animationStarted = false;
  28837. if (animations) {
  28838. this.appendAnimations(target, animations);
  28839. }
  28840. this._scene = scene;
  28841. scene._activeAnimatables.push(this);
  28842. }
  28843. // Methods
  28844. Animatable.prototype.getAnimations = function () {
  28845. return this._animations;
  28846. };
  28847. Animatable.prototype.appendAnimations = function (target, animations) {
  28848. for (var index = 0; index < animations.length; index++) {
  28849. var animation = animations[index];
  28850. animation._target = target;
  28851. this._animations.push(animation);
  28852. }
  28853. };
  28854. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28855. var animations = this._animations;
  28856. for (var index = 0; index < animations.length; index++) {
  28857. if (animations[index].targetProperty === property) {
  28858. return animations[index];
  28859. }
  28860. }
  28861. return null;
  28862. };
  28863. Animatable.prototype.reset = function () {
  28864. var animations = this._animations;
  28865. for (var index = 0; index < animations.length; index++) {
  28866. animations[index].reset();
  28867. }
  28868. this._localDelayOffset = null;
  28869. this._pausedDelay = null;
  28870. };
  28871. Animatable.prototype.enableBlending = function (blendingSpeed) {
  28872. var animations = this._animations;
  28873. for (var index = 0; index < animations.length; index++) {
  28874. animations[index].enableBlending = true;
  28875. animations[index].blendingSpeed = blendingSpeed;
  28876. }
  28877. };
  28878. Animatable.prototype.disableBlending = function () {
  28879. var animations = this._animations;
  28880. for (var index = 0; index < animations.length; index++) {
  28881. animations[index].enableBlending = false;
  28882. }
  28883. };
  28884. Animatable.prototype.goToFrame = function (frame) {
  28885. var animations = this._animations;
  28886. for (var index = 0; index < animations.length; index++) {
  28887. animations[index].goToFrame(frame);
  28888. }
  28889. };
  28890. Animatable.prototype.pause = function () {
  28891. if (this._paused) {
  28892. return;
  28893. }
  28894. this._paused = true;
  28895. };
  28896. Animatable.prototype.restart = function () {
  28897. this._paused = false;
  28898. };
  28899. Animatable.prototype.stop = function (animationName) {
  28900. var index = this._scene._activeAnimatables.indexOf(this);
  28901. if (index > -1) {
  28902. var animations = this._animations;
  28903. var numberOfAnimationsStopped = 0;
  28904. for (var index = animations.length - 1; index >= 0; index--) {
  28905. if (typeof animationName === "string" && animations[index].name != animationName) {
  28906. continue;
  28907. }
  28908. animations[index].reset();
  28909. animations.splice(index, 1);
  28910. numberOfAnimationsStopped++;
  28911. }
  28912. if (animations.length == numberOfAnimationsStopped) {
  28913. this._scene._activeAnimatables.splice(index, 1);
  28914. if (this.onAnimationEnd) {
  28915. this.onAnimationEnd();
  28916. }
  28917. }
  28918. }
  28919. };
  28920. Animatable.prototype._animate = function (delay) {
  28921. if (this._paused) {
  28922. this.animationStarted = false;
  28923. if (!this._pausedDelay) {
  28924. this._pausedDelay = delay;
  28925. }
  28926. return true;
  28927. }
  28928. if (!this._localDelayOffset) {
  28929. this._localDelayOffset = delay;
  28930. }
  28931. else if (this._pausedDelay) {
  28932. this._localDelayOffset += delay - this._pausedDelay;
  28933. this._pausedDelay = null;
  28934. }
  28935. // Animating
  28936. var running = false;
  28937. var animations = this._animations;
  28938. var index;
  28939. for (index = 0; index < animations.length; index++) {
  28940. var animation = animations[index];
  28941. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  28942. running = running || isRunning;
  28943. }
  28944. this.animationStarted = running;
  28945. if (!running) {
  28946. // Remove from active animatables
  28947. index = this._scene._activeAnimatables.indexOf(this);
  28948. this._scene._activeAnimatables.splice(index, 1);
  28949. }
  28950. if (!running && this.onAnimationEnd) {
  28951. this.onAnimationEnd();
  28952. this.onAnimationEnd = null;
  28953. }
  28954. return running;
  28955. };
  28956. return Animatable;
  28957. }());
  28958. BABYLON.Animatable = Animatable;
  28959. })(BABYLON || (BABYLON = {}));
  28960. var BABYLON;
  28961. (function (BABYLON) {
  28962. var EasingFunction = (function () {
  28963. function EasingFunction() {
  28964. // Properties
  28965. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  28966. }
  28967. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  28968. get: function () {
  28969. return EasingFunction._EASINGMODE_EASEIN;
  28970. },
  28971. enumerable: true,
  28972. configurable: true
  28973. });
  28974. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  28975. get: function () {
  28976. return EasingFunction._EASINGMODE_EASEOUT;
  28977. },
  28978. enumerable: true,
  28979. configurable: true
  28980. });
  28981. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  28982. get: function () {
  28983. return EasingFunction._EASINGMODE_EASEINOUT;
  28984. },
  28985. enumerable: true,
  28986. configurable: true
  28987. });
  28988. EasingFunction.prototype.setEasingMode = function (easingMode) {
  28989. var n = Math.min(Math.max(easingMode, 0), 2);
  28990. this._easingMode = n;
  28991. };
  28992. EasingFunction.prototype.getEasingMode = function () {
  28993. return this._easingMode;
  28994. };
  28995. EasingFunction.prototype.easeInCore = function (gradient) {
  28996. throw new Error('You must implement this method');
  28997. };
  28998. EasingFunction.prototype.ease = function (gradient) {
  28999. switch (this._easingMode) {
  29000. case EasingFunction.EASINGMODE_EASEIN:
  29001. return this.easeInCore(gradient);
  29002. case EasingFunction.EASINGMODE_EASEOUT:
  29003. return (1 - this.easeInCore(1 - gradient));
  29004. }
  29005. if (gradient >= 0.5) {
  29006. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29007. }
  29008. return (this.easeInCore(gradient * 2) * 0.5);
  29009. };
  29010. //Statics
  29011. EasingFunction._EASINGMODE_EASEIN = 0;
  29012. EasingFunction._EASINGMODE_EASEOUT = 1;
  29013. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29014. return EasingFunction;
  29015. }());
  29016. BABYLON.EasingFunction = EasingFunction;
  29017. var CircleEase = (function (_super) {
  29018. __extends(CircleEase, _super);
  29019. function CircleEase() {
  29020. _super.apply(this, arguments);
  29021. }
  29022. CircleEase.prototype.easeInCore = function (gradient) {
  29023. gradient = Math.max(0, Math.min(1, gradient));
  29024. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29025. };
  29026. return CircleEase;
  29027. }(EasingFunction));
  29028. BABYLON.CircleEase = CircleEase;
  29029. var BackEase = (function (_super) {
  29030. __extends(BackEase, _super);
  29031. function BackEase(amplitude) {
  29032. if (amplitude === void 0) { amplitude = 1; }
  29033. _super.call(this);
  29034. this.amplitude = amplitude;
  29035. }
  29036. BackEase.prototype.easeInCore = function (gradient) {
  29037. var num = Math.max(0, this.amplitude);
  29038. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29039. };
  29040. return BackEase;
  29041. }(EasingFunction));
  29042. BABYLON.BackEase = BackEase;
  29043. var BounceEase = (function (_super) {
  29044. __extends(BounceEase, _super);
  29045. function BounceEase(bounces, bounciness) {
  29046. if (bounces === void 0) { bounces = 3; }
  29047. if (bounciness === void 0) { bounciness = 2; }
  29048. _super.call(this);
  29049. this.bounces = bounces;
  29050. this.bounciness = bounciness;
  29051. }
  29052. BounceEase.prototype.easeInCore = function (gradient) {
  29053. var y = Math.max(0.0, this.bounces);
  29054. var bounciness = this.bounciness;
  29055. if (bounciness <= 1.0) {
  29056. bounciness = 1.001;
  29057. }
  29058. var num9 = Math.pow(bounciness, y);
  29059. var num5 = 1.0 - bounciness;
  29060. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29061. var num15 = gradient * num4;
  29062. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29063. var num3 = Math.floor(num65);
  29064. var num13 = num3 + 1.0;
  29065. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29066. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29067. var num7 = (num8 + num12) * 0.5;
  29068. var num6 = gradient - num7;
  29069. var num2 = num7 - num8;
  29070. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29071. };
  29072. return BounceEase;
  29073. }(EasingFunction));
  29074. BABYLON.BounceEase = BounceEase;
  29075. var CubicEase = (function (_super) {
  29076. __extends(CubicEase, _super);
  29077. function CubicEase() {
  29078. _super.apply(this, arguments);
  29079. }
  29080. CubicEase.prototype.easeInCore = function (gradient) {
  29081. return (gradient * gradient * gradient);
  29082. };
  29083. return CubicEase;
  29084. }(EasingFunction));
  29085. BABYLON.CubicEase = CubicEase;
  29086. var ElasticEase = (function (_super) {
  29087. __extends(ElasticEase, _super);
  29088. function ElasticEase(oscillations, springiness) {
  29089. if (oscillations === void 0) { oscillations = 3; }
  29090. if (springiness === void 0) { springiness = 3; }
  29091. _super.call(this);
  29092. this.oscillations = oscillations;
  29093. this.springiness = springiness;
  29094. }
  29095. ElasticEase.prototype.easeInCore = function (gradient) {
  29096. var num2;
  29097. var num3 = Math.max(0.0, this.oscillations);
  29098. var num = Math.max(0.0, this.springiness);
  29099. if (num == 0) {
  29100. num2 = gradient;
  29101. }
  29102. else {
  29103. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29104. }
  29105. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29106. };
  29107. return ElasticEase;
  29108. }(EasingFunction));
  29109. BABYLON.ElasticEase = ElasticEase;
  29110. var ExponentialEase = (function (_super) {
  29111. __extends(ExponentialEase, _super);
  29112. function ExponentialEase(exponent) {
  29113. if (exponent === void 0) { exponent = 2; }
  29114. _super.call(this);
  29115. this.exponent = exponent;
  29116. }
  29117. ExponentialEase.prototype.easeInCore = function (gradient) {
  29118. if (this.exponent <= 0) {
  29119. return gradient;
  29120. }
  29121. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29122. };
  29123. return ExponentialEase;
  29124. }(EasingFunction));
  29125. BABYLON.ExponentialEase = ExponentialEase;
  29126. var PowerEase = (function (_super) {
  29127. __extends(PowerEase, _super);
  29128. function PowerEase(power) {
  29129. if (power === void 0) { power = 2; }
  29130. _super.call(this);
  29131. this.power = power;
  29132. }
  29133. PowerEase.prototype.easeInCore = function (gradient) {
  29134. var y = Math.max(0.0, this.power);
  29135. return Math.pow(gradient, y);
  29136. };
  29137. return PowerEase;
  29138. }(EasingFunction));
  29139. BABYLON.PowerEase = PowerEase;
  29140. var QuadraticEase = (function (_super) {
  29141. __extends(QuadraticEase, _super);
  29142. function QuadraticEase() {
  29143. _super.apply(this, arguments);
  29144. }
  29145. QuadraticEase.prototype.easeInCore = function (gradient) {
  29146. return (gradient * gradient);
  29147. };
  29148. return QuadraticEase;
  29149. }(EasingFunction));
  29150. BABYLON.QuadraticEase = QuadraticEase;
  29151. var QuarticEase = (function (_super) {
  29152. __extends(QuarticEase, _super);
  29153. function QuarticEase() {
  29154. _super.apply(this, arguments);
  29155. }
  29156. QuarticEase.prototype.easeInCore = function (gradient) {
  29157. return (gradient * gradient * gradient * gradient);
  29158. };
  29159. return QuarticEase;
  29160. }(EasingFunction));
  29161. BABYLON.QuarticEase = QuarticEase;
  29162. var QuinticEase = (function (_super) {
  29163. __extends(QuinticEase, _super);
  29164. function QuinticEase() {
  29165. _super.apply(this, arguments);
  29166. }
  29167. QuinticEase.prototype.easeInCore = function (gradient) {
  29168. return (gradient * gradient * gradient * gradient * gradient);
  29169. };
  29170. return QuinticEase;
  29171. }(EasingFunction));
  29172. BABYLON.QuinticEase = QuinticEase;
  29173. var SineEase = (function (_super) {
  29174. __extends(SineEase, _super);
  29175. function SineEase() {
  29176. _super.apply(this, arguments);
  29177. }
  29178. SineEase.prototype.easeInCore = function (gradient) {
  29179. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29180. };
  29181. return SineEase;
  29182. }(EasingFunction));
  29183. BABYLON.SineEase = SineEase;
  29184. var BezierCurveEase = (function (_super) {
  29185. __extends(BezierCurveEase, _super);
  29186. function BezierCurveEase(x1, y1, x2, y2) {
  29187. if (x1 === void 0) { x1 = 0; }
  29188. if (y1 === void 0) { y1 = 0; }
  29189. if (x2 === void 0) { x2 = 1; }
  29190. if (y2 === void 0) { y2 = 1; }
  29191. _super.call(this);
  29192. this.x1 = x1;
  29193. this.y1 = y1;
  29194. this.x2 = x2;
  29195. this.y2 = y2;
  29196. }
  29197. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29198. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29199. };
  29200. return BezierCurveEase;
  29201. }(EasingFunction));
  29202. BABYLON.BezierCurveEase = BezierCurveEase;
  29203. })(BABYLON || (BABYLON = {}));
  29204. var BABYLON;
  29205. (function (BABYLON) {
  29206. var Bone = (function (_super) {
  29207. __extends(Bone, _super);
  29208. function Bone(name, skeleton, parentBone, matrix, restPose) {
  29209. _super.call(this, name, skeleton.getScene());
  29210. this.name = name;
  29211. this.children = new Array();
  29212. this.animations = new Array();
  29213. this._worldTransform = new BABYLON.Matrix();
  29214. this._absoluteTransform = new BABYLON.Matrix();
  29215. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  29216. this._skeleton = skeleton;
  29217. this._matrix = matrix;
  29218. this._baseMatrix = matrix;
  29219. this._restPose = restPose ? restPose : matrix.clone();
  29220. skeleton.bones.push(this);
  29221. if (parentBone) {
  29222. this._parent = parentBone;
  29223. parentBone.children.push(this);
  29224. }
  29225. else {
  29226. this._parent = null;
  29227. }
  29228. this._updateDifferenceMatrix();
  29229. }
  29230. // Members
  29231. Bone.prototype.getParent = function () {
  29232. return this._parent;
  29233. };
  29234. Bone.prototype.getLocalMatrix = function () {
  29235. return this._matrix;
  29236. };
  29237. Bone.prototype.getBaseMatrix = function () {
  29238. return this._baseMatrix;
  29239. };
  29240. Bone.prototype.getRestPose = function () {
  29241. return this._restPose;
  29242. };
  29243. Bone.prototype.returnToRest = function () {
  29244. this.updateMatrix(this._restPose.clone());
  29245. };
  29246. Bone.prototype.getWorldMatrix = function () {
  29247. return this._worldTransform;
  29248. };
  29249. Bone.prototype.getInvertedAbsoluteTransform = function () {
  29250. return this._invertedAbsoluteTransform;
  29251. };
  29252. Bone.prototype.getAbsoluteTransform = function () {
  29253. return this._absoluteTransform;
  29254. };
  29255. // Methods
  29256. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  29257. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  29258. this._baseMatrix = matrix.clone();
  29259. this._matrix = matrix.clone();
  29260. this._skeleton._markAsDirty();
  29261. if (updateDifferenceMatrix) {
  29262. this._updateDifferenceMatrix();
  29263. }
  29264. };
  29265. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  29266. if (!rootMatrix) {
  29267. rootMatrix = this._baseMatrix;
  29268. }
  29269. if (this._parent) {
  29270. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29271. }
  29272. else {
  29273. this._absoluteTransform.copyFrom(rootMatrix);
  29274. }
  29275. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  29276. for (var index = 0; index < this.children.length; index++) {
  29277. this.children[index]._updateDifferenceMatrix();
  29278. }
  29279. };
  29280. Bone.prototype.markAsDirty = function () {
  29281. this._currentRenderId++;
  29282. this._skeleton._markAsDirty();
  29283. };
  29284. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  29285. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29286. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  29287. // all animation may be coming from a library skeleton, so may need to create animation
  29288. if (this.animations.length === 0) {
  29289. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  29290. this.animations[0].setKeys([]);
  29291. }
  29292. // get animation info / verify there is such a range from the source bone
  29293. var sourceRange = source.animations[0].getRange(rangeName);
  29294. if (!sourceRange) {
  29295. return false;
  29296. }
  29297. var from = sourceRange.from;
  29298. var to = sourceRange.to;
  29299. var sourceKeys = source.animations[0].getKeys();
  29300. // rescaling prep
  29301. var sourceBoneLength = source.length;
  29302. var sourceParent = source.getParent();
  29303. var parent = this.getParent();
  29304. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  29305. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  29306. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  29307. var destKeys = this.animations[0].getKeys();
  29308. // loop vars declaration
  29309. var orig;
  29310. var origTranslation;
  29311. var mat;
  29312. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  29313. orig = sourceKeys[key];
  29314. if (orig.frame >= from && orig.frame <= to) {
  29315. if (rescaleAsRequired) {
  29316. mat = orig.value.clone();
  29317. // scale based on parent ratio, when bone has parent
  29318. if (parentScalingReqd) {
  29319. origTranslation = mat.getTranslation();
  29320. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  29321. }
  29322. else if (dimensionsScalingReqd) {
  29323. origTranslation = mat.getTranslation();
  29324. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  29325. }
  29326. else {
  29327. mat = orig.value;
  29328. }
  29329. }
  29330. else {
  29331. mat = orig.value;
  29332. }
  29333. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  29334. }
  29335. }
  29336. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  29337. return true;
  29338. };
  29339. return Bone;
  29340. }(BABYLON.Node));
  29341. BABYLON.Bone = Bone;
  29342. })(BABYLON || (BABYLON = {}));
  29343. var BABYLON;
  29344. (function (BABYLON) {
  29345. var Skeleton = (function () {
  29346. function Skeleton(name, id, scene) {
  29347. this.name = name;
  29348. this.id = id;
  29349. this.bones = new Array();
  29350. this.needInitialSkinMatrix = false;
  29351. this._isDirty = true;
  29352. this._meshesWithPoseMatrix = new Array();
  29353. this._identity = BABYLON.Matrix.Identity();
  29354. this._ranges = {};
  29355. this.bones = [];
  29356. this._scene = scene;
  29357. scene.skeletons.push(this);
  29358. //make sure it will recalculate the matrix next time prepare is called.
  29359. this._isDirty = true;
  29360. }
  29361. // Members
  29362. Skeleton.prototype.getTransformMatrices = function (mesh) {
  29363. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  29364. return mesh._bonesTransformMatrices;
  29365. }
  29366. return this._transformMatrices;
  29367. };
  29368. Skeleton.prototype.getScene = function () {
  29369. return this._scene;
  29370. };
  29371. // Methods
  29372. /**
  29373. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29374. */
  29375. Skeleton.prototype.toString = function (fullDetails) {
  29376. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  29377. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29378. if (fullDetails) {
  29379. ret += ", Ranges: {";
  29380. var first = true;
  29381. for (var name_1 in this._ranges) {
  29382. if (first) {
  29383. ret += ", ";
  29384. first = false;
  29385. }
  29386. ret += name_1;
  29387. }
  29388. ret += "}";
  29389. }
  29390. return ret;
  29391. };
  29392. /**
  29393. * Get bone's index searching by name
  29394. * @param {string} name is bone's name to search for
  29395. * @return {number} Indice of the bone. Returns -1 if not found
  29396. */
  29397. Skeleton.prototype.getBoneIndexByName = function (name) {
  29398. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  29399. if (this.bones[boneIndex].name === name) {
  29400. return boneIndex;
  29401. }
  29402. }
  29403. return -1;
  29404. };
  29405. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  29406. // check name not already in use
  29407. if (!this._ranges[name]) {
  29408. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  29409. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29410. if (this.bones[i].animations[0]) {
  29411. this.bones[i].animations[0].createRange(name, from, to);
  29412. }
  29413. }
  29414. }
  29415. };
  29416. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  29417. if (deleteFrames === void 0) { deleteFrames = true; }
  29418. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29419. if (this.bones[i].animations[0]) {
  29420. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  29421. }
  29422. }
  29423. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29424. };
  29425. Skeleton.prototype.getAnimationRange = function (name) {
  29426. return this._ranges[name];
  29427. };
  29428. /**
  29429. * Returns as an Array, all AnimationRanges defined on this skeleton
  29430. */
  29431. Skeleton.prototype.getAnimationRanges = function () {
  29432. var animationRanges = [];
  29433. var name;
  29434. var i = 0;
  29435. for (name in this._ranges) {
  29436. animationRanges[i] = this._ranges[name];
  29437. i++;
  29438. }
  29439. return animationRanges;
  29440. };
  29441. /**
  29442. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  29443. */
  29444. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  29445. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29446. if (this._ranges[name] || !source.getAnimationRange(name)) {
  29447. return false;
  29448. }
  29449. var ret = true;
  29450. var frameOffset = this._getHighestAnimationFrame() + 1;
  29451. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  29452. var boneDict = {};
  29453. var sourceBones = source.bones;
  29454. var nBones;
  29455. var i;
  29456. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  29457. boneDict[sourceBones[i].name] = sourceBones[i];
  29458. }
  29459. if (this.bones.length !== sourceBones.length) {
  29460. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  29461. ret = false;
  29462. }
  29463. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  29464. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  29465. var boneName = this.bones[i].name;
  29466. var sourceBone = boneDict[boneName];
  29467. if (sourceBone) {
  29468. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  29469. }
  29470. else {
  29471. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  29472. ret = false;
  29473. }
  29474. }
  29475. // do not call createAnimationRange(), since it also is done to bones, which was already done
  29476. var range = source.getAnimationRange(name);
  29477. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  29478. return ret;
  29479. };
  29480. Skeleton.prototype.returnToRest = function () {
  29481. for (var index = 0; index < this.bones.length; index++) {
  29482. this.bones[index].returnToRest();
  29483. }
  29484. };
  29485. Skeleton.prototype._getHighestAnimationFrame = function () {
  29486. var ret = 0;
  29487. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29488. if (this.bones[i].animations[0]) {
  29489. var highest = this.bones[i].animations[0].getHighestFrame();
  29490. if (ret < highest) {
  29491. ret = highest;
  29492. }
  29493. }
  29494. }
  29495. return ret;
  29496. };
  29497. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  29498. var range = this.getAnimationRange(name);
  29499. if (!range) {
  29500. return null;
  29501. }
  29502. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  29503. };
  29504. Skeleton.prototype._markAsDirty = function () {
  29505. this._isDirty = true;
  29506. };
  29507. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  29508. this._meshesWithPoseMatrix.push(mesh);
  29509. };
  29510. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  29511. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  29512. if (index > -1) {
  29513. this._meshesWithPoseMatrix.splice(index, 1);
  29514. }
  29515. };
  29516. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  29517. for (var index = 0; index < this.bones.length; index++) {
  29518. var bone = this.bones[index];
  29519. var parentBone = bone.getParent();
  29520. if (parentBone) {
  29521. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  29522. }
  29523. else {
  29524. if (initialSkinMatrix) {
  29525. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  29526. }
  29527. else {
  29528. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  29529. }
  29530. }
  29531. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  29532. }
  29533. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  29534. };
  29535. Skeleton.prototype.prepare = function () {
  29536. if (!this._isDirty) {
  29537. return;
  29538. }
  29539. if (this.needInitialSkinMatrix) {
  29540. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  29541. var mesh = this._meshesWithPoseMatrix[index];
  29542. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  29543. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29544. }
  29545. var poseMatrix = mesh.getPoseMatrix();
  29546. // Prepare bones
  29547. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  29548. var bone = this.bones[boneIndex];
  29549. if (!bone.getParent()) {
  29550. var matrix = bone.getBaseMatrix();
  29551. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  29552. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  29553. }
  29554. }
  29555. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  29556. }
  29557. }
  29558. else {
  29559. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  29560. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29561. }
  29562. this._computeTransformMatrices(this._transformMatrices, null);
  29563. }
  29564. this._isDirty = false;
  29565. this._scene._activeBones.addCount(this.bones.length, false);
  29566. };
  29567. Skeleton.prototype.getAnimatables = function () {
  29568. if (!this._animatables || this._animatables.length !== this.bones.length) {
  29569. this._animatables = [];
  29570. for (var index = 0; index < this.bones.length; index++) {
  29571. this._animatables.push(this.bones[index]);
  29572. }
  29573. }
  29574. return this._animatables;
  29575. };
  29576. Skeleton.prototype.clone = function (name, id) {
  29577. var result = new Skeleton(name, id || name, this._scene);
  29578. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29579. for (var index = 0; index < this.bones.length; index++) {
  29580. var source = this.bones[index];
  29581. var parentBone = null;
  29582. if (source.getParent()) {
  29583. var parentIndex = this.bones.indexOf(source.getParent());
  29584. parentBone = result.bones[parentIndex];
  29585. }
  29586. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  29587. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  29588. }
  29589. if (this._ranges) {
  29590. result._ranges = {};
  29591. for (var rangeName in this._ranges) {
  29592. result._ranges[rangeName] = this._ranges[rangeName].clone();
  29593. }
  29594. }
  29595. this._isDirty = true;
  29596. return result;
  29597. };
  29598. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  29599. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  29600. this.bones.forEach(function (bone) {
  29601. bone.animations.forEach(function (animation) {
  29602. animation.enableBlending = true;
  29603. animation.blendingSpeed = blendingSpeed;
  29604. });
  29605. });
  29606. };
  29607. Skeleton.prototype.dispose = function () {
  29608. this._meshesWithPoseMatrix = [];
  29609. // Animations
  29610. this.getScene().stopAnimation(this);
  29611. // Remove from scene
  29612. this.getScene().removeSkeleton(this);
  29613. };
  29614. Skeleton.prototype.serialize = function () {
  29615. var serializationObject = {};
  29616. serializationObject.name = this.name;
  29617. serializationObject.id = this.id;
  29618. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  29619. serializationObject.bones = [];
  29620. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29621. for (var index = 0; index < this.bones.length; index++) {
  29622. var bone = this.bones[index];
  29623. var serializedBone = {
  29624. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  29625. name: bone.name,
  29626. matrix: bone.getLocalMatrix().toArray(),
  29627. rest: bone.getRestPose().toArray()
  29628. };
  29629. serializationObject.bones.push(serializedBone);
  29630. if (bone.length) {
  29631. serializedBone.length = bone.length;
  29632. }
  29633. if (bone.animations && bone.animations.length > 0) {
  29634. serializedBone.animation = bone.animations[0].serialize();
  29635. }
  29636. serializationObject.ranges = [];
  29637. for (var name in this._ranges) {
  29638. var range = {};
  29639. range.name = name;
  29640. range.from = this._ranges[name].from;
  29641. range.to = this._ranges[name].to;
  29642. serializationObject.ranges.push(range);
  29643. }
  29644. }
  29645. return serializationObject;
  29646. };
  29647. Skeleton.Parse = function (parsedSkeleton, scene) {
  29648. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  29649. if (parsedSkeleton.dimensionsAtRest) {
  29650. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  29651. }
  29652. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  29653. var index;
  29654. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  29655. var parsedBone = parsedSkeleton.bones[index];
  29656. var parentBone = null;
  29657. if (parsedBone.parentBoneIndex > -1) {
  29658. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  29659. }
  29660. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  29661. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  29662. if (parsedBone.length) {
  29663. bone.length = parsedBone.length;
  29664. }
  29665. if (parsedBone.animation) {
  29666. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  29667. }
  29668. }
  29669. // placed after bones, so createAnimationRange can cascade down
  29670. if (parsedSkeleton.ranges) {
  29671. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  29672. var data = parsedSkeleton.ranges[index];
  29673. skeleton.createAnimationRange(data.name, data.from, data.to);
  29674. }
  29675. }
  29676. return skeleton;
  29677. };
  29678. return Skeleton;
  29679. }());
  29680. BABYLON.Skeleton = Skeleton;
  29681. })(BABYLON || (BABYLON = {}));
  29682. var BABYLON;
  29683. (function (BABYLON) {
  29684. var PostProcess = (function () {
  29685. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  29686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  29687. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  29688. this.name = name;
  29689. this.width = -1;
  29690. this.height = -1;
  29691. /*
  29692. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  29693. Can only be used on a single postprocess or on the last one of a chain.
  29694. */
  29695. this.enablePixelPerfectMode = false;
  29696. this._reusable = false;
  29697. this._textures = new BABYLON.SmartArray(2);
  29698. this._currentRenderTextureInd = 0;
  29699. this._scaleRatio = new BABYLON.Vector2(1, 1);
  29700. // Events
  29701. /**
  29702. * An event triggered when the postprocess is activated.
  29703. * @type {BABYLON.Observable}
  29704. */
  29705. this.onActivateObservable = new BABYLON.Observable();
  29706. /**
  29707. * An event triggered when the postprocess changes its size.
  29708. * @type {BABYLON.Observable}
  29709. */
  29710. this.onSizeChangedObservable = new BABYLON.Observable();
  29711. /**
  29712. * An event triggered when the postprocess applies its effect.
  29713. * @type {BABYLON.Observable}
  29714. */
  29715. this.onApplyObservable = new BABYLON.Observable();
  29716. /**
  29717. * An event triggered before rendering the postprocess
  29718. * @type {BABYLON.Observable}
  29719. */
  29720. this.onBeforeRenderObservable = new BABYLON.Observable();
  29721. /**
  29722. * An event triggered after rendering the postprocess
  29723. * @type {BABYLON.Observable}
  29724. */
  29725. this.onAfterRenderObservable = new BABYLON.Observable();
  29726. if (camera != null) {
  29727. this._camera = camera;
  29728. this._scene = camera.getScene();
  29729. camera.attachPostProcess(this);
  29730. this._engine = this._scene.getEngine();
  29731. }
  29732. else {
  29733. this._engine = engine;
  29734. }
  29735. this._options = options;
  29736. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  29737. this._reusable = reusable || false;
  29738. this._textureType = textureType;
  29739. this._samplers = samplers || [];
  29740. this._samplers.push("textureSampler");
  29741. this._fragmentUrl = fragmentUrl;
  29742. this._parameters = parameters || [];
  29743. this._parameters.push("scale");
  29744. this.updateEffect(defines);
  29745. }
  29746. Object.defineProperty(PostProcess.prototype, "onActivate", {
  29747. set: function (callback) {
  29748. if (this._onActivateObserver) {
  29749. this.onActivateObservable.remove(this._onActivateObserver);
  29750. }
  29751. this._onActivateObserver = this.onActivateObservable.add(callback);
  29752. },
  29753. enumerable: true,
  29754. configurable: true
  29755. });
  29756. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  29757. set: function (callback) {
  29758. if (this._onSizeChangedObserver) {
  29759. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  29760. }
  29761. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  29762. },
  29763. enumerable: true,
  29764. configurable: true
  29765. });
  29766. Object.defineProperty(PostProcess.prototype, "onApply", {
  29767. set: function (callback) {
  29768. if (this._onApplyObserver) {
  29769. this.onApplyObservable.remove(this._onApplyObserver);
  29770. }
  29771. this._onApplyObserver = this.onApplyObservable.add(callback);
  29772. },
  29773. enumerable: true,
  29774. configurable: true
  29775. });
  29776. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  29777. set: function (callback) {
  29778. if (this._onBeforeRenderObserver) {
  29779. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29780. }
  29781. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29782. },
  29783. enumerable: true,
  29784. configurable: true
  29785. });
  29786. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  29787. set: function (callback) {
  29788. if (this._onAfterRenderObserver) {
  29789. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29790. }
  29791. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29792. },
  29793. enumerable: true,
  29794. configurable: true
  29795. });
  29796. PostProcess.prototype.updateEffect = function (defines) {
  29797. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  29798. };
  29799. PostProcess.prototype.isReusable = function () {
  29800. return this._reusable;
  29801. };
  29802. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  29803. PostProcess.prototype.markTextureDirty = function () {
  29804. this.width = -1;
  29805. };
  29806. PostProcess.prototype.activate = function (camera, sourceTexture) {
  29807. camera = camera || this._camera;
  29808. var scene = camera.getScene();
  29809. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  29810. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  29811. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  29812. var desiredWidth = this._options.width || requiredWidth;
  29813. var desiredHeight = this._options.height || requiredHeight;
  29814. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  29815. if (!this._options.width) {
  29816. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  29817. }
  29818. if (!this._options.height) {
  29819. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  29820. }
  29821. }
  29822. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  29823. if (this._textures.length > 0) {
  29824. for (var i = 0; i < this._textures.length; i++) {
  29825. this._engine._releaseTexture(this._textures.data[i]);
  29826. }
  29827. this._textures.reset();
  29828. }
  29829. this.width = desiredWidth;
  29830. this.height = desiredHeight;
  29831. var textureSize = { width: this.width, height: this.height };
  29832. var textureOptions = {
  29833. generateMipMaps: false,
  29834. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  29835. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  29836. samplingMode: this.renderTargetSamplingMode,
  29837. type: this._textureType
  29838. };
  29839. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29840. if (this._reusable) {
  29841. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29842. }
  29843. this.onSizeChangedObservable.notifyObservers(this);
  29844. }
  29845. if (this.enablePixelPerfectMode) {
  29846. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  29847. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  29848. }
  29849. else {
  29850. this._scaleRatio.copyFromFloats(1, 1);
  29851. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  29852. }
  29853. this.onActivateObservable.notifyObservers(camera);
  29854. // Clear
  29855. if (this.clearColor) {
  29856. this._engine.clear(this.clearColor, true, true, true);
  29857. }
  29858. else {
  29859. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  29860. }
  29861. if (this._reusable) {
  29862. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  29863. }
  29864. };
  29865. Object.defineProperty(PostProcess.prototype, "isSupported", {
  29866. get: function () {
  29867. return this._effect.isSupported;
  29868. },
  29869. enumerable: true,
  29870. configurable: true
  29871. });
  29872. PostProcess.prototype.apply = function () {
  29873. // Check
  29874. if (!this._effect.isReady())
  29875. return null;
  29876. // States
  29877. this._engine.enableEffect(this._effect);
  29878. this._engine.setState(false);
  29879. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29880. this._engine.setDepthBuffer(false);
  29881. this._engine.setDepthWrite(false);
  29882. // Texture
  29883. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  29884. // Parameters
  29885. this._effect.setVector2("scale", this._scaleRatio);
  29886. this.onApplyObservable.notifyObservers(this._effect);
  29887. return this._effect;
  29888. };
  29889. PostProcess.prototype.dispose = function (camera) {
  29890. camera = camera || this._camera;
  29891. if (this._textures.length > 0) {
  29892. for (var i = 0; i < this._textures.length; i++) {
  29893. this._engine._releaseTexture(this._textures.data[i]);
  29894. }
  29895. this._textures.reset();
  29896. }
  29897. if (!camera) {
  29898. return;
  29899. }
  29900. camera.detachPostProcess(this);
  29901. var index = camera._postProcesses.indexOf(this);
  29902. if (index === 0 && camera._postProcesses.length > 0) {
  29903. this._camera._postProcesses[0].markTextureDirty();
  29904. }
  29905. this.onActivateObservable.clear();
  29906. this.onAfterRenderObservable.clear();
  29907. this.onApplyObservable.clear();
  29908. this.onBeforeRenderObservable.clear();
  29909. this.onSizeChangedObservable.clear();
  29910. };
  29911. return PostProcess;
  29912. }());
  29913. BABYLON.PostProcess = PostProcess;
  29914. })(BABYLON || (BABYLON = {}));
  29915. var BABYLON;
  29916. (function (BABYLON) {
  29917. var PostProcessManager = (function () {
  29918. function PostProcessManager(scene) {
  29919. this._vertexBuffers = {};
  29920. this._scene = scene;
  29921. }
  29922. PostProcessManager.prototype._prepareBuffers = function () {
  29923. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29924. return;
  29925. }
  29926. // VBO
  29927. var vertices = [];
  29928. vertices.push(1, 1);
  29929. vertices.push(-1, 1);
  29930. vertices.push(-1, -1);
  29931. vertices.push(1, -1);
  29932. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29933. // Indices
  29934. var indices = [];
  29935. indices.push(0);
  29936. indices.push(1);
  29937. indices.push(2);
  29938. indices.push(0);
  29939. indices.push(2);
  29940. indices.push(3);
  29941. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29942. };
  29943. // Methods
  29944. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  29945. var postProcesses = this._scene.activeCamera._postProcesses;
  29946. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29947. return false;
  29948. }
  29949. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  29950. return true;
  29951. };
  29952. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29953. var engine = this._scene.getEngine();
  29954. for (var index = 0; index < postProcesses.length; index++) {
  29955. if (index < postProcesses.length - 1) {
  29956. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29957. }
  29958. else {
  29959. if (targetTexture) {
  29960. engine.bindFramebuffer(targetTexture);
  29961. }
  29962. else {
  29963. engine.restoreDefaultFramebuffer();
  29964. }
  29965. }
  29966. var pp = postProcesses[index];
  29967. var effect = pp.apply();
  29968. if (effect) {
  29969. pp.onBeforeRenderObservable.notifyObservers(effect);
  29970. // VBOs
  29971. this._prepareBuffers();
  29972. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29973. // Draw order
  29974. engine.draw(true, 0, 6);
  29975. pp.onAfterRenderObservable.notifyObservers(effect);
  29976. }
  29977. }
  29978. // Restore depth buffer
  29979. engine.setDepthBuffer(true);
  29980. engine.setDepthWrite(true);
  29981. };
  29982. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29983. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29984. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29985. return;
  29986. }
  29987. var engine = this._scene.getEngine();
  29988. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29989. if (index < len - 1) {
  29990. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29991. }
  29992. else {
  29993. if (targetTexture) {
  29994. engine.bindFramebuffer(targetTexture, faceIndex);
  29995. }
  29996. else {
  29997. engine.restoreDefaultFramebuffer();
  29998. }
  29999. }
  30000. if (doNotPresent) {
  30001. break;
  30002. }
  30003. var pp = postProcesses[index];
  30004. var effect = pp.apply();
  30005. if (effect) {
  30006. pp.onBeforeRenderObservable.notifyObservers(effect);
  30007. // VBOs
  30008. this._prepareBuffers();
  30009. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30010. // Draw order
  30011. engine.draw(true, 0, 6);
  30012. pp.onAfterRenderObservable.notifyObservers(effect);
  30013. }
  30014. }
  30015. // Restore depth buffer
  30016. engine.setDepthBuffer(true);
  30017. engine.setDepthWrite(true);
  30018. };
  30019. PostProcessManager.prototype.dispose = function () {
  30020. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30021. if (buffer) {
  30022. buffer.dispose();
  30023. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30024. }
  30025. if (this._indexBuffer) {
  30026. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30027. this._indexBuffer = null;
  30028. }
  30029. };
  30030. return PostProcessManager;
  30031. }());
  30032. BABYLON.PostProcessManager = PostProcessManager;
  30033. })(BABYLON || (BABYLON = {}));
  30034. var BABYLON;
  30035. (function (BABYLON) {
  30036. var PassPostProcess = (function (_super) {
  30037. __extends(PassPostProcess, _super);
  30038. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  30039. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  30040. }
  30041. return PassPostProcess;
  30042. }(BABYLON.PostProcess));
  30043. BABYLON.PassPostProcess = PassPostProcess;
  30044. })(BABYLON || (BABYLON = {}));
  30045. var BABYLON;
  30046. (function (BABYLON) {
  30047. /**
  30048. * This is a holder class for the physics joint created by the physics plugin.
  30049. * It holds a set of functions to control the underlying joint.
  30050. */
  30051. var PhysicsJoint = (function () {
  30052. function PhysicsJoint(type, jointData) {
  30053. this.type = type;
  30054. this.jointData = jointData;
  30055. jointData.nativeParams = jointData.nativeParams || {};
  30056. }
  30057. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  30058. get: function () {
  30059. return this._physicsJoint;
  30060. },
  30061. set: function (newJoint) {
  30062. if (this._physicsJoint) {
  30063. }
  30064. this._physicsJoint = newJoint;
  30065. },
  30066. enumerable: true,
  30067. configurable: true
  30068. });
  30069. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  30070. set: function (physicsPlugin) {
  30071. this._physicsPlugin = physicsPlugin;
  30072. },
  30073. enumerable: true,
  30074. configurable: true
  30075. });
  30076. /**
  30077. * Execute a function that is physics-plugin specific.
  30078. * @param {Function} func the function that will be executed.
  30079. * It accepts two parameters: the physics world and the physics joint.
  30080. */
  30081. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  30082. func(this._physicsPlugin.world, this._physicsJoint);
  30083. };
  30084. //TODO check if the native joints are the same
  30085. //Joint Types
  30086. PhysicsJoint.DistanceJoint = 0;
  30087. PhysicsJoint.HingeJoint = 1;
  30088. PhysicsJoint.BallAndSocketJoint = 2;
  30089. PhysicsJoint.WheelJoint = 3;
  30090. PhysicsJoint.SliderJoint = 4;
  30091. //OIMO
  30092. PhysicsJoint.PrismaticJoint = 5;
  30093. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  30094. PhysicsJoint.UniversalJoint = 6;
  30095. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  30096. //Cannon
  30097. //Similar to a Ball-Joint. Different in params
  30098. PhysicsJoint.PointToPointJoint = 8;
  30099. //Cannon only at the moment
  30100. PhysicsJoint.SpringJoint = 9;
  30101. PhysicsJoint.LockJoint = 10;
  30102. return PhysicsJoint;
  30103. }());
  30104. BABYLON.PhysicsJoint = PhysicsJoint;
  30105. /**
  30106. * A class representing a physics distance joint.
  30107. */
  30108. var DistanceJoint = (function (_super) {
  30109. __extends(DistanceJoint, _super);
  30110. function DistanceJoint(jointData) {
  30111. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  30112. }
  30113. /**
  30114. * Update the predefined distance.
  30115. */
  30116. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  30117. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  30118. };
  30119. return DistanceJoint;
  30120. }(PhysicsJoint));
  30121. BABYLON.DistanceJoint = DistanceJoint;
  30122. var MotorEnabledJoint = (function (_super) {
  30123. __extends(MotorEnabledJoint, _super);
  30124. function MotorEnabledJoint(type, jointData) {
  30125. _super.call(this, type, jointData);
  30126. }
  30127. /**
  30128. * Set the motor values.
  30129. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30130. * @param {number} force the force to apply
  30131. * @param {number} maxForce max force for this motor.
  30132. */
  30133. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  30134. this._physicsPlugin.setMotor(this, force, maxForce);
  30135. };
  30136. /**
  30137. * Set the motor's limits.
  30138. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30139. */
  30140. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30141. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30142. };
  30143. return MotorEnabledJoint;
  30144. }(PhysicsJoint));
  30145. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  30146. /**
  30147. * This class represents a single hinge physics joint
  30148. */
  30149. var HingeJoint = (function (_super) {
  30150. __extends(HingeJoint, _super);
  30151. function HingeJoint(jointData) {
  30152. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  30153. }
  30154. /**
  30155. * Set the motor values.
  30156. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30157. * @param {number} force the force to apply
  30158. * @param {number} maxForce max force for this motor.
  30159. */
  30160. HingeJoint.prototype.setMotor = function (force, maxForce) {
  30161. this._physicsPlugin.setMotor(this, force, maxForce);
  30162. };
  30163. /**
  30164. * Set the motor's limits.
  30165. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30166. */
  30167. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30168. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30169. };
  30170. return HingeJoint;
  30171. }(MotorEnabledJoint));
  30172. BABYLON.HingeJoint = HingeJoint;
  30173. /**
  30174. * This class represents a dual hinge physics joint (same as wheel joint)
  30175. */
  30176. var Hinge2Joint = (function (_super) {
  30177. __extends(Hinge2Joint, _super);
  30178. function Hinge2Joint(jointData) {
  30179. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  30180. }
  30181. /**
  30182. * Set the motor values.
  30183. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30184. * @param {number} force the force to apply
  30185. * @param {number} maxForce max force for this motor.
  30186. * @param {motorIndex} the motor's index, 0 or 1.
  30187. */
  30188. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  30189. if (motorIndex === void 0) { motorIndex = 0; }
  30190. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  30191. };
  30192. /**
  30193. * Set the motor limits.
  30194. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30195. * @param {number} upperLimit the upper limit
  30196. * @param {number} lowerLimit lower limit
  30197. * @param {motorIndex} the motor's index, 0 or 1.
  30198. */
  30199. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  30200. if (motorIndex === void 0) { motorIndex = 0; }
  30201. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  30202. };
  30203. return Hinge2Joint;
  30204. }(MotorEnabledJoint));
  30205. BABYLON.Hinge2Joint = Hinge2Joint;
  30206. })(BABYLON || (BABYLON = {}));
  30207. var BABYLON;
  30208. (function (BABYLON) {
  30209. var PhysicsImpostor = (function () {
  30210. function PhysicsImpostor(object, type, _options, _scene) {
  30211. var _this = this;
  30212. if (_options === void 0) { _options = { mass: 0 }; }
  30213. this.object = object;
  30214. this.type = type;
  30215. this._options = _options;
  30216. this._scene = _scene;
  30217. this._bodyUpdateRequired = false;
  30218. this._onBeforePhysicsStepCallbacks = new Array();
  30219. this._onAfterPhysicsStepCallbacks = new Array();
  30220. this._onPhysicsCollideCallbacks = [];
  30221. this._deltaPosition = BABYLON.Vector3.Zero();
  30222. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  30223. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  30224. /**
  30225. * this function is executed by the physics engine.
  30226. */
  30227. this.beforeStep = function () {
  30228. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  30229. //conjugate deltaRotation
  30230. if (_this._deltaRotationConjugated) {
  30231. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  30232. }
  30233. else {
  30234. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  30235. }
  30236. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  30237. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  30238. func(_this);
  30239. });
  30240. };
  30241. /**
  30242. * this function is executed by the physics engine.
  30243. */
  30244. this.afterStep = function () {
  30245. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  30246. func(_this);
  30247. });
  30248. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  30249. _this.object.position.addInPlace(_this._deltaPosition);
  30250. if (_this._deltaRotation) {
  30251. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  30252. }
  30253. };
  30254. //event and body object due to cannon's event-based architecture.
  30255. this.onCollide = function (e) {
  30256. if (!_this._onPhysicsCollideCallbacks.length)
  30257. return;
  30258. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  30259. if (otherImpostor) {
  30260. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  30261. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  30262. }).forEach(function (obj) {
  30263. obj.callback(_this, otherImpostor);
  30264. });
  30265. }
  30266. };
  30267. //sanity check!
  30268. if (!this.object) {
  30269. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  30270. return;
  30271. }
  30272. //legacy support for old syntax.
  30273. if (!this._scene && object.getScene) {
  30274. this._scene = object.getScene();
  30275. }
  30276. this._physicsEngine = this._scene.getPhysicsEngine();
  30277. if (!this._physicsEngine) {
  30278. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  30279. }
  30280. else {
  30281. //set the object's quaternion, if not set
  30282. if (!this.object.rotationQuaternion) {
  30283. if (this.object.rotation) {
  30284. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  30285. }
  30286. else {
  30287. this.object.rotationQuaternion = new BABYLON.Quaternion();
  30288. }
  30289. }
  30290. //default options params
  30291. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  30292. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  30293. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  30294. this._joints = [];
  30295. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  30296. if (!this.object.parent) {
  30297. this._init();
  30298. }
  30299. }
  30300. }
  30301. /**
  30302. * This function will completly initialize this impostor.
  30303. * It will create a new body - but only if this mesh has no parent.
  30304. * If it has, this impostor will not be used other than to define the impostor
  30305. * of the child mesh.
  30306. */
  30307. PhysicsImpostor.prototype._init = function () {
  30308. this._physicsEngine.removeImpostor(this);
  30309. this.physicsBody = null;
  30310. this._parent = this._parent || this._getPhysicsParent();
  30311. if (!this.parent) {
  30312. this._physicsEngine.addImpostor(this);
  30313. }
  30314. };
  30315. PhysicsImpostor.prototype._getPhysicsParent = function () {
  30316. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  30317. var parentMesh = this.object.parent;
  30318. return parentMesh.physicsImpostor;
  30319. }
  30320. return;
  30321. };
  30322. /**
  30323. * Should a new body be generated.
  30324. */
  30325. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  30326. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  30327. };
  30328. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  30329. this.forceUpdate();
  30330. };
  30331. /**
  30332. * Force a regeneration of this or the parent's impostor's body.
  30333. * Use under cautious - This will remove all joints already implemented.
  30334. */
  30335. PhysicsImpostor.prototype.forceUpdate = function () {
  30336. this._init();
  30337. if (this.parent) {
  30338. this.parent.forceUpdate();
  30339. }
  30340. };
  30341. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  30342. /*public get mesh(): AbstractMesh {
  30343. return this._mesh;
  30344. }*/
  30345. /**
  30346. * Gets the body that holds this impostor. Either its own, or its parent.
  30347. */
  30348. get: function () {
  30349. return this._parent ? this._parent.physicsBody : this._physicsBody;
  30350. },
  30351. /**
  30352. * Set the physics body. Used mainly by the physics engine/plugin
  30353. */
  30354. set: function (physicsBody) {
  30355. if (this._physicsBody) {
  30356. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  30357. }
  30358. this._physicsBody = physicsBody;
  30359. this.resetUpdateFlags();
  30360. },
  30361. enumerable: true,
  30362. configurable: true
  30363. });
  30364. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  30365. get: function () {
  30366. return this._parent;
  30367. },
  30368. set: function (value) {
  30369. this._parent = value;
  30370. },
  30371. enumerable: true,
  30372. configurable: true
  30373. });
  30374. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  30375. this._bodyUpdateRequired = false;
  30376. };
  30377. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  30378. if (this.object.getBoundingInfo) {
  30379. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  30380. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  30381. }
  30382. else {
  30383. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  30384. }
  30385. };
  30386. PhysicsImpostor.prototype.getObjectCenter = function () {
  30387. if (this.object.getBoundingInfo) {
  30388. return this.object.getBoundingInfo().boundingBox.center;
  30389. }
  30390. else {
  30391. return this.object.position;
  30392. }
  30393. };
  30394. /**
  30395. * Get a specific parametes from the options parameter.
  30396. */
  30397. PhysicsImpostor.prototype.getParam = function (paramName) {
  30398. return this._options[paramName];
  30399. };
  30400. /**
  30401. * Sets a specific parameter in the options given to the physics plugin
  30402. */
  30403. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  30404. this._options[paramName] = value;
  30405. this._bodyUpdateRequired = true;
  30406. };
  30407. /**
  30408. * Specifically change the body's mass option. Won't recreate the physics body object
  30409. */
  30410. PhysicsImpostor.prototype.setMass = function (mass) {
  30411. if (this.getParam("mass") !== mass) {
  30412. this.setParam("mass", mass);
  30413. }
  30414. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  30415. };
  30416. PhysicsImpostor.prototype.getLinearVelocity = function () {
  30417. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  30418. };
  30419. /**
  30420. * Set the body's linear velocity.
  30421. */
  30422. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  30423. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  30424. };
  30425. PhysicsImpostor.prototype.getAngularVelocity = function () {
  30426. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  30427. };
  30428. /**
  30429. * Set the body's linear velocity.
  30430. */
  30431. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  30432. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  30433. };
  30434. /**
  30435. * Execute a function with the physics plugin native code.
  30436. * Provide a function the will have two variables - the world object and the physics body object.
  30437. */
  30438. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  30439. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  30440. };
  30441. /**
  30442. * Register a function that will be executed before the physics world is stepping forward.
  30443. */
  30444. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  30445. this._onBeforePhysicsStepCallbacks.push(func);
  30446. };
  30447. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  30448. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  30449. if (index > -1) {
  30450. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  30451. }
  30452. else {
  30453. BABYLON.Tools.Warn("Function to remove was not found");
  30454. }
  30455. };
  30456. /**
  30457. * Register a function that will be executed after the physics step
  30458. */
  30459. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  30460. this._onAfterPhysicsStepCallbacks.push(func);
  30461. };
  30462. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  30463. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  30464. if (index > -1) {
  30465. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  30466. }
  30467. else {
  30468. BABYLON.Tools.Warn("Function to remove was not found");
  30469. }
  30470. };
  30471. /**
  30472. * register a function that will be executed when this impostor collides against a different body.
  30473. */
  30474. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  30475. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30476. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  30477. };
  30478. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  30479. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30480. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  30481. if (index > -1) {
  30482. this._onPhysicsCollideCallbacks.splice(index, 1);
  30483. }
  30484. else {
  30485. BABYLON.Tools.Warn("Function to remove was not found");
  30486. }
  30487. };
  30488. /**
  30489. * Apply a force
  30490. */
  30491. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  30492. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  30493. };
  30494. /**
  30495. * Apply an impulse
  30496. */
  30497. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  30498. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  30499. };
  30500. /**
  30501. * A help function to create a joint.
  30502. */
  30503. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  30504. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  30505. this.addJoint(otherImpostor, joint);
  30506. };
  30507. /**
  30508. * Add a joint to this impostor with a different impostor.
  30509. */
  30510. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  30511. this._joints.push({
  30512. otherImpostor: otherImpostor,
  30513. joint: joint
  30514. });
  30515. this._physicsEngine.addJoint(this, otherImpostor, joint);
  30516. };
  30517. /**
  30518. * Will keep this body still, in a sleep mode.
  30519. */
  30520. PhysicsImpostor.prototype.sleep = function () {
  30521. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  30522. };
  30523. /**
  30524. * Wake the body up.
  30525. */
  30526. PhysicsImpostor.prototype.wakeUp = function () {
  30527. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  30528. };
  30529. PhysicsImpostor.prototype.clone = function (newObject) {
  30530. if (!newObject)
  30531. return null;
  30532. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  30533. };
  30534. PhysicsImpostor.prototype.dispose = function () {
  30535. var _this = this;
  30536. //no dispose if no physics engine is available.
  30537. if (!this._physicsEngine) {
  30538. return;
  30539. }
  30540. this._joints.forEach(function (j) {
  30541. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  30542. });
  30543. //dispose the physics body
  30544. this._physicsEngine.removeImpostor(this);
  30545. if (this.parent) {
  30546. this.parent.forceUpdate();
  30547. }
  30548. else {
  30549. }
  30550. };
  30551. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  30552. this._deltaPosition.copyFrom(position);
  30553. };
  30554. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  30555. if (!this._deltaRotation) {
  30556. this._deltaRotation = new BABYLON.Quaternion();
  30557. }
  30558. this._deltaRotation.copyFrom(rotation);
  30559. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  30560. };
  30561. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  30562. //Impostor types
  30563. PhysicsImpostor.NoImpostor = 0;
  30564. PhysicsImpostor.SphereImpostor = 1;
  30565. PhysicsImpostor.BoxImpostor = 2;
  30566. PhysicsImpostor.PlaneImpostor = 3;
  30567. PhysicsImpostor.MeshImpostor = 4;
  30568. PhysicsImpostor.CylinderImpostor = 7;
  30569. PhysicsImpostor.ParticleImpostor = 8;
  30570. PhysicsImpostor.HeightmapImpostor = 9;
  30571. return PhysicsImpostor;
  30572. }());
  30573. BABYLON.PhysicsImpostor = PhysicsImpostor;
  30574. })(BABYLON || (BABYLON = {}));
  30575. var BABYLON;
  30576. (function (BABYLON) {
  30577. var PhysicsEngine = (function () {
  30578. function PhysicsEngine(gravity, _physicsPlugin) {
  30579. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  30580. this._physicsPlugin = _physicsPlugin;
  30581. //new methods and parameters
  30582. this._impostors = [];
  30583. this._joints = [];
  30584. if (!this._physicsPlugin.isSupported()) {
  30585. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  30586. + "Please make sure it is included.");
  30587. }
  30588. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  30589. this.setGravity(gravity);
  30590. this.setTimeStep();
  30591. }
  30592. PhysicsEngine.prototype.setGravity = function (gravity) {
  30593. this.gravity = gravity;
  30594. this._physicsPlugin.setGravity(this.gravity);
  30595. };
  30596. /**
  30597. * Set the time step of the physics engine.
  30598. * default is 1/60.
  30599. * To slow it down, enter 1/600 for example.
  30600. * To speed it up, 1/30
  30601. * @param {number} newTimeStep the new timestep to apply to this world.
  30602. */
  30603. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  30604. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  30605. this._physicsPlugin.setTimeStep(newTimeStep);
  30606. };
  30607. PhysicsEngine.prototype.dispose = function () {
  30608. this._impostors.forEach(function (impostor) {
  30609. impostor.dispose();
  30610. });
  30611. this._physicsPlugin.dispose();
  30612. };
  30613. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  30614. return this._physicsPlugin.name;
  30615. };
  30616. /**
  30617. * Adding a new impostor for the impostor tracking.
  30618. * This will be done by the impostor itself.
  30619. * @param {PhysicsImpostor} impostor the impostor to add
  30620. */
  30621. PhysicsEngine.prototype.addImpostor = function (impostor) {
  30622. impostor.uniqueId = this._impostors.push(impostor);
  30623. //if no parent, generate the body
  30624. if (!impostor.parent) {
  30625. this._physicsPlugin.generatePhysicsBody(impostor);
  30626. }
  30627. };
  30628. /**
  30629. * Remove an impostor from the engine.
  30630. * This impostor and its mesh will not longer be updated by the physics engine.
  30631. * @param {PhysicsImpostor} impostor the impostor to remove
  30632. */
  30633. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  30634. var index = this._impostors.indexOf(impostor);
  30635. if (index > -1) {
  30636. var removed = this._impostors.splice(index, 1);
  30637. //Is it needed?
  30638. if (removed.length) {
  30639. //this will also remove it from the world.
  30640. removed[0].physicsBody = null;
  30641. }
  30642. }
  30643. };
  30644. /**
  30645. * Add a joint to the physics engine
  30646. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  30647. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  30648. * @param {PhysicsJoint} the joint that will connect both impostors.
  30649. */
  30650. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  30651. var impostorJoint = {
  30652. mainImpostor: mainImpostor,
  30653. connectedImpostor: connectedImpostor,
  30654. joint: joint
  30655. };
  30656. joint.physicsPlugin = this._physicsPlugin;
  30657. this._joints.push(impostorJoint);
  30658. this._physicsPlugin.generateJoint(impostorJoint);
  30659. };
  30660. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  30661. var matchingJoints = this._joints.filter(function (impostorJoint) {
  30662. return (impostorJoint.connectedImpostor === connectedImpostor
  30663. && impostorJoint.joint === joint
  30664. && impostorJoint.mainImpostor === mainImpostor);
  30665. });
  30666. if (matchingJoints.length) {
  30667. this._physicsPlugin.removeJoint(matchingJoints[0]);
  30668. }
  30669. };
  30670. /**
  30671. * Called by the scene. no need to call it.
  30672. */
  30673. PhysicsEngine.prototype._step = function (delta) {
  30674. var _this = this;
  30675. //check if any mesh has no body / requires an update
  30676. this._impostors.forEach(function (impostor) {
  30677. if (impostor.isBodyInitRequired()) {
  30678. _this._physicsPlugin.generatePhysicsBody(impostor);
  30679. }
  30680. });
  30681. if (delta > 0.1) {
  30682. delta = 0.1;
  30683. }
  30684. else if (delta <= 0) {
  30685. delta = 1.0 / 60.0;
  30686. }
  30687. this._physicsPlugin.executeStep(delta, this._impostors);
  30688. };
  30689. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  30690. return this._physicsPlugin;
  30691. };
  30692. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  30693. for (var i = 0; i < this._impostors.length; ++i) {
  30694. if (this._impostors[i].object === object) {
  30695. return this._impostors[i];
  30696. }
  30697. }
  30698. };
  30699. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  30700. for (var i = 0; i < this._impostors.length; ++i) {
  30701. if (this._impostors[i].physicsBody === body) {
  30702. return this._impostors[i];
  30703. }
  30704. }
  30705. };
  30706. // Statics, Legacy support.
  30707. /**
  30708. * @Deprecated
  30709. *
  30710. */
  30711. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  30712. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  30713. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  30714. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  30715. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  30716. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  30717. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  30718. PhysicsEngine.CapsuleImpostor = -1;
  30719. PhysicsEngine.ConeImpostor = -1;
  30720. PhysicsEngine.ConvexHullImpostor = -1;
  30721. PhysicsEngine.Epsilon = 0.001;
  30722. return PhysicsEngine;
  30723. }());
  30724. BABYLON.PhysicsEngine = PhysicsEngine;
  30725. })(BABYLON || (BABYLON = {}));
  30726. var BABYLON;
  30727. (function (BABYLON) {
  30728. var VertexData = (function () {
  30729. function VertexData() {
  30730. }
  30731. VertexData.prototype.set = function (data, kind) {
  30732. switch (kind) {
  30733. case BABYLON.VertexBuffer.PositionKind:
  30734. this.positions = data;
  30735. break;
  30736. case BABYLON.VertexBuffer.NormalKind:
  30737. this.normals = data;
  30738. break;
  30739. case BABYLON.VertexBuffer.UVKind:
  30740. this.uvs = data;
  30741. break;
  30742. case BABYLON.VertexBuffer.UV2Kind:
  30743. this.uvs2 = data;
  30744. break;
  30745. case BABYLON.VertexBuffer.UV3Kind:
  30746. this.uvs3 = data;
  30747. break;
  30748. case BABYLON.VertexBuffer.UV4Kind:
  30749. this.uvs4 = data;
  30750. break;
  30751. case BABYLON.VertexBuffer.UV5Kind:
  30752. this.uvs5 = data;
  30753. break;
  30754. case BABYLON.VertexBuffer.UV6Kind:
  30755. this.uvs6 = data;
  30756. break;
  30757. case BABYLON.VertexBuffer.ColorKind:
  30758. this.colors = data;
  30759. break;
  30760. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30761. this.matricesIndices = data;
  30762. break;
  30763. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30764. this.matricesWeights = data;
  30765. break;
  30766. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30767. this.matricesIndicesExtra = data;
  30768. break;
  30769. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30770. this.matricesWeightsExtra = data;
  30771. break;
  30772. }
  30773. };
  30774. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30775. this._applyTo(mesh, updatable);
  30776. };
  30777. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30778. this._applyTo(geometry, updatable);
  30779. };
  30780. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30781. this._update(mesh);
  30782. };
  30783. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30784. this._update(geometry);
  30785. };
  30786. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30787. if (this.positions) {
  30788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30789. }
  30790. if (this.normals) {
  30791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30792. }
  30793. if (this.uvs) {
  30794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30795. }
  30796. if (this.uvs2) {
  30797. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30798. }
  30799. if (this.uvs3) {
  30800. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30801. }
  30802. if (this.uvs4) {
  30803. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30804. }
  30805. if (this.uvs5) {
  30806. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30807. }
  30808. if (this.uvs6) {
  30809. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30810. }
  30811. if (this.colors) {
  30812. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30813. }
  30814. if (this.matricesIndices) {
  30815. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30816. }
  30817. if (this.matricesWeights) {
  30818. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30819. }
  30820. if (this.matricesIndicesExtra) {
  30821. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30822. }
  30823. if (this.matricesWeightsExtra) {
  30824. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30825. }
  30826. if (this.indices) {
  30827. meshOrGeometry.setIndices(this.indices);
  30828. }
  30829. };
  30830. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30831. if (this.positions) {
  30832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30833. }
  30834. if (this.normals) {
  30835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30836. }
  30837. if (this.uvs) {
  30838. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30839. }
  30840. if (this.uvs2) {
  30841. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30842. }
  30843. if (this.uvs3) {
  30844. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30845. }
  30846. if (this.uvs4) {
  30847. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30848. }
  30849. if (this.uvs5) {
  30850. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30851. }
  30852. if (this.uvs6) {
  30853. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30854. }
  30855. if (this.colors) {
  30856. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30857. }
  30858. if (this.matricesIndices) {
  30859. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30860. }
  30861. if (this.matricesWeights) {
  30862. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30863. }
  30864. if (this.matricesIndicesExtra) {
  30865. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30866. }
  30867. if (this.matricesWeightsExtra) {
  30868. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30869. }
  30870. if (this.indices) {
  30871. meshOrGeometry.setIndices(this.indices);
  30872. }
  30873. };
  30874. VertexData.prototype.transform = function (matrix) {
  30875. var transformed = BABYLON.Vector3.Zero();
  30876. var index;
  30877. if (this.positions) {
  30878. var position = BABYLON.Vector3.Zero();
  30879. for (index = 0; index < this.positions.length; index += 3) {
  30880. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30881. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30882. this.positions[index] = transformed.x;
  30883. this.positions[index + 1] = transformed.y;
  30884. this.positions[index + 2] = transformed.z;
  30885. }
  30886. }
  30887. if (this.normals) {
  30888. var normal = BABYLON.Vector3.Zero();
  30889. for (index = 0; index < this.normals.length; index += 3) {
  30890. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30891. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30892. this.normals[index] = transformed.x;
  30893. this.normals[index + 1] = transformed.y;
  30894. this.normals[index + 2] = transformed.z;
  30895. }
  30896. }
  30897. };
  30898. VertexData.prototype.merge = function (other) {
  30899. if (other.indices) {
  30900. if (!this.indices) {
  30901. this.indices = [];
  30902. }
  30903. var offset = this.positions ? this.positions.length / 3 : 0;
  30904. for (var index = 0; index < other.indices.length; index++) {
  30905. //TODO check type - if Int32Array!
  30906. this.indices.push(other.indices[index] + offset);
  30907. }
  30908. }
  30909. this.positions = this._mergeElement(this.positions, other.positions);
  30910. this.normals = this._mergeElement(this.normals, other.normals);
  30911. this.uvs = this._mergeElement(this.uvs, other.uvs);
  30912. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  30913. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  30914. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  30915. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  30916. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  30917. this.colors = this._mergeElement(this.colors, other.colors);
  30918. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  30919. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  30920. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  30921. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  30922. };
  30923. VertexData.prototype._mergeElement = function (source, other) {
  30924. if (!other)
  30925. return source;
  30926. if (!source)
  30927. return other;
  30928. var len = other.length + source.length;
  30929. var isSrcTypedArray = source instanceof Float32Array;
  30930. var isOthTypedArray = other instanceof Float32Array;
  30931. // use non-loop method when the source is Float32Array
  30932. if (isSrcTypedArray) {
  30933. var ret32 = new Float32Array(len);
  30934. ret32.set(source);
  30935. ret32.set(other, source.length);
  30936. return ret32;
  30937. }
  30938. else if (!isOthTypedArray) {
  30939. return source.concat(other);
  30940. }
  30941. else {
  30942. var ret = source.slice(0); // copy source to a separate array
  30943. for (var i = 0, len = other.length; i < len; i++) {
  30944. ret.push(other[i]);
  30945. }
  30946. return ret;
  30947. }
  30948. };
  30949. VertexData.prototype.serialize = function () {
  30950. var serializationObject = this.serialize();
  30951. if (this.positions) {
  30952. serializationObject.positions = this.positions;
  30953. }
  30954. if (this.normals) {
  30955. serializationObject.normals = this.normals;
  30956. }
  30957. if (this.uvs) {
  30958. serializationObject.uvs = this.uvs;
  30959. }
  30960. if (this.uvs2) {
  30961. serializationObject.uvs2 = this.uvs2;
  30962. }
  30963. if (this.uvs3) {
  30964. serializationObject.uvs3 = this.uvs3;
  30965. }
  30966. if (this.uvs4) {
  30967. serializationObject.uvs4 = this.uvs4;
  30968. }
  30969. if (this.uvs5) {
  30970. serializationObject.uvs5 = this.uvs5;
  30971. }
  30972. if (this.uvs6) {
  30973. serializationObject.uvs6 = this.uvs6;
  30974. }
  30975. if (this.colors) {
  30976. serializationObject.colors = this.colors;
  30977. }
  30978. if (this.matricesIndices) {
  30979. serializationObject.matricesIndices = this.matricesIndices;
  30980. serializationObject.matricesIndices._isExpanded = true;
  30981. }
  30982. if (this.matricesWeights) {
  30983. serializationObject.matricesWeights = this.matricesWeights;
  30984. }
  30985. if (this.matricesIndicesExtra) {
  30986. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30987. serializationObject.matricesIndicesExtra._isExpanded = true;
  30988. }
  30989. if (this.matricesWeightsExtra) {
  30990. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30991. }
  30992. serializationObject.indices = this.indices;
  30993. return serializationObject;
  30994. };
  30995. // Statics
  30996. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  30997. return VertexData._ExtractFrom(mesh, copyWhenShared);
  30998. };
  30999. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  31000. return VertexData._ExtractFrom(geometry, copyWhenShared);
  31001. };
  31002. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  31003. var result = new VertexData();
  31004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31005. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  31006. }
  31007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31008. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  31009. }
  31010. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31011. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  31012. }
  31013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31014. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  31015. }
  31016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31017. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  31018. }
  31019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31020. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  31021. }
  31022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31023. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  31024. }
  31025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31026. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  31027. }
  31028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31029. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  31030. }
  31031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31032. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  31033. }
  31034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31035. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  31036. }
  31037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  31038. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  31039. }
  31040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  31041. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  31042. }
  31043. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  31044. return result;
  31045. };
  31046. VertexData.CreateRibbon = function (options) {
  31047. var pathArray = options.pathArray;
  31048. var closeArray = options.closeArray || false;
  31049. var closePath = options.closePath || false;
  31050. var invertUV = options.invertUV || false;
  31051. var defaultOffset = Math.floor(pathArray[0].length / 2);
  31052. var offset = options.offset || defaultOffset;
  31053. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  31054. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31055. var positions = [];
  31056. var indices = [];
  31057. var normals = [];
  31058. var uvs = [];
  31059. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  31060. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  31061. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  31062. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  31063. var minlg; // minimal length among all paths from pathArray
  31064. var lg = []; // array of path lengths : nb of vertex per path
  31065. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  31066. var p; // path iterator
  31067. var i; // point iterator
  31068. var j; // point iterator
  31069. // if single path in pathArray
  31070. if (pathArray.length < 2) {
  31071. var ar1 = [];
  31072. var ar2 = [];
  31073. for (i = 0; i < pathArray[0].length - offset; i++) {
  31074. ar1.push(pathArray[0][i]);
  31075. ar2.push(pathArray[0][i + offset]);
  31076. }
  31077. pathArray = [ar1, ar2];
  31078. }
  31079. // positions and horizontal distances (u)
  31080. var idc = 0;
  31081. var closePathCorr = (closePath) ? 1 : 0;
  31082. var path;
  31083. var l;
  31084. minlg = pathArray[0].length;
  31085. var vectlg;
  31086. var dist;
  31087. for (p = 0; p < pathArray.length; p++) {
  31088. uTotalDistance[p] = 0;
  31089. us[p] = [0];
  31090. path = pathArray[p];
  31091. l = path.length;
  31092. minlg = (minlg < l) ? minlg : l;
  31093. j = 0;
  31094. while (j < l) {
  31095. positions.push(path[j].x, path[j].y, path[j].z);
  31096. if (j > 0) {
  31097. vectlg = path[j].subtract(path[j - 1]).length();
  31098. dist = vectlg + uTotalDistance[p];
  31099. us[p].push(dist);
  31100. uTotalDistance[p] = dist;
  31101. }
  31102. j++;
  31103. }
  31104. if (closePath) {
  31105. j--;
  31106. positions.push(path[0].x, path[0].y, path[0].z);
  31107. vectlg = path[j].subtract(path[0]).length();
  31108. dist = vectlg + uTotalDistance[p];
  31109. us[p].push(dist);
  31110. uTotalDistance[p] = dist;
  31111. }
  31112. lg[p] = l + closePathCorr;
  31113. idx[p] = idc;
  31114. idc += (l + closePathCorr);
  31115. }
  31116. // vertical distances (v)
  31117. var path1;
  31118. var path2;
  31119. var vertex1;
  31120. var vertex2;
  31121. for (i = 0; i < minlg + closePathCorr; i++) {
  31122. vTotalDistance[i] = 0;
  31123. vs[i] = [0];
  31124. for (p = 0; p < pathArray.length - 1; p++) {
  31125. path1 = pathArray[p];
  31126. path2 = pathArray[p + 1];
  31127. if (i === minlg) {
  31128. vertex1 = path1[0];
  31129. vertex2 = path2[0];
  31130. }
  31131. else {
  31132. vertex1 = path1[i];
  31133. vertex2 = path2[i];
  31134. }
  31135. vectlg = vertex2.subtract(vertex1).length();
  31136. dist = vectlg + vTotalDistance[i];
  31137. vs[i].push(dist);
  31138. vTotalDistance[i] = dist;
  31139. }
  31140. if (closeArray) {
  31141. path1 = pathArray[p];
  31142. path2 = pathArray[0];
  31143. if (i === minlg) {
  31144. vertex2 = path2[0];
  31145. }
  31146. vectlg = vertex2.subtract(vertex1).length();
  31147. dist = vectlg + vTotalDistance[i];
  31148. vTotalDistance[i] = dist;
  31149. }
  31150. }
  31151. // uvs
  31152. var u;
  31153. var v;
  31154. for (p = 0; p < pathArray.length; p++) {
  31155. for (i = 0; i < minlg + closePathCorr; i++) {
  31156. u = us[p][i] / uTotalDistance[p];
  31157. v = vs[i][p] / vTotalDistance[i];
  31158. if (invertUV) {
  31159. uvs.push(v, u);
  31160. }
  31161. else {
  31162. uvs.push(u, v);
  31163. }
  31164. }
  31165. }
  31166. // indices
  31167. p = 0; // path index
  31168. var pi = 0; // positions array index
  31169. var l1 = lg[p] - 1; // path1 length
  31170. var l2 = lg[p + 1] - 1; // path2 length
  31171. var min = (l1 < l2) ? l1 : l2; // current path stop index
  31172. var shft = idx[1] - idx[0]; // shift
  31173. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  31174. while (pi <= min && p < path1nb) {
  31175. // 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
  31176. indices.push(pi, pi + shft, pi + 1);
  31177. indices.push(pi + shft + 1, pi + 1, pi + shft);
  31178. pi += 1;
  31179. if (pi === min) {
  31180. p++;
  31181. if (p === lg.length - 1) {
  31182. shft = idx[0] - idx[p];
  31183. l1 = lg[p] - 1;
  31184. l2 = lg[0] - 1;
  31185. }
  31186. else {
  31187. shft = idx[p + 1] - idx[p];
  31188. l1 = lg[p] - 1;
  31189. l2 = lg[p + 1] - 1;
  31190. }
  31191. pi = idx[p];
  31192. min = (l1 < l2) ? l1 + pi : l2 + pi;
  31193. }
  31194. }
  31195. // normals
  31196. VertexData.ComputeNormals(positions, indices, normals);
  31197. if (closePath) {
  31198. var indexFirst = 0;
  31199. var indexLast = 0;
  31200. for (p = 0; p < pathArray.length; p++) {
  31201. indexFirst = idx[p] * 3;
  31202. if (p + 1 < pathArray.length) {
  31203. indexLast = (idx[p + 1] - 1) * 3;
  31204. }
  31205. else {
  31206. indexLast = normals.length - 3;
  31207. }
  31208. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  31209. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  31210. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  31211. normals[indexLast] = normals[indexFirst];
  31212. normals[indexLast + 1] = normals[indexFirst + 1];
  31213. normals[indexLast + 2] = normals[indexFirst + 2];
  31214. }
  31215. }
  31216. // sides
  31217. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31218. // Result
  31219. var vertexData = new VertexData();
  31220. vertexData.indices = indices;
  31221. vertexData.positions = positions;
  31222. vertexData.normals = normals;
  31223. vertexData.uvs = uvs;
  31224. if (closePath) {
  31225. vertexData._idx = idx;
  31226. }
  31227. return vertexData;
  31228. };
  31229. VertexData.CreateBox = function (options) {
  31230. var normalsSource = [
  31231. new BABYLON.Vector3(0, 0, 1),
  31232. new BABYLON.Vector3(0, 0, -1),
  31233. new BABYLON.Vector3(1, 0, 0),
  31234. new BABYLON.Vector3(-1, 0, 0),
  31235. new BABYLON.Vector3(0, 1, 0),
  31236. new BABYLON.Vector3(0, -1, 0)
  31237. ];
  31238. var indices = [];
  31239. var positions = [];
  31240. var normals = [];
  31241. var uvs = [];
  31242. var width = options.width || options.size || 1;
  31243. var height = options.height || options.size || 1;
  31244. var depth = options.depth || options.size || 1;
  31245. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31246. var faceUV = options.faceUV || new Array(6);
  31247. var faceColors = options.faceColors;
  31248. var colors = [];
  31249. // default face colors and UV if undefined
  31250. for (var f = 0; f < 6; f++) {
  31251. if (faceUV[f] === undefined) {
  31252. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31253. }
  31254. if (faceColors && faceColors[f] === undefined) {
  31255. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31256. }
  31257. }
  31258. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31259. // Create each face in turn.
  31260. for (var index = 0; index < normalsSource.length; index++) {
  31261. var normal = normalsSource[index];
  31262. // Get two vectors perpendicular to the face normal and to each other.
  31263. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31264. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31265. // Six indices (two triangles) per face.
  31266. var verticesLength = positions.length / 3;
  31267. indices.push(verticesLength);
  31268. indices.push(verticesLength + 1);
  31269. indices.push(verticesLength + 2);
  31270. indices.push(verticesLength);
  31271. indices.push(verticesLength + 2);
  31272. indices.push(verticesLength + 3);
  31273. // Four vertices per face.
  31274. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31275. positions.push(vertex.x, vertex.y, vertex.z);
  31276. normals.push(normal.x, normal.y, normal.z);
  31277. uvs.push(faceUV[index].z, faceUV[index].w);
  31278. if (faceColors) {
  31279. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31280. }
  31281. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31282. positions.push(vertex.x, vertex.y, vertex.z);
  31283. normals.push(normal.x, normal.y, normal.z);
  31284. uvs.push(faceUV[index].x, faceUV[index].w);
  31285. if (faceColors) {
  31286. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31287. }
  31288. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31289. positions.push(vertex.x, vertex.y, vertex.z);
  31290. normals.push(normal.x, normal.y, normal.z);
  31291. uvs.push(faceUV[index].x, faceUV[index].y);
  31292. if (faceColors) {
  31293. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31294. }
  31295. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31296. positions.push(vertex.x, vertex.y, vertex.z);
  31297. normals.push(normal.x, normal.y, normal.z);
  31298. uvs.push(faceUV[index].z, faceUV[index].y);
  31299. if (faceColors) {
  31300. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31301. }
  31302. }
  31303. // sides
  31304. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31305. // Result
  31306. var vertexData = new VertexData();
  31307. vertexData.indices = indices;
  31308. vertexData.positions = positions;
  31309. vertexData.normals = normals;
  31310. vertexData.uvs = uvs;
  31311. if (faceColors) {
  31312. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31313. vertexData.colors = totalColors;
  31314. }
  31315. return vertexData;
  31316. };
  31317. VertexData.CreateSphere = function (options) {
  31318. var segments = options.segments || 32;
  31319. var diameterX = options.diameterX || options.diameter || 1;
  31320. var diameterY = options.diameterY || options.diameter || 1;
  31321. var diameterZ = options.diameterZ || options.diameter || 1;
  31322. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31323. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31324. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31325. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31326. var totalZRotationSteps = 2 + segments;
  31327. var totalYRotationSteps = 2 * totalZRotationSteps;
  31328. var indices = [];
  31329. var positions = [];
  31330. var normals = [];
  31331. var uvs = [];
  31332. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31333. var normalizedZ = zRotationStep / totalZRotationSteps;
  31334. var angleZ = normalizedZ * Math.PI * slice;
  31335. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31336. var normalizedY = yRotationStep / totalYRotationSteps;
  31337. var angleY = normalizedY * Math.PI * 2 * arc;
  31338. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31339. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31340. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31341. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31342. var vertex = complete.multiply(radius);
  31343. var normal = complete.divide(radius).normalize();
  31344. positions.push(vertex.x, vertex.y, vertex.z);
  31345. normals.push(normal.x, normal.y, normal.z);
  31346. uvs.push(normalizedY, normalizedZ);
  31347. }
  31348. if (zRotationStep > 0) {
  31349. var verticesCount = positions.length / 3;
  31350. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31351. indices.push((firstIndex));
  31352. indices.push((firstIndex + 1));
  31353. indices.push(firstIndex + totalYRotationSteps + 1);
  31354. indices.push((firstIndex + totalYRotationSteps + 1));
  31355. indices.push((firstIndex + 1));
  31356. indices.push((firstIndex + totalYRotationSteps + 2));
  31357. }
  31358. }
  31359. }
  31360. // Sides
  31361. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31362. // Result
  31363. var vertexData = new VertexData();
  31364. vertexData.indices = indices;
  31365. vertexData.positions = positions;
  31366. vertexData.normals = normals;
  31367. vertexData.uvs = uvs;
  31368. return vertexData;
  31369. };
  31370. // Cylinder and cone
  31371. VertexData.CreateCylinder = function (options) {
  31372. var height = options.height || 2;
  31373. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31374. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31375. var tessellation = options.tessellation || 24;
  31376. var subdivisions = options.subdivisions || 1;
  31377. var hasRings = options.hasRings;
  31378. var enclose = options.enclose;
  31379. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31380. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31381. var faceUV = options.faceUV || new Array(3);
  31382. var faceColors = options.faceColors;
  31383. // default face colors and UV if undefined
  31384. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31385. var ringNb = (hasRings) ? subdivisions : 1;
  31386. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31387. var f;
  31388. for (f = 0; f < surfaceNb; f++) {
  31389. if (faceColors && faceColors[f] === undefined) {
  31390. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31391. }
  31392. }
  31393. for (f = 0; f < surfaceNb; f++) {
  31394. if (faceUV && faceUV[f] === undefined) {
  31395. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31396. }
  31397. }
  31398. var indices = [];
  31399. var positions = [];
  31400. var normals = [];
  31401. var uvs = [];
  31402. var colors = [];
  31403. var angle_step = Math.PI * 2 * arc / tessellation;
  31404. var angle;
  31405. var h;
  31406. var radius;
  31407. var tan = (diameterBottom - diameterTop) / 2 / height;
  31408. var ringVertex = BABYLON.Vector3.Zero();
  31409. var ringNormal = BABYLON.Vector3.Zero();
  31410. var ringFirstVertex = BABYLON.Vector3.Zero();
  31411. var ringFirstNormal = BABYLON.Vector3.Zero();
  31412. var quadNormal = BABYLON.Vector3.Zero();
  31413. var Y = BABYLON.Axis.Y;
  31414. // positions, normals, uvs
  31415. var i;
  31416. var j;
  31417. var r;
  31418. var ringIdx = 1;
  31419. var s = 1; // surface index
  31420. var cs = 0;
  31421. var v = 0;
  31422. for (i = 0; i <= subdivisions; i++) {
  31423. h = i / subdivisions;
  31424. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31425. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31426. for (r = 0; r < ringIdx; r++) {
  31427. if (hasRings) {
  31428. s += r;
  31429. }
  31430. if (enclose) {
  31431. s += 2 * r;
  31432. }
  31433. for (j = 0; j <= tessellation; j++) {
  31434. angle = j * angle_step;
  31435. // position
  31436. ringVertex.x = Math.cos(-angle) * radius;
  31437. ringVertex.y = -height / 2 + h * height;
  31438. ringVertex.z = Math.sin(-angle) * radius;
  31439. // normal
  31440. if (diameterTop === 0 && i === subdivisions) {
  31441. // if no top cap, reuse former normals
  31442. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31443. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31444. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31445. }
  31446. else {
  31447. ringNormal.x = ringVertex.x;
  31448. ringNormal.z = ringVertex.z;
  31449. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31450. ringNormal.normalize();
  31451. }
  31452. // keep first ring vertex values for enclose
  31453. if (j === 0) {
  31454. ringFirstVertex.copyFrom(ringVertex);
  31455. ringFirstNormal.copyFrom(ringNormal);
  31456. }
  31457. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31458. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31459. if (hasRings) {
  31460. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31461. }
  31462. else {
  31463. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31464. }
  31465. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31466. if (faceColors) {
  31467. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31468. }
  31469. }
  31470. // if enclose, add four vertices and their dedicated normals
  31471. if (arc !== 1 && enclose) {
  31472. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31473. positions.push(0, ringVertex.y, 0);
  31474. positions.push(0, ringVertex.y, 0);
  31475. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31476. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31477. quadNormal.normalize();
  31478. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31479. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31480. quadNormal.normalize();
  31481. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31482. if (hasRings) {
  31483. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31484. }
  31485. else {
  31486. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31487. }
  31488. uvs.push(faceUV[s + 1].x, v);
  31489. uvs.push(faceUV[s + 1].z, v);
  31490. if (hasRings) {
  31491. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31492. }
  31493. else {
  31494. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31495. }
  31496. uvs.push(faceUV[s + 2].x, v);
  31497. uvs.push(faceUV[s + 2].z, v);
  31498. if (faceColors) {
  31499. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31500. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31501. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31502. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31503. }
  31504. }
  31505. if (cs !== s) {
  31506. cs = s;
  31507. }
  31508. }
  31509. }
  31510. // indices
  31511. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31512. var s;
  31513. i = 0;
  31514. for (s = 0; s < subdivisions; s++) {
  31515. for (j = 0; j < tessellation; j++) {
  31516. var i0 = i * (e + 1) + j;
  31517. var i1 = (i + 1) * (e + 1) + j;
  31518. var i2 = i * (e + 1) + (j + 1);
  31519. var i3 = (i + 1) * (e + 1) + (j + 1);
  31520. indices.push(i0, i1, i2);
  31521. indices.push(i3, i2, i1);
  31522. }
  31523. if (arc !== 1 && enclose) {
  31524. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31525. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31526. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31527. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31528. }
  31529. i = (hasRings) ? (i + 2) : (i + 1);
  31530. }
  31531. // Caps
  31532. var createCylinderCap = function (isTop) {
  31533. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31534. if (radius === 0) {
  31535. return;
  31536. }
  31537. // Cap positions, normals & uvs
  31538. var angle;
  31539. var circleVector;
  31540. var i;
  31541. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31542. var c;
  31543. if (faceColors) {
  31544. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31545. }
  31546. // cap center
  31547. var vbase = positions.length / 3;
  31548. var offset = isTop ? height / 2 : -height / 2;
  31549. var center = new BABYLON.Vector3(0, offset, 0);
  31550. positions.push(center.x, center.y, center.z);
  31551. normals.push(0, isTop ? 1 : -1, 0);
  31552. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31553. if (faceColors) {
  31554. colors.push(c.r, c.g, c.b, c.a);
  31555. }
  31556. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31557. for (i = 0; i <= tessellation; i++) {
  31558. angle = Math.PI * 2 * i * arc / tessellation;
  31559. var cos = Math.cos(-angle);
  31560. var sin = Math.sin(-angle);
  31561. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31562. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31563. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31564. normals.push(0, isTop ? 1 : -1, 0);
  31565. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31566. if (faceColors) {
  31567. colors.push(c.r, c.g, c.b, c.a);
  31568. }
  31569. }
  31570. // Cap indices
  31571. for (i = 0; i < tessellation; i++) {
  31572. if (!isTop) {
  31573. indices.push(vbase);
  31574. indices.push(vbase + (i + 1));
  31575. indices.push(vbase + (i + 2));
  31576. }
  31577. else {
  31578. indices.push(vbase);
  31579. indices.push(vbase + (i + 2));
  31580. indices.push(vbase + (i + 1));
  31581. }
  31582. }
  31583. };
  31584. // add caps to geometry
  31585. createCylinderCap(false);
  31586. createCylinderCap(true);
  31587. // Sides
  31588. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31589. var vertexData = new VertexData();
  31590. vertexData.indices = indices;
  31591. vertexData.positions = positions;
  31592. vertexData.normals = normals;
  31593. vertexData.uvs = uvs;
  31594. if (faceColors) {
  31595. vertexData.colors = colors;
  31596. }
  31597. return vertexData;
  31598. };
  31599. VertexData.CreateTorus = function (options) {
  31600. var indices = [];
  31601. var positions = [];
  31602. var normals = [];
  31603. var uvs = [];
  31604. var diameter = options.diameter || 1;
  31605. var thickness = options.thickness || 0.5;
  31606. var tessellation = options.tessellation || 16;
  31607. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31608. var stride = tessellation + 1;
  31609. for (var i = 0; i <= tessellation; i++) {
  31610. var u = i / tessellation;
  31611. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31612. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31613. for (var j = 0; j <= tessellation; j++) {
  31614. var v = 1 - j / tessellation;
  31615. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31616. var dx = Math.cos(innerAngle);
  31617. var dy = Math.sin(innerAngle);
  31618. // Create a vertex.
  31619. var normal = new BABYLON.Vector3(dx, dy, 0);
  31620. var position = normal.scale(thickness / 2);
  31621. var textureCoordinate = new BABYLON.Vector2(u, v);
  31622. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31623. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31624. positions.push(position.x, position.y, position.z);
  31625. normals.push(normal.x, normal.y, normal.z);
  31626. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31627. // And create indices for two triangles.
  31628. var nextI = (i + 1) % stride;
  31629. var nextJ = (j + 1) % stride;
  31630. indices.push(i * stride + j);
  31631. indices.push(i * stride + nextJ);
  31632. indices.push(nextI * stride + j);
  31633. indices.push(i * stride + nextJ);
  31634. indices.push(nextI * stride + nextJ);
  31635. indices.push(nextI * stride + j);
  31636. }
  31637. }
  31638. // Sides
  31639. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31640. // Result
  31641. var vertexData = new VertexData();
  31642. vertexData.indices = indices;
  31643. vertexData.positions = positions;
  31644. vertexData.normals = normals;
  31645. vertexData.uvs = uvs;
  31646. return vertexData;
  31647. };
  31648. VertexData.CreateLineSystem = function (options) {
  31649. var indices = [];
  31650. var positions = [];
  31651. var lines = options.lines;
  31652. var idx = 0;
  31653. for (var l = 0; l < lines.length; l++) {
  31654. var points = lines[l];
  31655. for (var index = 0; index < points.length; index++) {
  31656. positions.push(points[index].x, points[index].y, points[index].z);
  31657. if (index > 0) {
  31658. indices.push(idx - 1);
  31659. indices.push(idx);
  31660. }
  31661. idx++;
  31662. }
  31663. }
  31664. var vertexData = new VertexData();
  31665. vertexData.indices = indices;
  31666. vertexData.positions = positions;
  31667. return vertexData;
  31668. };
  31669. VertexData.CreateDashedLines = function (options) {
  31670. var dashSize = options.dashSize || 3;
  31671. var gapSize = options.gapSize || 1;
  31672. var dashNb = options.dashNb || 200;
  31673. var points = options.points;
  31674. var positions = new Array();
  31675. var indices = new Array();
  31676. var curvect = BABYLON.Vector3.Zero();
  31677. var lg = 0;
  31678. var nb = 0;
  31679. var shft = 0;
  31680. var dashshft = 0;
  31681. var curshft = 0;
  31682. var idx = 0;
  31683. var i = 0;
  31684. for (i = 0; i < points.length - 1; i++) {
  31685. points[i + 1].subtractToRef(points[i], curvect);
  31686. lg += curvect.length();
  31687. }
  31688. shft = lg / dashNb;
  31689. dashshft = dashSize * shft / (dashSize + gapSize);
  31690. for (i = 0; i < points.length - 1; i++) {
  31691. points[i + 1].subtractToRef(points[i], curvect);
  31692. nb = Math.floor(curvect.length() / shft);
  31693. curvect.normalize();
  31694. for (var j = 0; j < nb; j++) {
  31695. curshft = shft * j;
  31696. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31697. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31698. indices.push(idx, idx + 1);
  31699. idx += 2;
  31700. }
  31701. }
  31702. // Result
  31703. var vertexData = new VertexData();
  31704. vertexData.positions = positions;
  31705. vertexData.indices = indices;
  31706. return vertexData;
  31707. };
  31708. VertexData.CreateGround = function (options) {
  31709. var indices = [];
  31710. var positions = [];
  31711. var normals = [];
  31712. var uvs = [];
  31713. var row, col;
  31714. var width = options.width || 1;
  31715. var height = options.height || 1;
  31716. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31717. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31718. for (row = 0; row <= subdivisionsY; row++) {
  31719. for (col = 0; col <= subdivisionsX; col++) {
  31720. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31721. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31722. positions.push(position.x, position.y, position.z);
  31723. normals.push(normal.x, normal.y, normal.z);
  31724. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  31725. }
  31726. }
  31727. for (row = 0; row < subdivisionsY; row++) {
  31728. for (col = 0; col < subdivisionsX; col++) {
  31729. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31730. indices.push(col + 1 + row * (subdivisionsX + 1));
  31731. indices.push(col + row * (subdivisionsX + 1));
  31732. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31733. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31734. indices.push(col + row * (subdivisionsX + 1));
  31735. }
  31736. }
  31737. // Result
  31738. var vertexData = new VertexData();
  31739. vertexData.indices = indices;
  31740. vertexData.positions = positions;
  31741. vertexData.normals = normals;
  31742. vertexData.uvs = uvs;
  31743. return vertexData;
  31744. };
  31745. VertexData.CreateTiledGround = function (options) {
  31746. var xmin = options.xmin || -1.0;
  31747. var zmin = options.zmin || -1.0;
  31748. var xmax = options.xmax || 1.0;
  31749. var zmax = options.zmax || 1.0;
  31750. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31751. var precision = options.precision || { w: 1, h: 1 };
  31752. var indices = [];
  31753. var positions = [];
  31754. var normals = [];
  31755. var uvs = [];
  31756. var row, col, tileRow, tileCol;
  31757. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31758. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31759. precision.w = (precision.w < 1) ? 1 : precision.w;
  31760. precision.h = (precision.h < 1) ? 1 : precision.h;
  31761. var tileSize = {
  31762. 'w': (xmax - xmin) / subdivisions.w,
  31763. 'h': (zmax - zmin) / subdivisions.h
  31764. };
  31765. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31766. // Indices
  31767. var base = positions.length / 3;
  31768. var rowLength = precision.w + 1;
  31769. for (row = 0; row < precision.h; row++) {
  31770. for (col = 0; col < precision.w; col++) {
  31771. var square = [
  31772. base + col + row * rowLength,
  31773. base + (col + 1) + row * rowLength,
  31774. base + (col + 1) + (row + 1) * rowLength,
  31775. base + col + (row + 1) * rowLength
  31776. ];
  31777. indices.push(square[1]);
  31778. indices.push(square[2]);
  31779. indices.push(square[3]);
  31780. indices.push(square[0]);
  31781. indices.push(square[1]);
  31782. indices.push(square[3]);
  31783. }
  31784. }
  31785. // Position, normals and uvs
  31786. var position = BABYLON.Vector3.Zero();
  31787. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31788. for (row = 0; row <= precision.h; row++) {
  31789. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31790. for (col = 0; col <= precision.w; col++) {
  31791. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31792. position.y = 0;
  31793. positions.push(position.x, position.y, position.z);
  31794. normals.push(normal.x, normal.y, normal.z);
  31795. uvs.push(col / precision.w, row / precision.h);
  31796. }
  31797. }
  31798. }
  31799. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31800. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31801. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31802. }
  31803. }
  31804. // Result
  31805. var vertexData = new VertexData();
  31806. vertexData.indices = indices;
  31807. vertexData.positions = positions;
  31808. vertexData.normals = normals;
  31809. vertexData.uvs = uvs;
  31810. return vertexData;
  31811. };
  31812. VertexData.CreateGroundFromHeightMap = function (options) {
  31813. var indices = [];
  31814. var positions = [];
  31815. var normals = [];
  31816. var uvs = [];
  31817. var row, col;
  31818. // Vertices
  31819. for (row = 0; row <= options.subdivisions; row++) {
  31820. for (col = 0; col <= options.subdivisions; col++) {
  31821. 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));
  31822. // Compute height
  31823. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31824. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31825. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31826. var r = options.buffer[pos] / 255.0;
  31827. var g = options.buffer[pos + 1] / 255.0;
  31828. var b = options.buffer[pos + 2] / 255.0;
  31829. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31830. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31831. // Add vertex
  31832. positions.push(position.x, position.y, position.z);
  31833. normals.push(0, 0, 0);
  31834. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31835. }
  31836. }
  31837. // Indices
  31838. for (row = 0; row < options.subdivisions; row++) {
  31839. for (col = 0; col < options.subdivisions; col++) {
  31840. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31841. indices.push(col + 1 + row * (options.subdivisions + 1));
  31842. indices.push(col + row * (options.subdivisions + 1));
  31843. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31844. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31845. indices.push(col + row * (options.subdivisions + 1));
  31846. }
  31847. }
  31848. // Normals
  31849. VertexData.ComputeNormals(positions, indices, normals);
  31850. // Result
  31851. var vertexData = new VertexData();
  31852. vertexData.indices = indices;
  31853. vertexData.positions = positions;
  31854. vertexData.normals = normals;
  31855. vertexData.uvs = uvs;
  31856. return vertexData;
  31857. };
  31858. VertexData.CreatePlane = function (options) {
  31859. var indices = [];
  31860. var positions = [];
  31861. var normals = [];
  31862. var uvs = [];
  31863. var width = options.width || options.size || 1;
  31864. var height = options.height || options.size || 1;
  31865. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31866. // Vertices
  31867. var halfWidth = width / 2.0;
  31868. var halfHeight = height / 2.0;
  31869. positions.push(-halfWidth, -halfHeight, 0);
  31870. normals.push(0, 0, -1.0);
  31871. uvs.push(0.0, 0.0);
  31872. positions.push(halfWidth, -halfHeight, 0);
  31873. normals.push(0, 0, -1.0);
  31874. uvs.push(1.0, 0.0);
  31875. positions.push(halfWidth, halfHeight, 0);
  31876. normals.push(0, 0, -1.0);
  31877. uvs.push(1.0, 1.0);
  31878. positions.push(-halfWidth, halfHeight, 0);
  31879. normals.push(0, 0, -1.0);
  31880. uvs.push(0.0, 1.0);
  31881. // Indices
  31882. indices.push(0);
  31883. indices.push(1);
  31884. indices.push(2);
  31885. indices.push(0);
  31886. indices.push(2);
  31887. indices.push(3);
  31888. // Sides
  31889. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31890. // Result
  31891. var vertexData = new VertexData();
  31892. vertexData.indices = indices;
  31893. vertexData.positions = positions;
  31894. vertexData.normals = normals;
  31895. vertexData.uvs = uvs;
  31896. return vertexData;
  31897. };
  31898. VertexData.CreateDisc = function (options) {
  31899. var positions = [];
  31900. var indices = [];
  31901. var normals = [];
  31902. var uvs = [];
  31903. var radius = options.radius || 0.5;
  31904. var tessellation = options.tessellation || 64;
  31905. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31906. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31907. // positions and uvs
  31908. positions.push(0, 0, 0); // disc center first
  31909. uvs.push(0.5, 0.5);
  31910. var theta = Math.PI * 2 * arc;
  31911. var step = theta / tessellation;
  31912. for (var a = 0; a < theta; a += step) {
  31913. var x = Math.cos(a);
  31914. var y = Math.sin(a);
  31915. var u = (x + 1) / 2;
  31916. var v = (1 - y) / 2;
  31917. positions.push(radius * x, radius * y, 0);
  31918. uvs.push(u, v);
  31919. }
  31920. if (arc === 1) {
  31921. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31922. uvs.push(uvs[2], uvs[3]);
  31923. }
  31924. //indices
  31925. var vertexNb = positions.length / 3;
  31926. for (var i = 1; i < vertexNb - 1; i++) {
  31927. indices.push(i + 1, 0, i);
  31928. }
  31929. // result
  31930. VertexData.ComputeNormals(positions, indices, normals);
  31931. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31932. var vertexData = new VertexData();
  31933. vertexData.indices = indices;
  31934. vertexData.positions = positions;
  31935. vertexData.normals = normals;
  31936. vertexData.uvs = uvs;
  31937. return vertexData;
  31938. };
  31939. VertexData.CreateIcoSphere = function (options) {
  31940. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31941. var radius = options.radius || 1;
  31942. var flat = (options.flat === undefined) ? true : options.flat;
  31943. var subdivisions = options.subdivisions || 4;
  31944. var radiusX = options.radiusX || radius;
  31945. var radiusY = options.radiusY || radius;
  31946. var radiusZ = options.radiusZ || radius;
  31947. var t = (1 + Math.sqrt(5)) / 2;
  31948. // 12 vertex x,y,z
  31949. var ico_vertices = [
  31950. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31951. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31952. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31953. ];
  31954. // index of 3 vertex makes a face of icopshere
  31955. var ico_indices = [
  31956. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31957. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31958. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31959. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31960. ];
  31961. // vertex for uv have aliased position, not for UV
  31962. var vertices_unalias_id = [
  31963. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31964. // vertex alias
  31965. 0,
  31966. 2,
  31967. 3,
  31968. 3,
  31969. 3,
  31970. 4,
  31971. 7,
  31972. 8,
  31973. 9,
  31974. 9,
  31975. 10,
  31976. 11 // 23: B + 12
  31977. ];
  31978. // uv as integer step (not pixels !)
  31979. var ico_vertexuv = [
  31980. 5, 1, 3, 1, 6, 4, 0, 0,
  31981. 5, 3, 4, 2, 2, 2, 4, 0,
  31982. 2, 0, 1, 1, 6, 0, 6, 2,
  31983. // vertex alias (for same vertex on different faces)
  31984. 0, 4,
  31985. 3, 3,
  31986. 4, 4,
  31987. 3, 1,
  31988. 4, 2,
  31989. 4, 4,
  31990. 0, 2,
  31991. 1, 1,
  31992. 2, 2,
  31993. 3, 3,
  31994. 1, 3,
  31995. 2, 4 // 23: B + 12
  31996. ];
  31997. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31998. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31999. // First island of uv mapping
  32000. // v = 4h 3+ 2
  32001. // v = 3h 9+ 4
  32002. // v = 2h 9+ 5 B
  32003. // v = 1h 9 1 0
  32004. // v = 0h 3 8 7 A
  32005. // u = 0 1 2 3 4 5 6 *a
  32006. // Second island of uv mapping
  32007. // v = 4h 0+ B+ 4+
  32008. // v = 3h A+ 2+
  32009. // v = 2h 7+ 6 3+
  32010. // v = 1h 8+ 3+
  32011. // v = 0h
  32012. // u = 0 1 2 3 4 5 6 *a
  32013. // Face layout on texture UV mapping
  32014. // ============
  32015. // \ 4 /\ 16 / ======
  32016. // \ / \ / /\ 11 /
  32017. // \/ 7 \/ / \ /
  32018. // ======= / 10 \/
  32019. // /\ 17 /\ =======
  32020. // / \ / \ \ 15 /\
  32021. // / 8 \/ 12 \ \ / \
  32022. // ============ \/ 6 \
  32023. // \ 18 /\ ============
  32024. // \ / \ \ 5 /\ 0 /
  32025. // \/ 13 \ \ / \ /
  32026. // ======= \/ 1 \/
  32027. // =============
  32028. // /\ 19 /\ 2 /\
  32029. // / \ / \ / \
  32030. // / 14 \/ 9 \/ 3 \
  32031. // ===================
  32032. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  32033. var ustep = 138 / 1024;
  32034. var vstep = 239 / 1024;
  32035. var uoffset = 60 / 1024;
  32036. var voffset = 26 / 1024;
  32037. // Second island should have margin, not to touch the first island
  32038. // avoid any borderline artefact in pixel rounding
  32039. var island_u_offset = -40 / 1024;
  32040. var island_v_offset = +20 / 1024;
  32041. // face is either island 0 or 1 :
  32042. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  32043. var island = [
  32044. 0, 0, 0, 0, 1,
  32045. 0, 0, 1, 1, 0,
  32046. 0, 0, 1, 1, 0,
  32047. 0, 1, 1, 1, 0 // 15 - 19
  32048. ];
  32049. var indices = [];
  32050. var positions = [];
  32051. var normals = [];
  32052. var uvs = [];
  32053. var current_indice = 0;
  32054. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  32055. var face_vertex_pos = new Array(3);
  32056. var face_vertex_uv = new Array(3);
  32057. var v012;
  32058. for (v012 = 0; v012 < 3; v012++) {
  32059. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  32060. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  32061. }
  32062. // create all with normals
  32063. for (var face = 0; face < 20; face++) {
  32064. // 3 vertex per face
  32065. for (v012 = 0; v012 < 3; v012++) {
  32066. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  32067. var v_id = ico_indices[3 * face + v012];
  32068. // vertex have 3D position (x,y,z)
  32069. 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]);
  32070. // Normalize to get normal, then scale to radius
  32071. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  32072. // uv Coordinates from vertex ID
  32073. 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);
  32074. }
  32075. // Subdivide the face (interpolate pos, norm, uv)
  32076. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  32077. // - norm is linear interpolation of vertex corner normal
  32078. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  32079. // - uv is linear interpolation
  32080. //
  32081. // Topology is as below for sub-divide by 2
  32082. // vertex shown as v0,v1,v2
  32083. // interp index is i1 to progress in range [v0,v1[
  32084. // interp index is i2 to progress in range [v0,v2[
  32085. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  32086. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32087. //
  32088. //
  32089. // i2 v2
  32090. // ^ ^
  32091. // / / \
  32092. // / / \
  32093. // / / \
  32094. // / / (0,1) \
  32095. // / #---------\
  32096. // / / \ (0,0)'/ \
  32097. // / / \ / \
  32098. // / / \ / \
  32099. // / / (0,0) \ / (1,0) \
  32100. // / #---------#---------\
  32101. // v0 v1
  32102. //
  32103. // --------------------> i1
  32104. //
  32105. // interp of (i1,i2):
  32106. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32107. // along i1 : lerp(x0,x1, i1/(S-i2))
  32108. //
  32109. // centroid of triangle is needed to get help normal computation
  32110. // (c1,c2) are used for centroid location
  32111. var interp_vertex = function (i1, i2, c1, c2) {
  32112. // vertex is interpolated from
  32113. // - face_vertex_pos[0..2]
  32114. // - face_vertex_uv[0..2]
  32115. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32116. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32117. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32118. pos_interp.normalize();
  32119. var vertex_normal;
  32120. if (flat) {
  32121. // in flat mode, recalculate normal as face centroid normal
  32122. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32123. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32124. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32125. }
  32126. else {
  32127. // in smooth mode, recalculate normal from each single vertex position
  32128. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32129. }
  32130. // Vertex normal need correction due to X,Y,Z radius scaling
  32131. vertex_normal.x /= radiusX;
  32132. vertex_normal.y /= radiusY;
  32133. vertex_normal.z /= radiusZ;
  32134. vertex_normal.normalize();
  32135. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32136. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32137. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32138. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32139. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32140. uvs.push(uv_interp.x, uv_interp.y);
  32141. // push each vertex has member of a face
  32142. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32143. indices.push(current_indice);
  32144. current_indice++;
  32145. };
  32146. for (var i2 = 0; i2 < subdivisions; i2++) {
  32147. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32148. // face : (i1,i2) for /\ :
  32149. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32150. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32151. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32152. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32153. if (i1 + i2 + 1 < subdivisions) {
  32154. // face : (i1,i2)' for \/ :
  32155. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32156. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32157. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32158. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32159. }
  32160. }
  32161. }
  32162. }
  32163. // Sides
  32164. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32165. // Result
  32166. var vertexData = new VertexData();
  32167. vertexData.indices = indices;
  32168. vertexData.positions = positions;
  32169. vertexData.normals = normals;
  32170. vertexData.uvs = uvs;
  32171. return vertexData;
  32172. };
  32173. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32174. VertexData.CreatePolyhedron = function (options) {
  32175. // provided polyhedron types :
  32176. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32177. // 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)
  32178. var polyhedra = [];
  32179. 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]] };
  32180. 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]] };
  32181. polyhedra[2] = {
  32182. 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]],
  32183. 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]]
  32184. };
  32185. polyhedra[3] = {
  32186. 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]],
  32187. 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]]
  32188. };
  32189. polyhedra[4] = {
  32190. 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]],
  32191. 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]]
  32192. };
  32193. 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]] };
  32194. 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]] };
  32195. 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]] };
  32196. 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]] };
  32197. 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]] };
  32198. 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]] };
  32199. 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]] };
  32200. 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]] };
  32201. 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]] };
  32202. polyhedra[14] = {
  32203. 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]],
  32204. 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]]
  32205. };
  32206. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32207. var size = options.size;
  32208. var sizeX = options.sizeX || size || 1;
  32209. var sizeY = options.sizeY || size || 1;
  32210. var sizeZ = options.sizeZ || size || 1;
  32211. var data = options.custom || polyhedra[type];
  32212. var nbfaces = data.face.length;
  32213. var faceUV = options.faceUV || new Array(nbfaces);
  32214. var faceColors = options.faceColors;
  32215. var flat = (options.flat === undefined) ? true : options.flat;
  32216. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32217. var positions = [];
  32218. var indices = [];
  32219. var normals = [];
  32220. var uvs = [];
  32221. var colors = [];
  32222. var index = 0;
  32223. var faceIdx = 0; // face cursor in the array "indexes"
  32224. var indexes = [];
  32225. var i = 0;
  32226. var f = 0;
  32227. var u, v, ang, x, y, tmp;
  32228. // default face colors and UV if undefined
  32229. if (flat) {
  32230. for (f = 0; f < nbfaces; f++) {
  32231. if (faceColors && faceColors[f] === undefined) {
  32232. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32233. }
  32234. if (faceUV && faceUV[f] === undefined) {
  32235. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32236. }
  32237. }
  32238. }
  32239. if (!flat) {
  32240. for (i = 0; i < data.vertex.length; i++) {
  32241. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32242. uvs.push(0, 0);
  32243. }
  32244. for (f = 0; f < nbfaces; f++) {
  32245. for (i = 0; i < data.face[f].length - 2; i++) {
  32246. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32247. }
  32248. }
  32249. }
  32250. else {
  32251. for (f = 0; f < nbfaces; f++) {
  32252. var fl = data.face[f].length; // number of vertices of the current face
  32253. ang = 2 * Math.PI / fl;
  32254. x = 0.5 * Math.tan(ang / 2);
  32255. y = 0.5;
  32256. // positions, uvs, colors
  32257. for (i = 0; i < fl; i++) {
  32258. // positions
  32259. 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);
  32260. indexes.push(index);
  32261. index++;
  32262. // uvs
  32263. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32264. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32265. uvs.push(u, v);
  32266. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32267. y = x * Math.sin(ang) + y * Math.cos(ang);
  32268. x = tmp;
  32269. // colors
  32270. if (faceColors) {
  32271. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32272. }
  32273. }
  32274. // indices from indexes
  32275. for (i = 0; i < fl - 2; i++) {
  32276. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32277. }
  32278. faceIdx += fl;
  32279. }
  32280. }
  32281. VertexData.ComputeNormals(positions, indices, normals);
  32282. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32283. var vertexData = new VertexData();
  32284. vertexData.positions = positions;
  32285. vertexData.indices = indices;
  32286. vertexData.normals = normals;
  32287. vertexData.uvs = uvs;
  32288. if (faceColors && flat) {
  32289. vertexData.colors = colors;
  32290. }
  32291. return vertexData;
  32292. };
  32293. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32294. VertexData.CreateTorusKnot = function (options) {
  32295. var indices = [];
  32296. var positions = [];
  32297. var normals = [];
  32298. var uvs = [];
  32299. var radius = options.radius || 2;
  32300. var tube = options.tube || 0.5;
  32301. var radialSegments = options.radialSegments || 32;
  32302. var tubularSegments = options.tubularSegments || 32;
  32303. var p = options.p || 2;
  32304. var q = options.q || 3;
  32305. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32306. // Helper
  32307. var getPos = function (angle) {
  32308. var cu = Math.cos(angle);
  32309. var su = Math.sin(angle);
  32310. var quOverP = q / p * angle;
  32311. var cs = Math.cos(quOverP);
  32312. var tx = radius * (2 + cs) * 0.5 * cu;
  32313. var ty = radius * (2 + cs) * su * 0.5;
  32314. var tz = radius * Math.sin(quOverP) * 0.5;
  32315. return new BABYLON.Vector3(tx, ty, tz);
  32316. };
  32317. // Vertices
  32318. var i;
  32319. var j;
  32320. for (i = 0; i <= radialSegments; i++) {
  32321. var modI = i % radialSegments;
  32322. var u = modI / radialSegments * 2 * p * Math.PI;
  32323. var p1 = getPos(u);
  32324. var p2 = getPos(u + 0.01);
  32325. var tang = p2.subtract(p1);
  32326. var n = p2.add(p1);
  32327. var bitan = BABYLON.Vector3.Cross(tang, n);
  32328. n = BABYLON.Vector3.Cross(bitan, tang);
  32329. bitan.normalize();
  32330. n.normalize();
  32331. for (j = 0; j < tubularSegments; j++) {
  32332. var modJ = j % tubularSegments;
  32333. var v = modJ / tubularSegments * 2 * Math.PI;
  32334. var cx = -tube * Math.cos(v);
  32335. var cy = tube * Math.sin(v);
  32336. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32337. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32338. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32339. uvs.push(i / radialSegments);
  32340. uvs.push(j / tubularSegments);
  32341. }
  32342. }
  32343. for (i = 0; i < radialSegments; i++) {
  32344. for (j = 0; j < tubularSegments; j++) {
  32345. var jNext = (j + 1) % tubularSegments;
  32346. var a = i * tubularSegments + j;
  32347. var b = (i + 1) * tubularSegments + j;
  32348. var c = (i + 1) * tubularSegments + jNext;
  32349. var d = i * tubularSegments + jNext;
  32350. indices.push(d);
  32351. indices.push(b);
  32352. indices.push(a);
  32353. indices.push(d);
  32354. indices.push(c);
  32355. indices.push(b);
  32356. }
  32357. }
  32358. // Normals
  32359. VertexData.ComputeNormals(positions, indices, normals);
  32360. // Sides
  32361. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32362. // Result
  32363. var vertexData = new VertexData();
  32364. vertexData.indices = indices;
  32365. vertexData.positions = positions;
  32366. vertexData.normals = normals;
  32367. vertexData.uvs = uvs;
  32368. return vertexData;
  32369. };
  32370. // Tools
  32371. /**
  32372. * @param {any} - positions (number[] or Float32Array)
  32373. * @param {any} - indices (number[] or Uint16Array)
  32374. * @param {any} - normals (number[] or Float32Array)
  32375. */
  32376. VertexData.ComputeNormals = function (positions, indices, normals) {
  32377. var index = 0;
  32378. var p1p2x = 0.0;
  32379. var p1p2y = 0.0;
  32380. var p1p2z = 0.0;
  32381. var p3p2x = 0.0;
  32382. var p3p2y = 0.0;
  32383. var p3p2z = 0.0;
  32384. var faceNormalx = 0.0;
  32385. var faceNormaly = 0.0;
  32386. var faceNormalz = 0.0;
  32387. var length = 0.0;
  32388. var i1 = 0;
  32389. var i2 = 0;
  32390. var i3 = 0;
  32391. for (index = 0; index < positions.length; index++) {
  32392. normals[index] = 0.0;
  32393. }
  32394. // indice triplet = 1 face
  32395. var nbFaces = indices.length / 3;
  32396. for (index = 0; index < nbFaces; index++) {
  32397. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  32398. i2 = indices[index * 3 + 1];
  32399. i3 = indices[index * 3 + 2];
  32400. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  32401. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  32402. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  32403. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  32404. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  32405. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  32406. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  32407. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  32408. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  32409. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32410. length = (length === 0) ? 1.0 : length;
  32411. faceNormalx /= length; // normalize this normal
  32412. faceNormaly /= length;
  32413. faceNormalz /= length;
  32414. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  32415. normals[i1 * 3 + 1] += faceNormaly;
  32416. normals[i1 * 3 + 2] += faceNormalz;
  32417. normals[i2 * 3] += faceNormalx;
  32418. normals[i2 * 3 + 1] += faceNormaly;
  32419. normals[i2 * 3 + 2] += faceNormalz;
  32420. normals[i3 * 3] += faceNormalx;
  32421. normals[i3 * 3 + 1] += faceNormaly;
  32422. normals[i3 * 3 + 2] += faceNormalz;
  32423. }
  32424. // last normalization of each normal
  32425. for (index = 0; index < normals.length / 3; index++) {
  32426. faceNormalx = normals[index * 3];
  32427. faceNormaly = normals[index * 3 + 1];
  32428. faceNormalz = normals[index * 3 + 2];
  32429. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32430. length = (length === 0) ? 1.0 : length;
  32431. faceNormalx /= length;
  32432. faceNormaly /= length;
  32433. faceNormalz /= length;
  32434. normals[index * 3] = faceNormalx;
  32435. normals[index * 3 + 1] = faceNormaly;
  32436. normals[index * 3 + 2] = faceNormalz;
  32437. }
  32438. };
  32439. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  32440. var li = indices.length;
  32441. var ln = normals.length;
  32442. var i;
  32443. var n;
  32444. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32445. switch (sideOrientation) {
  32446. case BABYLON.Mesh.FRONTSIDE:
  32447. // nothing changed
  32448. break;
  32449. case BABYLON.Mesh.BACKSIDE:
  32450. var tmp;
  32451. // indices
  32452. for (i = 0; i < li; i += 3) {
  32453. tmp = indices[i];
  32454. indices[i] = indices[i + 2];
  32455. indices[i + 2] = tmp;
  32456. }
  32457. // normals
  32458. for (n = 0; n < ln; n++) {
  32459. normals[n] = -normals[n];
  32460. }
  32461. break;
  32462. case BABYLON.Mesh.DOUBLESIDE:
  32463. // positions
  32464. var lp = positions.length;
  32465. var l = lp / 3;
  32466. for (var p = 0; p < lp; p++) {
  32467. positions[lp + p] = positions[p];
  32468. }
  32469. // indices
  32470. for (i = 0; i < li; i += 3) {
  32471. indices[i + li] = indices[i + 2] + l;
  32472. indices[i + 1 + li] = indices[i + 1] + l;
  32473. indices[i + 2 + li] = indices[i] + l;
  32474. }
  32475. // normals
  32476. for (n = 0; n < ln; n++) {
  32477. normals[ln + n] = -normals[n];
  32478. }
  32479. // uvs
  32480. var lu = uvs.length;
  32481. for (var u = 0; u < lu; u++) {
  32482. uvs[u + lu] = uvs[u];
  32483. }
  32484. break;
  32485. }
  32486. };
  32487. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32488. var vertexData = new VertexData();
  32489. // positions
  32490. var positions = parsedVertexData.positions;
  32491. if (positions) {
  32492. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32493. }
  32494. // normals
  32495. var normals = parsedVertexData.normals;
  32496. if (normals) {
  32497. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32498. }
  32499. // uvs
  32500. var uvs = parsedVertexData.uvs;
  32501. if (uvs) {
  32502. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32503. }
  32504. // uv2s
  32505. var uv2s = parsedVertexData.uv2s;
  32506. if (uv2s) {
  32507. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32508. }
  32509. // uv3s
  32510. var uv3s = parsedVertexData.uv3s;
  32511. if (uv3s) {
  32512. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32513. }
  32514. // uv4s
  32515. var uv4s = parsedVertexData.uv4s;
  32516. if (uv4s) {
  32517. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32518. }
  32519. // uv5s
  32520. var uv5s = parsedVertexData.uv5s;
  32521. if (uv5s) {
  32522. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32523. }
  32524. // uv6s
  32525. var uv6s = parsedVertexData.uv6s;
  32526. if (uv6s) {
  32527. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32528. }
  32529. // colors
  32530. var colors = parsedVertexData.colors;
  32531. if (colors) {
  32532. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32533. }
  32534. // matricesIndices
  32535. var matricesIndices = parsedVertexData.matricesIndices;
  32536. if (matricesIndices) {
  32537. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32538. }
  32539. // matricesWeights
  32540. var matricesWeights = parsedVertexData.matricesWeights;
  32541. if (matricesWeights) {
  32542. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32543. }
  32544. // indices
  32545. var indices = parsedVertexData.indices;
  32546. if (indices) {
  32547. vertexData.indices = indices;
  32548. }
  32549. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32550. };
  32551. return VertexData;
  32552. }());
  32553. BABYLON.VertexData = VertexData;
  32554. })(BABYLON || (BABYLON = {}));
  32555. var BABYLON;
  32556. (function (BABYLON) {
  32557. var Tags = (function () {
  32558. function Tags() {
  32559. }
  32560. Tags.EnableFor = function (obj) {
  32561. obj._tags = obj._tags || {};
  32562. obj.hasTags = function () {
  32563. return Tags.HasTags(obj);
  32564. };
  32565. obj.addTags = function (tagsString) {
  32566. return Tags.AddTagsTo(obj, tagsString);
  32567. };
  32568. obj.removeTags = function (tagsString) {
  32569. return Tags.RemoveTagsFrom(obj, tagsString);
  32570. };
  32571. obj.matchesTagsQuery = function (tagsQuery) {
  32572. return Tags.MatchesQuery(obj, tagsQuery);
  32573. };
  32574. };
  32575. Tags.DisableFor = function (obj) {
  32576. delete obj._tags;
  32577. delete obj.hasTags;
  32578. delete obj.addTags;
  32579. delete obj.removeTags;
  32580. delete obj.matchesTagsQuery;
  32581. };
  32582. Tags.HasTags = function (obj) {
  32583. if (!obj._tags) {
  32584. return false;
  32585. }
  32586. return !BABYLON.Tools.IsEmpty(obj._tags);
  32587. };
  32588. Tags.GetTags = function (obj, asString) {
  32589. if (asString === void 0) { asString = true; }
  32590. if (!obj._tags) {
  32591. return null;
  32592. }
  32593. if (asString) {
  32594. var tagsArray = [];
  32595. for (var tag in obj._tags) {
  32596. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  32597. tagsArray.push(tag);
  32598. }
  32599. }
  32600. return tagsArray.join(" ");
  32601. }
  32602. else {
  32603. return obj._tags;
  32604. }
  32605. };
  32606. // the tags 'true' and 'false' are reserved and cannot be used as tags
  32607. // a tag cannot start with '||', '&&', and '!'
  32608. // it cannot contain whitespaces
  32609. Tags.AddTagsTo = function (obj, tagsString) {
  32610. if (!tagsString) {
  32611. return;
  32612. }
  32613. if (typeof tagsString !== "string") {
  32614. return;
  32615. }
  32616. var tags = tagsString.split(" ");
  32617. tags.forEach(function (tag, index, array) {
  32618. Tags._AddTagTo(obj, tag);
  32619. });
  32620. };
  32621. Tags._AddTagTo = function (obj, tag) {
  32622. tag = tag.trim();
  32623. if (tag === "" || tag === "true" || tag === "false") {
  32624. return;
  32625. }
  32626. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  32627. return;
  32628. }
  32629. Tags.EnableFor(obj);
  32630. obj._tags[tag] = true;
  32631. };
  32632. Tags.RemoveTagsFrom = function (obj, tagsString) {
  32633. if (!Tags.HasTags(obj)) {
  32634. return;
  32635. }
  32636. var tags = tagsString.split(" ");
  32637. for (var t in tags) {
  32638. Tags._RemoveTagFrom(obj, tags[t]);
  32639. }
  32640. };
  32641. Tags._RemoveTagFrom = function (obj, tag) {
  32642. delete obj._tags[tag];
  32643. };
  32644. Tags.MatchesQuery = function (obj, tagsQuery) {
  32645. if (tagsQuery === undefined) {
  32646. return true;
  32647. }
  32648. if (tagsQuery === "") {
  32649. return Tags.HasTags(obj);
  32650. }
  32651. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  32652. };
  32653. return Tags;
  32654. }());
  32655. BABYLON.Tags = Tags;
  32656. })(BABYLON || (BABYLON = {}));
  32657. var BABYLON;
  32658. (function (BABYLON) {
  32659. var Internals;
  32660. (function (Internals) {
  32661. var AndOrNotEvaluator = (function () {
  32662. function AndOrNotEvaluator() {
  32663. }
  32664. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  32665. if (!query.match(/\([^\(\)]*\)/g)) {
  32666. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  32667. }
  32668. else {
  32669. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  32670. // remove parenthesis
  32671. r = r.slice(1, r.length - 1);
  32672. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  32673. });
  32674. }
  32675. if (query === "true") {
  32676. return true;
  32677. }
  32678. if (query === "false") {
  32679. return false;
  32680. }
  32681. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  32682. };
  32683. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  32684. evaluateCallback = evaluateCallback || (function (r) {
  32685. return r === "true" ? true : false;
  32686. });
  32687. var result;
  32688. var or = parenthesisContent.split("||");
  32689. for (var i in or) {
  32690. if (or.hasOwnProperty(i)) {
  32691. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  32692. var and = ori.split("&&");
  32693. if (and.length > 1) {
  32694. for (var j = 0; j < and.length; ++j) {
  32695. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  32696. if (andj !== "true" && andj !== "false") {
  32697. if (andj[0] === "!") {
  32698. result = !evaluateCallback(andj.substring(1));
  32699. }
  32700. else {
  32701. result = evaluateCallback(andj);
  32702. }
  32703. }
  32704. else {
  32705. result = andj === "true" ? true : false;
  32706. }
  32707. if (!result) {
  32708. ori = "false";
  32709. break;
  32710. }
  32711. }
  32712. }
  32713. if (result || ori === "true") {
  32714. result = true;
  32715. break;
  32716. }
  32717. // result equals false (or undefined)
  32718. if (ori !== "true" && ori !== "false") {
  32719. if (ori[0] === "!") {
  32720. result = !evaluateCallback(ori.substring(1));
  32721. }
  32722. else {
  32723. result = evaluateCallback(ori);
  32724. }
  32725. }
  32726. else {
  32727. result = ori === "true" ? true : false;
  32728. }
  32729. }
  32730. }
  32731. // the whole parenthesis scope is replaced by 'true' or 'false'
  32732. return result ? "true" : "false";
  32733. };
  32734. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  32735. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  32736. // remove whitespaces
  32737. r = r.replace(/[\s]/g, function () { return ""; });
  32738. return r.length % 2 ? "!" : "";
  32739. });
  32740. booleanString = booleanString.trim();
  32741. if (booleanString === "!true") {
  32742. booleanString = "false";
  32743. }
  32744. else if (booleanString === "!false") {
  32745. booleanString = "true";
  32746. }
  32747. return booleanString;
  32748. };
  32749. return AndOrNotEvaluator;
  32750. }());
  32751. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  32752. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32753. })(BABYLON || (BABYLON = {}));
  32754. var BABYLON;
  32755. (function (BABYLON) {
  32756. var PostProcessRenderPass = (function () {
  32757. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  32758. this._enabled = true;
  32759. this._refCount = 0;
  32760. this._name = name;
  32761. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  32762. this.setRenderList(renderList);
  32763. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  32764. this._renderTexture.onAfterRenderObservable.add(afterRender);
  32765. this._scene = scene;
  32766. this._renderList = renderList;
  32767. }
  32768. // private
  32769. PostProcessRenderPass.prototype._incRefCount = function () {
  32770. if (this._refCount === 0) {
  32771. this._scene.customRenderTargets.push(this._renderTexture);
  32772. }
  32773. return ++this._refCount;
  32774. };
  32775. PostProcessRenderPass.prototype._decRefCount = function () {
  32776. this._refCount--;
  32777. if (this._refCount <= 0) {
  32778. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  32779. }
  32780. return this._refCount;
  32781. };
  32782. PostProcessRenderPass.prototype._update = function () {
  32783. this.setRenderList(this._renderList);
  32784. };
  32785. // public
  32786. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  32787. this._renderTexture.renderList = renderList;
  32788. };
  32789. PostProcessRenderPass.prototype.getRenderTexture = function () {
  32790. return this._renderTexture;
  32791. };
  32792. return PostProcessRenderPass;
  32793. }());
  32794. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  32795. })(BABYLON || (BABYLON = {}));
  32796. var BABYLON;
  32797. (function (BABYLON) {
  32798. var PostProcessRenderEffect = (function () {
  32799. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  32800. this._engine = engine;
  32801. this._name = name;
  32802. this._singleInstance = singleInstance || true;
  32803. this._getPostProcess = getPostProcess;
  32804. this._cameras = [];
  32805. this._indicesForCamera = [];
  32806. this._postProcesses = {};
  32807. this._renderPasses = {};
  32808. this._renderEffectAsPasses = {};
  32809. }
  32810. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  32811. get: function () {
  32812. for (var index in this._postProcesses) {
  32813. if (!this._postProcesses[index].isSupported) {
  32814. return false;
  32815. }
  32816. }
  32817. return true;
  32818. },
  32819. enumerable: true,
  32820. configurable: true
  32821. });
  32822. PostProcessRenderEffect.prototype._update = function () {
  32823. for (var renderPassName in this._renderPasses) {
  32824. this._renderPasses[renderPassName]._update();
  32825. }
  32826. };
  32827. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  32828. this._renderPasses[renderPass._name] = renderPass;
  32829. this._linkParameters();
  32830. };
  32831. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  32832. delete this._renderPasses[renderPass._name];
  32833. this._linkParameters();
  32834. };
  32835. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  32836. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  32837. this._linkParameters();
  32838. };
  32839. PostProcessRenderEffect.prototype.getPass = function (passName) {
  32840. for (var renderPassName in this._renderPasses) {
  32841. if (renderPassName === passName) {
  32842. return this._renderPasses[passName];
  32843. }
  32844. }
  32845. };
  32846. PostProcessRenderEffect.prototype.emptyPasses = function () {
  32847. this._renderPasses = {};
  32848. this._linkParameters();
  32849. };
  32850. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  32851. var cameraKey;
  32852. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32853. for (var i = 0; i < _cam.length; i++) {
  32854. var camera = _cam[i];
  32855. var cameraName = camera.name;
  32856. if (this._singleInstance) {
  32857. cameraKey = 0;
  32858. }
  32859. else {
  32860. cameraKey = cameraName;
  32861. }
  32862. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  32863. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  32864. if (!this._indicesForCamera[cameraName]) {
  32865. this._indicesForCamera[cameraName] = [];
  32866. }
  32867. this._indicesForCamera[cameraName].push(index);
  32868. if (this._cameras.indexOf(camera) === -1) {
  32869. this._cameras[cameraName] = camera;
  32870. }
  32871. for (var passName in this._renderPasses) {
  32872. this._renderPasses[passName]._incRefCount();
  32873. }
  32874. }
  32875. this._linkParameters();
  32876. };
  32877. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  32878. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32879. for (var i = 0; i < _cam.length; i++) {
  32880. var camera = _cam[i];
  32881. var cameraName = camera.name;
  32882. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32883. var index = this._cameras.indexOf(cameraName);
  32884. this._indicesForCamera.splice(index, 1);
  32885. this._cameras.splice(index, 1);
  32886. for (var passName in this._renderPasses) {
  32887. this._renderPasses[passName]._decRefCount();
  32888. }
  32889. }
  32890. };
  32891. PostProcessRenderEffect.prototype._enable = function (cameras) {
  32892. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32893. for (var i = 0; i < _cam.length; i++) {
  32894. var camera = _cam[i];
  32895. var cameraName = camera.name;
  32896. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  32897. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  32898. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  32899. }
  32900. }
  32901. for (var passName in this._renderPasses) {
  32902. this._renderPasses[passName]._incRefCount();
  32903. }
  32904. }
  32905. };
  32906. PostProcessRenderEffect.prototype._disable = function (cameras) {
  32907. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32908. for (var i = 0; i < _cam.length; i++) {
  32909. var camera = _cam[i];
  32910. var cameraName = camera.Name;
  32911. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32912. for (var passName in this._renderPasses) {
  32913. this._renderPasses[passName]._decRefCount();
  32914. }
  32915. }
  32916. };
  32917. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  32918. if (this._singleInstance) {
  32919. return this._postProcesses[0];
  32920. }
  32921. else {
  32922. return this._postProcesses[camera.name];
  32923. }
  32924. };
  32925. PostProcessRenderEffect.prototype._linkParameters = function () {
  32926. var _this = this;
  32927. for (var index in this._postProcesses) {
  32928. if (this.applyParameters) {
  32929. this.applyParameters(this._postProcesses[index]);
  32930. }
  32931. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  32932. _this._linkTextures(effect);
  32933. });
  32934. }
  32935. };
  32936. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  32937. for (var renderPassName in this._renderPasses) {
  32938. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  32939. }
  32940. for (var renderEffectName in this._renderEffectAsPasses) {
  32941. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  32942. }
  32943. };
  32944. return PostProcessRenderEffect;
  32945. }());
  32946. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  32947. })(BABYLON || (BABYLON = {}));
  32948. var BABYLON;
  32949. (function (BABYLON) {
  32950. var PostProcessRenderPipeline = (function () {
  32951. function PostProcessRenderPipeline(engine, name) {
  32952. this._engine = engine;
  32953. this._name = name;
  32954. this._renderEffects = {};
  32955. this._renderEffectsForIsolatedPass = {};
  32956. this._cameras = [];
  32957. }
  32958. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  32959. get: function () {
  32960. for (var renderEffectName in this._renderEffects) {
  32961. if (!this._renderEffects[renderEffectName].isSupported) {
  32962. return false;
  32963. }
  32964. }
  32965. return true;
  32966. },
  32967. enumerable: true,
  32968. configurable: true
  32969. });
  32970. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  32971. this._renderEffects[renderEffect._name] = renderEffect;
  32972. };
  32973. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  32974. var renderEffects = this._renderEffects[renderEffectName];
  32975. if (!renderEffects) {
  32976. return;
  32977. }
  32978. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32979. };
  32980. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  32981. var renderEffects = this._renderEffects[renderEffectName];
  32982. if (!renderEffects) {
  32983. return;
  32984. }
  32985. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32986. };
  32987. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  32988. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32989. var indicesToDelete = [];
  32990. var i;
  32991. for (i = 0; i < _cam.length; i++) {
  32992. var camera = _cam[i];
  32993. var cameraName = camera.name;
  32994. if (this._cameras.indexOf(camera) === -1) {
  32995. this._cameras[cameraName] = camera;
  32996. }
  32997. else if (unique) {
  32998. indicesToDelete.push(i);
  32999. }
  33000. }
  33001. for (i = 0; i < indicesToDelete.length; i++) {
  33002. cameras.splice(indicesToDelete[i], 1);
  33003. }
  33004. for (var renderEffectName in this._renderEffects) {
  33005. this._renderEffects[renderEffectName]._attachCameras(_cam);
  33006. }
  33007. };
  33008. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  33009. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33010. for (var renderEffectName in this._renderEffects) {
  33011. this._renderEffects[renderEffectName]._detachCameras(_cam);
  33012. }
  33013. for (var i = 0; i < _cam.length; i++) {
  33014. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  33015. }
  33016. };
  33017. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  33018. var _this = this;
  33019. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33020. var pass = null;
  33021. var renderEffectName;
  33022. for (renderEffectName in this._renderEffects) {
  33023. pass = this._renderEffects[renderEffectName].getPass(passName);
  33024. if (pass != null) {
  33025. break;
  33026. }
  33027. }
  33028. if (pass === null) {
  33029. return;
  33030. }
  33031. for (renderEffectName in this._renderEffects) {
  33032. this._renderEffects[renderEffectName]._disable(_cam);
  33033. }
  33034. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  33035. for (var i = 0; i < _cam.length; i++) {
  33036. var camera = _cam[i];
  33037. var cameraName = camera.name;
  33038. 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); });
  33039. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  33040. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  33041. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  33042. }
  33043. };
  33044. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  33045. var _this = this;
  33046. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33047. for (var i = 0; i < _cam.length; i++) {
  33048. var camera = _cam[i];
  33049. var cameraName = camera.name;
  33050. 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); });
  33051. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  33052. }
  33053. for (var renderEffectName in this._renderEffects) {
  33054. this._renderEffects[renderEffectName]._enable(_cam);
  33055. }
  33056. };
  33057. PostProcessRenderPipeline.prototype._update = function () {
  33058. for (var renderEffectName in this._renderEffects) {
  33059. this._renderEffects[renderEffectName]._update();
  33060. }
  33061. for (var i = 0; i < this._cameras.length; i++) {
  33062. var cameraName = this._cameras[i].name;
  33063. if (this._renderEffectsForIsolatedPass[cameraName]) {
  33064. this._renderEffectsForIsolatedPass[cameraName]._update();
  33065. }
  33066. }
  33067. };
  33068. PostProcessRenderPipeline.prototype.dispose = function () {
  33069. // Must be implemented by children
  33070. };
  33071. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  33072. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  33073. return PostProcessRenderPipeline;
  33074. }());
  33075. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  33076. })(BABYLON || (BABYLON = {}));
  33077. var BABYLON;
  33078. (function (BABYLON) {
  33079. var PostProcessRenderPipelineManager = (function () {
  33080. function PostProcessRenderPipelineManager() {
  33081. this._renderPipelines = {};
  33082. }
  33083. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  33084. this._renderPipelines[renderPipeline._name] = renderPipeline;
  33085. };
  33086. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  33087. var renderPipeline = this._renderPipelines[renderPipelineName];
  33088. if (!renderPipeline) {
  33089. return;
  33090. }
  33091. renderPipeline._attachCameras(cameras, unique);
  33092. };
  33093. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  33094. var renderPipeline = this._renderPipelines[renderPipelineName];
  33095. if (!renderPipeline) {
  33096. return;
  33097. }
  33098. renderPipeline._detachCameras(cameras);
  33099. };
  33100. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33101. var renderPipeline = this._renderPipelines[renderPipelineName];
  33102. if (!renderPipeline) {
  33103. return;
  33104. }
  33105. renderPipeline._enableEffect(renderEffectName, cameras);
  33106. };
  33107. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33108. var renderPipeline = this._renderPipelines[renderPipelineName];
  33109. if (!renderPipeline) {
  33110. return;
  33111. }
  33112. renderPipeline._disableEffect(renderEffectName, cameras);
  33113. };
  33114. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  33115. var renderPipeline = this._renderPipelines[renderPipelineName];
  33116. if (!renderPipeline) {
  33117. return;
  33118. }
  33119. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  33120. };
  33121. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  33122. var renderPipeline = this._renderPipelines[renderPipelineName];
  33123. if (!renderPipeline) {
  33124. return;
  33125. }
  33126. renderPipeline._disableDisplayOnlyPass(cameras);
  33127. };
  33128. PostProcessRenderPipelineManager.prototype.update = function () {
  33129. for (var renderPipelineName in this._renderPipelines) {
  33130. var pipeline = this._renderPipelines[renderPipelineName];
  33131. if (!pipeline.isSupported) {
  33132. pipeline.dispose();
  33133. delete this._renderPipelines[renderPipelineName];
  33134. }
  33135. else {
  33136. pipeline._update();
  33137. }
  33138. }
  33139. };
  33140. return PostProcessRenderPipelineManager;
  33141. }());
  33142. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  33143. })(BABYLON || (BABYLON = {}));
  33144. var BABYLON;
  33145. (function (BABYLON) {
  33146. var BoundingBoxRenderer = (function () {
  33147. function BoundingBoxRenderer(scene) {
  33148. this.frontColor = new BABYLON.Color3(1, 1, 1);
  33149. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  33150. this.showBackLines = true;
  33151. this.renderList = new BABYLON.SmartArray(32);
  33152. this._vertexBuffers = {};
  33153. this._scene = scene;
  33154. }
  33155. BoundingBoxRenderer.prototype._prepareRessources = function () {
  33156. if (this._colorShader) {
  33157. return;
  33158. }
  33159. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  33160. attributes: [BABYLON.VertexBuffer.PositionKind],
  33161. uniforms: ["worldViewProjection", "color"]
  33162. });
  33163. var engine = this._scene.getEngine();
  33164. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  33165. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  33166. 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]);
  33167. };
  33168. BoundingBoxRenderer.prototype.reset = function () {
  33169. this.renderList.reset();
  33170. };
  33171. BoundingBoxRenderer.prototype.render = function () {
  33172. if (this.renderList.length === 0) {
  33173. return;
  33174. }
  33175. this._prepareRessources();
  33176. if (!this._colorShader.isReady()) {
  33177. return;
  33178. }
  33179. var engine = this._scene.getEngine();
  33180. engine.setDepthWrite(false);
  33181. this._colorShader._preBind();
  33182. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  33183. var boundingBox = this.renderList.data[boundingBoxIndex];
  33184. var min = boundingBox.minimum;
  33185. var max = boundingBox.maximum;
  33186. var diff = max.subtract(min);
  33187. var median = min.add(diff.scale(0.5));
  33188. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  33189. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  33190. .multiply(boundingBox.getWorldMatrix());
  33191. // VBOs
  33192. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  33193. if (this.showBackLines) {
  33194. // Back
  33195. engine.setDepthFunctionToGreaterOrEqual();
  33196. this._scene.resetCachedMaterial();
  33197. this._colorShader.setColor4("color", this.backColor.toColor4());
  33198. this._colorShader.bind(worldMatrix);
  33199. // Draw order
  33200. engine.draw(false, 0, 24);
  33201. }
  33202. // Front
  33203. engine.setDepthFunctionToLess();
  33204. this._scene.resetCachedMaterial();
  33205. this._colorShader.setColor4("color", this.frontColor.toColor4());
  33206. this._colorShader.bind(worldMatrix);
  33207. // Draw order
  33208. engine.draw(false, 0, 24);
  33209. }
  33210. this._colorShader.unbind();
  33211. engine.setDepthFunctionToLessOrEqual();
  33212. engine.setDepthWrite(true);
  33213. };
  33214. BoundingBoxRenderer.prototype.dispose = function () {
  33215. if (!this._colorShader) {
  33216. return;
  33217. }
  33218. this._colorShader.dispose();
  33219. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33220. if (buffer) {
  33221. buffer.dispose();
  33222. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33223. }
  33224. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33225. };
  33226. return BoundingBoxRenderer;
  33227. }());
  33228. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  33229. })(BABYLON || (BABYLON = {}));
  33230. var BABYLON;
  33231. (function (BABYLON) {
  33232. var Condition = (function () {
  33233. function Condition(actionManager) {
  33234. this._actionManager = actionManager;
  33235. }
  33236. Condition.prototype.isValid = function () {
  33237. return true;
  33238. };
  33239. Condition.prototype._getProperty = function (propertyPath) {
  33240. return this._actionManager._getProperty(propertyPath);
  33241. };
  33242. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33243. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33244. };
  33245. Condition.prototype.serialize = function () {
  33246. };
  33247. Condition.prototype._serialize = function (serializedCondition) {
  33248. return {
  33249. type: 2,
  33250. children: [],
  33251. name: serializedCondition.name,
  33252. properties: serializedCondition.properties
  33253. };
  33254. };
  33255. return Condition;
  33256. }());
  33257. BABYLON.Condition = Condition;
  33258. var ValueCondition = (function (_super) {
  33259. __extends(ValueCondition, _super);
  33260. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33261. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33262. _super.call(this, actionManager);
  33263. this.propertyPath = propertyPath;
  33264. this.value = value;
  33265. this.operator = operator;
  33266. this._target = target;
  33267. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  33268. this._property = this._getProperty(this.propertyPath);
  33269. }
  33270. Object.defineProperty(ValueCondition, "IsEqual", {
  33271. get: function () {
  33272. return ValueCondition._IsEqual;
  33273. },
  33274. enumerable: true,
  33275. configurable: true
  33276. });
  33277. Object.defineProperty(ValueCondition, "IsDifferent", {
  33278. get: function () {
  33279. return ValueCondition._IsDifferent;
  33280. },
  33281. enumerable: true,
  33282. configurable: true
  33283. });
  33284. Object.defineProperty(ValueCondition, "IsGreater", {
  33285. get: function () {
  33286. return ValueCondition._IsGreater;
  33287. },
  33288. enumerable: true,
  33289. configurable: true
  33290. });
  33291. Object.defineProperty(ValueCondition, "IsLesser", {
  33292. get: function () {
  33293. return ValueCondition._IsLesser;
  33294. },
  33295. enumerable: true,
  33296. configurable: true
  33297. });
  33298. // Methods
  33299. ValueCondition.prototype.isValid = function () {
  33300. switch (this.operator) {
  33301. case ValueCondition.IsGreater:
  33302. return this._effectiveTarget[this._property] > this.value;
  33303. case ValueCondition.IsLesser:
  33304. return this._effectiveTarget[this._property] < this.value;
  33305. case ValueCondition.IsEqual:
  33306. case ValueCondition.IsDifferent:
  33307. var check;
  33308. if (this.value.equals) {
  33309. check = this.value.equals(this._effectiveTarget[this._property]);
  33310. }
  33311. else {
  33312. check = this.value === this._effectiveTarget[this._property];
  33313. }
  33314. return this.operator === ValueCondition.IsEqual ? check : !check;
  33315. }
  33316. return false;
  33317. };
  33318. ValueCondition.prototype.serialize = function () {
  33319. return this._serialize({
  33320. name: "ValueCondition",
  33321. properties: [
  33322. BABYLON.Action._GetTargetProperty(this._target),
  33323. { name: "propertyPath", value: this.propertyPath },
  33324. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33325. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33326. ]
  33327. });
  33328. };
  33329. ValueCondition.GetOperatorName = function (operator) {
  33330. switch (operator) {
  33331. case ValueCondition._IsEqual: return "IsEqual";
  33332. case ValueCondition._IsDifferent: return "IsDifferent";
  33333. case ValueCondition._IsGreater: return "IsGreater";
  33334. case ValueCondition._IsLesser: return "IsLesser";
  33335. default: return "";
  33336. }
  33337. };
  33338. // Statics
  33339. ValueCondition._IsEqual = 0;
  33340. ValueCondition._IsDifferent = 1;
  33341. ValueCondition._IsGreater = 2;
  33342. ValueCondition._IsLesser = 3;
  33343. return ValueCondition;
  33344. }(Condition));
  33345. BABYLON.ValueCondition = ValueCondition;
  33346. var PredicateCondition = (function (_super) {
  33347. __extends(PredicateCondition, _super);
  33348. function PredicateCondition(actionManager, predicate) {
  33349. _super.call(this, actionManager);
  33350. this.predicate = predicate;
  33351. }
  33352. PredicateCondition.prototype.isValid = function () {
  33353. return this.predicate();
  33354. };
  33355. return PredicateCondition;
  33356. }(Condition));
  33357. BABYLON.PredicateCondition = PredicateCondition;
  33358. var StateCondition = (function (_super) {
  33359. __extends(StateCondition, _super);
  33360. function StateCondition(actionManager, target, value) {
  33361. _super.call(this, actionManager);
  33362. this.value = value;
  33363. this._target = target;
  33364. }
  33365. // Methods
  33366. StateCondition.prototype.isValid = function () {
  33367. return this._target.state === this.value;
  33368. };
  33369. StateCondition.prototype.serialize = function () {
  33370. return this._serialize({
  33371. name: "StateCondition",
  33372. properties: [
  33373. BABYLON.Action._GetTargetProperty(this._target),
  33374. { name: "value", value: this.value }
  33375. ]
  33376. });
  33377. };
  33378. return StateCondition;
  33379. }(Condition));
  33380. BABYLON.StateCondition = StateCondition;
  33381. })(BABYLON || (BABYLON = {}));
  33382. var BABYLON;
  33383. (function (BABYLON) {
  33384. var Action = (function () {
  33385. function Action(triggerOptions, condition) {
  33386. this.triggerOptions = triggerOptions;
  33387. if (triggerOptions.parameter) {
  33388. this.trigger = triggerOptions.trigger;
  33389. this._triggerParameter = triggerOptions.parameter;
  33390. }
  33391. else {
  33392. this.trigger = triggerOptions;
  33393. }
  33394. this._nextActiveAction = this;
  33395. this._condition = condition;
  33396. }
  33397. // Methods
  33398. Action.prototype._prepare = function () {
  33399. };
  33400. Action.prototype.getTriggerParameter = function () {
  33401. return this._triggerParameter;
  33402. };
  33403. Action.prototype._executeCurrent = function (evt) {
  33404. if (this._nextActiveAction._condition) {
  33405. var condition = this._nextActiveAction._condition;
  33406. var currentRenderId = this._actionManager.getScene().getRenderId();
  33407. // We cache the current evaluation for the current frame
  33408. if (condition._evaluationId === currentRenderId) {
  33409. if (!condition._currentResult) {
  33410. return;
  33411. }
  33412. }
  33413. else {
  33414. condition._evaluationId = currentRenderId;
  33415. if (!condition.isValid()) {
  33416. condition._currentResult = false;
  33417. return;
  33418. }
  33419. condition._currentResult = true;
  33420. }
  33421. }
  33422. this._nextActiveAction.execute(evt);
  33423. this.skipToNextActiveAction();
  33424. };
  33425. Action.prototype.execute = function (evt) {
  33426. };
  33427. Action.prototype.skipToNextActiveAction = function () {
  33428. if (this._nextActiveAction._child) {
  33429. if (!this._nextActiveAction._child._actionManager) {
  33430. this._nextActiveAction._child._actionManager = this._actionManager;
  33431. }
  33432. this._nextActiveAction = this._nextActiveAction._child;
  33433. }
  33434. else {
  33435. this._nextActiveAction = this;
  33436. }
  33437. };
  33438. Action.prototype.then = function (action) {
  33439. this._child = action;
  33440. action._actionManager = this._actionManager;
  33441. action._prepare();
  33442. return action;
  33443. };
  33444. Action.prototype._getProperty = function (propertyPath) {
  33445. return this._actionManager._getProperty(propertyPath);
  33446. };
  33447. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33448. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33449. };
  33450. Action.prototype.serialize = function (parent) {
  33451. };
  33452. // Called by BABYLON.Action objects in serialize(...). Internal use
  33453. Action.prototype._serialize = function (serializedAction, parent) {
  33454. var serializationObject = {
  33455. type: 1,
  33456. children: [],
  33457. name: serializedAction.name,
  33458. properties: serializedAction.properties || []
  33459. };
  33460. // Serialize child
  33461. if (this._child) {
  33462. this._child.serialize(serializationObject);
  33463. }
  33464. // Check if "this" has a condition
  33465. if (this._condition) {
  33466. var serializedCondition = this._condition.serialize();
  33467. serializedCondition.children.push(serializationObject);
  33468. if (parent) {
  33469. parent.children.push(serializedCondition);
  33470. }
  33471. return serializedCondition;
  33472. }
  33473. if (parent) {
  33474. parent.children.push(serializationObject);
  33475. }
  33476. return serializationObject;
  33477. };
  33478. Action._SerializeValueAsString = function (value) {
  33479. if (typeof value === "number") {
  33480. return value.toString();
  33481. }
  33482. if (typeof value === "boolean") {
  33483. return value ? "true" : "false";
  33484. }
  33485. if (value instanceof BABYLON.Vector2) {
  33486. return value.x + ", " + value.y;
  33487. }
  33488. if (value instanceof BABYLON.Vector3) {
  33489. return value.x + ", " + value.y + ", " + value.z;
  33490. }
  33491. if (value instanceof BABYLON.Color3) {
  33492. return value.r + ", " + value.g + ", " + value.b;
  33493. }
  33494. if (value instanceof BABYLON.Color4) {
  33495. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33496. }
  33497. return value; // string
  33498. };
  33499. Action._GetTargetProperty = function (target) {
  33500. return {
  33501. name: "target",
  33502. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33503. : target instanceof BABYLON.Light ? "LightProperties"
  33504. : target instanceof BABYLON.Camera ? "CameraProperties"
  33505. : "SceneProperties",
  33506. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33507. };
  33508. };
  33509. return Action;
  33510. }());
  33511. BABYLON.Action = Action;
  33512. })(BABYLON || (BABYLON = {}));
  33513. var BABYLON;
  33514. (function (BABYLON) {
  33515. /**
  33516. * ActionEvent is the event beint sent when an action is triggered.
  33517. */
  33518. var ActionEvent = (function () {
  33519. /**
  33520. * @constructor
  33521. * @param source The mesh or sprite that triggered the action.
  33522. * @param pointerX The X mouse cursor position at the time of the event
  33523. * @param pointerY The Y mouse cursor position at the time of the event
  33524. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33525. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33526. */
  33527. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33528. this.source = source;
  33529. this.pointerX = pointerX;
  33530. this.pointerY = pointerY;
  33531. this.meshUnderPointer = meshUnderPointer;
  33532. this.sourceEvent = sourceEvent;
  33533. this.additionalData = additionalData;
  33534. }
  33535. /**
  33536. * Helper function to auto-create an ActionEvent from a source mesh.
  33537. * @param source The source mesh that triggered the event
  33538. * @param evt {Event} The original (browser) event
  33539. */
  33540. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33541. var scene = source.getScene();
  33542. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33543. };
  33544. /**
  33545. * Helper function to auto-create an ActionEvent from a source mesh.
  33546. * @param source The source sprite that triggered the event
  33547. * @param scene Scene associated with the sprite
  33548. * @param evt {Event} The original (browser) event
  33549. */
  33550. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33551. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33552. };
  33553. /**
  33554. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33555. * @param scene the scene where the event occurred
  33556. * @param evt {Event} The original (browser) event
  33557. */
  33558. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33559. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33560. };
  33561. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33562. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33563. };
  33564. return ActionEvent;
  33565. }());
  33566. BABYLON.ActionEvent = ActionEvent;
  33567. /**
  33568. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  33569. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  33570. */
  33571. var ActionManager = (function () {
  33572. function ActionManager(scene) {
  33573. // Members
  33574. this.actions = new Array();
  33575. this._scene = scene;
  33576. scene._actionManagers.push(this);
  33577. }
  33578. Object.defineProperty(ActionManager, "NothingTrigger", {
  33579. get: function () {
  33580. return ActionManager._NothingTrigger;
  33581. },
  33582. enumerable: true,
  33583. configurable: true
  33584. });
  33585. Object.defineProperty(ActionManager, "OnPickTrigger", {
  33586. get: function () {
  33587. return ActionManager._OnPickTrigger;
  33588. },
  33589. enumerable: true,
  33590. configurable: true
  33591. });
  33592. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  33593. get: function () {
  33594. return ActionManager._OnLeftPickTrigger;
  33595. },
  33596. enumerable: true,
  33597. configurable: true
  33598. });
  33599. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  33600. get: function () {
  33601. return ActionManager._OnRightPickTrigger;
  33602. },
  33603. enumerable: true,
  33604. configurable: true
  33605. });
  33606. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  33607. get: function () {
  33608. return ActionManager._OnCenterPickTrigger;
  33609. },
  33610. enumerable: true,
  33611. configurable: true
  33612. });
  33613. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33614. get: function () {
  33615. return ActionManager._OnPickDownTrigger;
  33616. },
  33617. enumerable: true,
  33618. configurable: true
  33619. });
  33620. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33621. get: function () {
  33622. return ActionManager._OnPickUpTrigger;
  33623. },
  33624. enumerable: true,
  33625. configurable: true
  33626. });
  33627. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33628. /// This trigger will only be raised if you also declared a OnPickDown
  33629. get: function () {
  33630. return ActionManager._OnPickOutTrigger;
  33631. },
  33632. enumerable: true,
  33633. configurable: true
  33634. });
  33635. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33636. get: function () {
  33637. return ActionManager._OnLongPressTrigger;
  33638. },
  33639. enumerable: true,
  33640. configurable: true
  33641. });
  33642. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33643. get: function () {
  33644. return ActionManager._OnPointerOverTrigger;
  33645. },
  33646. enumerable: true,
  33647. configurable: true
  33648. });
  33649. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33650. get: function () {
  33651. return ActionManager._OnPointerOutTrigger;
  33652. },
  33653. enumerable: true,
  33654. configurable: true
  33655. });
  33656. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33657. get: function () {
  33658. return ActionManager._OnEveryFrameTrigger;
  33659. },
  33660. enumerable: true,
  33661. configurable: true
  33662. });
  33663. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33664. get: function () {
  33665. return ActionManager._OnIntersectionEnterTrigger;
  33666. },
  33667. enumerable: true,
  33668. configurable: true
  33669. });
  33670. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33671. get: function () {
  33672. return ActionManager._OnIntersectionExitTrigger;
  33673. },
  33674. enumerable: true,
  33675. configurable: true
  33676. });
  33677. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33678. get: function () {
  33679. return ActionManager._OnKeyDownTrigger;
  33680. },
  33681. enumerable: true,
  33682. configurable: true
  33683. });
  33684. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33685. get: function () {
  33686. return ActionManager._OnKeyUpTrigger;
  33687. },
  33688. enumerable: true,
  33689. configurable: true
  33690. });
  33691. // Methods
  33692. ActionManager.prototype.dispose = function () {
  33693. var index = this._scene._actionManagers.indexOf(this);
  33694. if (index > -1) {
  33695. this._scene._actionManagers.splice(index, 1);
  33696. }
  33697. };
  33698. ActionManager.prototype.getScene = function () {
  33699. return this._scene;
  33700. };
  33701. /**
  33702. * Does this action manager handles actions of any of the given triggers
  33703. * @param {number[]} triggers - the triggers to be tested
  33704. * @return {boolean} whether one (or more) of the triggers is handeled
  33705. */
  33706. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  33707. for (var index = 0; index < this.actions.length; index++) {
  33708. var action = this.actions[index];
  33709. if (triggers.indexOf(action.trigger) > -1) {
  33710. return true;
  33711. }
  33712. }
  33713. return false;
  33714. };
  33715. /**
  33716. * Does this action manager handles actions of a given trigger
  33717. * @param {number} trigger - the trigger to be tested
  33718. * @return {boolean} whether the trigger is handeled
  33719. */
  33720. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33721. for (var index = 0; index < this.actions.length; index++) {
  33722. var action = this.actions[index];
  33723. if (action.trigger === trigger) {
  33724. return true;
  33725. }
  33726. }
  33727. return false;
  33728. };
  33729. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33730. /**
  33731. * Does this action manager has pointer triggers
  33732. * @return {boolean} whether or not it has pointer triggers
  33733. */
  33734. get: function () {
  33735. for (var index = 0; index < this.actions.length; index++) {
  33736. var action = this.actions[index];
  33737. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33738. return true;
  33739. }
  33740. }
  33741. return false;
  33742. },
  33743. enumerable: true,
  33744. configurable: true
  33745. });
  33746. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33747. /**
  33748. * Does this action manager has pick triggers
  33749. * @return {boolean} whether or not it has pick triggers
  33750. */
  33751. get: function () {
  33752. for (var index = 0; index < this.actions.length; index++) {
  33753. var action = this.actions[index];
  33754. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33755. return true;
  33756. }
  33757. }
  33758. return false;
  33759. },
  33760. enumerable: true,
  33761. configurable: true
  33762. });
  33763. /**
  33764. * Registers an action to this action manager
  33765. * @param {BABYLON.Action} action - the action to be registered
  33766. * @return {BABYLON.Action} the action amended (prepared) after registration
  33767. */
  33768. ActionManager.prototype.registerAction = function (action) {
  33769. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33770. if (this.getScene().actionManager !== this) {
  33771. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33772. return null;
  33773. }
  33774. }
  33775. this.actions.push(action);
  33776. action._actionManager = this;
  33777. action._prepare();
  33778. return action;
  33779. };
  33780. /**
  33781. * Process a specific trigger
  33782. * @param {number} trigger - the trigger to process
  33783. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33784. */
  33785. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33786. for (var index = 0; index < this.actions.length; index++) {
  33787. var action = this.actions[index];
  33788. if (action.trigger === trigger) {
  33789. if (trigger === ActionManager.OnKeyUpTrigger
  33790. || trigger === ActionManager.OnKeyDownTrigger) {
  33791. var parameter = action.getTriggerParameter();
  33792. if (parameter) {
  33793. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33794. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33795. if (actualkey !== parameter.toLowerCase()) {
  33796. continue;
  33797. }
  33798. }
  33799. }
  33800. action._executeCurrent(evt);
  33801. }
  33802. }
  33803. };
  33804. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33805. var properties = propertyPath.split(".");
  33806. for (var index = 0; index < properties.length - 1; index++) {
  33807. target = target[properties[index]];
  33808. }
  33809. return target;
  33810. };
  33811. ActionManager.prototype._getProperty = function (propertyPath) {
  33812. var properties = propertyPath.split(".");
  33813. return properties[properties.length - 1];
  33814. };
  33815. ActionManager.prototype.serialize = function (name) {
  33816. var root = {
  33817. children: [],
  33818. name: name,
  33819. type: 3,
  33820. properties: [] // Empty for root but required
  33821. };
  33822. for (var i = 0; i < this.actions.length; i++) {
  33823. var triggerObject = {
  33824. type: 0,
  33825. children: [],
  33826. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33827. properties: []
  33828. };
  33829. var triggerOptions = this.actions[i].triggerOptions;
  33830. if (triggerOptions && typeof triggerOptions !== "number") {
  33831. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33832. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33833. }
  33834. else {
  33835. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  33836. }
  33837. }
  33838. // Serialize child action, recursively
  33839. this.actions[i].serialize(triggerObject);
  33840. // Add serialized trigger
  33841. root.children.push(triggerObject);
  33842. }
  33843. return root;
  33844. };
  33845. ActionManager.Parse = function (parsedActions, object, scene) {
  33846. var actionManager = new BABYLON.ActionManager(scene);
  33847. if (object === null)
  33848. scene.actionManager = actionManager;
  33849. else
  33850. object.actionManager = actionManager;
  33851. // instanciate a new object
  33852. var instanciate = function (name, params) {
  33853. var newInstance = Object.create(BABYLON[name].prototype);
  33854. newInstance.constructor.apply(newInstance, params);
  33855. return newInstance;
  33856. };
  33857. var parseParameter = function (name, value, target, propertyPath) {
  33858. if (propertyPath === null) {
  33859. // String, boolean or float
  33860. var floatValue = parseFloat(value);
  33861. if (value === "true" || value === "false")
  33862. return value === "true";
  33863. else
  33864. return isNaN(floatValue) ? value : floatValue;
  33865. }
  33866. var effectiveTarget = propertyPath.split(".");
  33867. var values = value.split(",");
  33868. // Get effective Target
  33869. for (var i = 0; i < effectiveTarget.length; i++) {
  33870. target = target[effectiveTarget[i]];
  33871. }
  33872. // Return appropriate value with its type
  33873. if (typeof (target) === "boolean")
  33874. return values[0] === "true";
  33875. if (typeof (target) === "string")
  33876. return values[0];
  33877. // Parameters with multiple values such as Vector3 etc.
  33878. var split = new Array();
  33879. for (var i = 0; i < values.length; i++)
  33880. split.push(parseFloat(values[i]));
  33881. if (target instanceof BABYLON.Vector3)
  33882. return BABYLON.Vector3.FromArray(split);
  33883. if (target instanceof BABYLON.Vector4)
  33884. return BABYLON.Vector4.FromArray(split);
  33885. if (target instanceof BABYLON.Color3)
  33886. return BABYLON.Color3.FromArray(split);
  33887. if (target instanceof BABYLON.Color4)
  33888. return BABYLON.Color4.FromArray(split);
  33889. return parseFloat(values[0]);
  33890. };
  33891. // traverse graph per trigger
  33892. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33893. if (combineArray === void 0) { combineArray = null; }
  33894. if (parsedAction.detached)
  33895. return;
  33896. var parameters = new Array();
  33897. var target = null;
  33898. var propertyPath = null;
  33899. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33900. // Parameters
  33901. if (parsedAction.type === 2)
  33902. parameters.push(actionManager);
  33903. else
  33904. parameters.push(trigger);
  33905. if (combine) {
  33906. var actions = new Array();
  33907. for (var j = 0; j < parsedAction.combine.length; j++) {
  33908. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33909. }
  33910. parameters.push(actions);
  33911. }
  33912. else {
  33913. for (var i = 0; i < parsedAction.properties.length; i++) {
  33914. var value = parsedAction.properties[i].value;
  33915. var name = parsedAction.properties[i].name;
  33916. var targetType = parsedAction.properties[i].targetType;
  33917. if (name === "target")
  33918. if (targetType !== null && targetType === "SceneProperties")
  33919. value = target = scene;
  33920. else
  33921. value = target = scene.getNodeByName(value);
  33922. else if (name === "parent")
  33923. value = scene.getNodeByName(value);
  33924. else if (name === "sound")
  33925. value = scene.getSoundByName(value);
  33926. else if (name !== "propertyPath") {
  33927. if (parsedAction.type === 2 && name === "operator")
  33928. value = BABYLON.ValueCondition[value];
  33929. else
  33930. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33931. }
  33932. else {
  33933. propertyPath = value;
  33934. }
  33935. parameters.push(value);
  33936. }
  33937. }
  33938. if (combineArray === null) {
  33939. parameters.push(condition);
  33940. }
  33941. else {
  33942. parameters.push(null);
  33943. }
  33944. // If interpolate value action
  33945. if (parsedAction.name === "InterpolateValueAction") {
  33946. var param = parameters[parameters.length - 2];
  33947. parameters[parameters.length - 1] = param;
  33948. parameters[parameters.length - 2] = condition;
  33949. }
  33950. // Action or condition(s) and not CombineAction
  33951. var newAction = instanciate(parsedAction.name, parameters);
  33952. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33953. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33954. if (action)
  33955. action.then(nothing);
  33956. else
  33957. actionManager.registerAction(nothing);
  33958. action = nothing;
  33959. }
  33960. if (combineArray === null) {
  33961. if (newAction instanceof BABYLON.Condition) {
  33962. condition = newAction;
  33963. newAction = action;
  33964. }
  33965. else {
  33966. condition = null;
  33967. if (action)
  33968. action.then(newAction);
  33969. else
  33970. actionManager.registerAction(newAction);
  33971. }
  33972. }
  33973. else {
  33974. combineArray.push(newAction);
  33975. }
  33976. for (var i = 0; i < parsedAction.children.length; i++)
  33977. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33978. };
  33979. // triggers
  33980. for (var i = 0; i < parsedActions.children.length; i++) {
  33981. var triggerParams;
  33982. var trigger = parsedActions.children[i];
  33983. if (trigger.properties.length > 0) {
  33984. var param = trigger.properties[0].value;
  33985. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33986. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33987. }
  33988. else
  33989. triggerParams = BABYLON.ActionManager[trigger.name];
  33990. for (var j = 0; j < trigger.children.length; j++) {
  33991. if (!trigger.detached)
  33992. traverse(trigger.children[j], triggerParams, null, null);
  33993. }
  33994. }
  33995. };
  33996. ActionManager.GetTriggerName = function (trigger) {
  33997. switch (trigger) {
  33998. case 0: return "NothingTrigger";
  33999. case 1: return "OnPickTrigger";
  34000. case 2: return "OnLeftPickTrigger";
  34001. case 3: return "OnRightPickTrigger";
  34002. case 4: return "OnCenterPickTrigger";
  34003. case 5: return "OnPickDownTrigger";
  34004. case 6: return "OnPickUpTrigger";
  34005. case 7: return "OnLongPressTrigger";
  34006. case 8: return "OnPointerOverTrigger";
  34007. case 9: return "OnPointerOutTrigger";
  34008. case 10: return "OnEveryFrameTrigger";
  34009. case 11: return "OnIntersectionEnterTrigger";
  34010. case 12: return "OnIntersectionExitTrigger";
  34011. case 13: return "OnKeyDownTrigger";
  34012. case 14: return "OnKeyUpTrigger";
  34013. case 15: return "OnPickOutTrigger";
  34014. default: return "";
  34015. }
  34016. };
  34017. // Statics
  34018. ActionManager._NothingTrigger = 0;
  34019. ActionManager._OnPickTrigger = 1;
  34020. ActionManager._OnLeftPickTrigger = 2;
  34021. ActionManager._OnRightPickTrigger = 3;
  34022. ActionManager._OnCenterPickTrigger = 4;
  34023. ActionManager._OnPickDownTrigger = 5;
  34024. ActionManager._OnPickUpTrigger = 6;
  34025. ActionManager._OnLongPressTrigger = 7;
  34026. ActionManager._OnPointerOverTrigger = 8;
  34027. ActionManager._OnPointerOutTrigger = 9;
  34028. ActionManager._OnEveryFrameTrigger = 10;
  34029. ActionManager._OnIntersectionEnterTrigger = 11;
  34030. ActionManager._OnIntersectionExitTrigger = 12;
  34031. ActionManager._OnKeyDownTrigger = 13;
  34032. ActionManager._OnKeyUpTrigger = 14;
  34033. ActionManager._OnPickOutTrigger = 15;
  34034. ActionManager.DragMovementThreshold = 10; // in pixels
  34035. ActionManager.LongPressDelay = 500; // in milliseconds
  34036. return ActionManager;
  34037. }());
  34038. BABYLON.ActionManager = ActionManager;
  34039. })(BABYLON || (BABYLON = {}));
  34040. var BABYLON;
  34041. (function (BABYLON) {
  34042. var InterpolateValueAction = (function (_super) {
  34043. __extends(InterpolateValueAction, _super);
  34044. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  34045. if (duration === void 0) { duration = 1000; }
  34046. _super.call(this, triggerOptions, condition);
  34047. this.propertyPath = propertyPath;
  34048. this.value = value;
  34049. this.duration = duration;
  34050. this.stopOtherAnimations = stopOtherAnimations;
  34051. this.onInterpolationDone = onInterpolationDone;
  34052. this._target = this._effectiveTarget = target;
  34053. }
  34054. InterpolateValueAction.prototype._prepare = function () {
  34055. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34056. this._property = this._getProperty(this.propertyPath);
  34057. };
  34058. InterpolateValueAction.prototype.execute = function () {
  34059. var scene = this._actionManager.getScene();
  34060. var keys = [
  34061. {
  34062. frame: 0,
  34063. value: this._effectiveTarget[this._property]
  34064. }, {
  34065. frame: 100,
  34066. value: this.value
  34067. }
  34068. ];
  34069. var dataType;
  34070. if (typeof this.value === "number") {
  34071. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34072. }
  34073. else if (this.value instanceof BABYLON.Color3) {
  34074. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34075. }
  34076. else if (this.value instanceof BABYLON.Vector3) {
  34077. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34078. }
  34079. else if (this.value instanceof BABYLON.Matrix) {
  34080. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34081. }
  34082. else if (this.value instanceof BABYLON.Quaternion) {
  34083. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34084. }
  34085. else {
  34086. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34087. return;
  34088. }
  34089. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34090. animation.setKeys(keys);
  34091. if (this.stopOtherAnimations) {
  34092. scene.stopAnimation(this._effectiveTarget);
  34093. }
  34094. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34095. };
  34096. InterpolateValueAction.prototype.serialize = function (parent) {
  34097. return _super.prototype._serialize.call(this, {
  34098. name: "InterpolateValueAction",
  34099. properties: [
  34100. BABYLON.Action._GetTargetProperty(this._target),
  34101. { name: "propertyPath", value: this.propertyPath },
  34102. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34103. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34104. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34105. ]
  34106. }, parent);
  34107. };
  34108. return InterpolateValueAction;
  34109. }(BABYLON.Action));
  34110. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34111. })(BABYLON || (BABYLON = {}));
  34112. var BABYLON;
  34113. (function (BABYLON) {
  34114. var SwitchBooleanAction = (function (_super) {
  34115. __extends(SwitchBooleanAction, _super);
  34116. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34117. _super.call(this, triggerOptions, condition);
  34118. this.propertyPath = propertyPath;
  34119. this._target = this._effectiveTarget = target;
  34120. }
  34121. SwitchBooleanAction.prototype._prepare = function () {
  34122. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34123. this._property = this._getProperty(this.propertyPath);
  34124. };
  34125. SwitchBooleanAction.prototype.execute = function () {
  34126. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34127. };
  34128. SwitchBooleanAction.prototype.serialize = function (parent) {
  34129. return _super.prototype._serialize.call(this, {
  34130. name: "SwitchBooleanAction",
  34131. properties: [
  34132. BABYLON.Action._GetTargetProperty(this._target),
  34133. { name: "propertyPath", value: this.propertyPath }
  34134. ]
  34135. }, parent);
  34136. };
  34137. return SwitchBooleanAction;
  34138. }(BABYLON.Action));
  34139. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34140. var SetStateAction = (function (_super) {
  34141. __extends(SetStateAction, _super);
  34142. function SetStateAction(triggerOptions, target, value, condition) {
  34143. _super.call(this, triggerOptions, condition);
  34144. this.value = value;
  34145. this._target = target;
  34146. }
  34147. SetStateAction.prototype.execute = function () {
  34148. this._target.state = this.value;
  34149. };
  34150. SetStateAction.prototype.serialize = function (parent) {
  34151. return _super.prototype._serialize.call(this, {
  34152. name: "SetStateAction",
  34153. properties: [
  34154. BABYLON.Action._GetTargetProperty(this._target),
  34155. { name: "value", value: this.value }
  34156. ]
  34157. }, parent);
  34158. };
  34159. return SetStateAction;
  34160. }(BABYLON.Action));
  34161. BABYLON.SetStateAction = SetStateAction;
  34162. var SetValueAction = (function (_super) {
  34163. __extends(SetValueAction, _super);
  34164. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34165. _super.call(this, triggerOptions, condition);
  34166. this.propertyPath = propertyPath;
  34167. this.value = value;
  34168. this._target = this._effectiveTarget = target;
  34169. }
  34170. SetValueAction.prototype._prepare = function () {
  34171. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34172. this._property = this._getProperty(this.propertyPath);
  34173. };
  34174. SetValueAction.prototype.execute = function () {
  34175. this._effectiveTarget[this._property] = this.value;
  34176. if (this._target.markAsDirty) {
  34177. this._target.markAsDirty(this._property);
  34178. }
  34179. };
  34180. SetValueAction.prototype.serialize = function (parent) {
  34181. return _super.prototype._serialize.call(this, {
  34182. name: "SetValueAction",
  34183. properties: [
  34184. BABYLON.Action._GetTargetProperty(this._target),
  34185. { name: "propertyPath", value: this.propertyPath },
  34186. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34187. ]
  34188. }, parent);
  34189. };
  34190. return SetValueAction;
  34191. }(BABYLON.Action));
  34192. BABYLON.SetValueAction = SetValueAction;
  34193. var IncrementValueAction = (function (_super) {
  34194. __extends(IncrementValueAction, _super);
  34195. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34196. _super.call(this, triggerOptions, condition);
  34197. this.propertyPath = propertyPath;
  34198. this.value = value;
  34199. this._target = this._effectiveTarget = target;
  34200. }
  34201. IncrementValueAction.prototype._prepare = function () {
  34202. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34203. this._property = this._getProperty(this.propertyPath);
  34204. if (typeof this._effectiveTarget[this._property] !== "number") {
  34205. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34206. }
  34207. };
  34208. IncrementValueAction.prototype.execute = function () {
  34209. this._effectiveTarget[this._property] += this.value;
  34210. if (this._target.markAsDirty) {
  34211. this._target.markAsDirty(this._property);
  34212. }
  34213. };
  34214. IncrementValueAction.prototype.serialize = function (parent) {
  34215. return _super.prototype._serialize.call(this, {
  34216. name: "IncrementValueAction",
  34217. properties: [
  34218. BABYLON.Action._GetTargetProperty(this._target),
  34219. { name: "propertyPath", value: this.propertyPath },
  34220. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34221. ]
  34222. }, parent);
  34223. };
  34224. return IncrementValueAction;
  34225. }(BABYLON.Action));
  34226. BABYLON.IncrementValueAction = IncrementValueAction;
  34227. var PlayAnimationAction = (function (_super) {
  34228. __extends(PlayAnimationAction, _super);
  34229. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34230. _super.call(this, triggerOptions, condition);
  34231. this.from = from;
  34232. this.to = to;
  34233. this.loop = loop;
  34234. this._target = target;
  34235. }
  34236. PlayAnimationAction.prototype._prepare = function () {
  34237. };
  34238. PlayAnimationAction.prototype.execute = function () {
  34239. var scene = this._actionManager.getScene();
  34240. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34241. };
  34242. PlayAnimationAction.prototype.serialize = function (parent) {
  34243. return _super.prototype._serialize.call(this, {
  34244. name: "PlayAnimationAction",
  34245. properties: [
  34246. BABYLON.Action._GetTargetProperty(this._target),
  34247. { name: "from", value: String(this.from) },
  34248. { name: "to", value: String(this.to) },
  34249. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34250. ]
  34251. }, parent);
  34252. };
  34253. return PlayAnimationAction;
  34254. }(BABYLON.Action));
  34255. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34256. var StopAnimationAction = (function (_super) {
  34257. __extends(StopAnimationAction, _super);
  34258. function StopAnimationAction(triggerOptions, target, condition) {
  34259. _super.call(this, triggerOptions, condition);
  34260. this._target = target;
  34261. }
  34262. StopAnimationAction.prototype._prepare = function () {
  34263. };
  34264. StopAnimationAction.prototype.execute = function () {
  34265. var scene = this._actionManager.getScene();
  34266. scene.stopAnimation(this._target);
  34267. };
  34268. StopAnimationAction.prototype.serialize = function (parent) {
  34269. return _super.prototype._serialize.call(this, {
  34270. name: "StopAnimationAction",
  34271. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34272. }, parent);
  34273. };
  34274. return StopAnimationAction;
  34275. }(BABYLON.Action));
  34276. BABYLON.StopAnimationAction = StopAnimationAction;
  34277. var DoNothingAction = (function (_super) {
  34278. __extends(DoNothingAction, _super);
  34279. function DoNothingAction(triggerOptions, condition) {
  34280. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34281. _super.call(this, triggerOptions, condition);
  34282. }
  34283. DoNothingAction.prototype.execute = function () {
  34284. };
  34285. DoNothingAction.prototype.serialize = function (parent) {
  34286. return _super.prototype._serialize.call(this, {
  34287. name: "DoNothingAction",
  34288. properties: []
  34289. }, parent);
  34290. };
  34291. return DoNothingAction;
  34292. }(BABYLON.Action));
  34293. BABYLON.DoNothingAction = DoNothingAction;
  34294. var CombineAction = (function (_super) {
  34295. __extends(CombineAction, _super);
  34296. function CombineAction(triggerOptions, children, condition) {
  34297. _super.call(this, triggerOptions, condition);
  34298. this.children = children;
  34299. }
  34300. CombineAction.prototype._prepare = function () {
  34301. for (var index = 0; index < this.children.length; index++) {
  34302. this.children[index]._actionManager = this._actionManager;
  34303. this.children[index]._prepare();
  34304. }
  34305. };
  34306. CombineAction.prototype.execute = function (evt) {
  34307. for (var index = 0; index < this.children.length; index++) {
  34308. this.children[index].execute(evt);
  34309. }
  34310. };
  34311. CombineAction.prototype.serialize = function (parent) {
  34312. var serializationObject = _super.prototype._serialize.call(this, {
  34313. name: "CombineAction",
  34314. properties: [],
  34315. combine: []
  34316. }, parent);
  34317. for (var i = 0; i < this.children.length; i++) {
  34318. serializationObject.combine.push(this.children[i].serialize(null));
  34319. }
  34320. return serializationObject;
  34321. };
  34322. return CombineAction;
  34323. }(BABYLON.Action));
  34324. BABYLON.CombineAction = CombineAction;
  34325. var ExecuteCodeAction = (function (_super) {
  34326. __extends(ExecuteCodeAction, _super);
  34327. function ExecuteCodeAction(triggerOptions, func, condition) {
  34328. _super.call(this, triggerOptions, condition);
  34329. this.func = func;
  34330. }
  34331. ExecuteCodeAction.prototype.execute = function (evt) {
  34332. this.func(evt);
  34333. };
  34334. return ExecuteCodeAction;
  34335. }(BABYLON.Action));
  34336. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34337. var SetParentAction = (function (_super) {
  34338. __extends(SetParentAction, _super);
  34339. function SetParentAction(triggerOptions, target, parent, condition) {
  34340. _super.call(this, triggerOptions, condition);
  34341. this._target = target;
  34342. this._parent = parent;
  34343. }
  34344. SetParentAction.prototype._prepare = function () {
  34345. };
  34346. SetParentAction.prototype.execute = function () {
  34347. if (this._target.parent === this._parent) {
  34348. return;
  34349. }
  34350. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34351. invertParentWorldMatrix.invert();
  34352. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34353. this._target.parent = this._parent;
  34354. };
  34355. SetParentAction.prototype.serialize = function (parent) {
  34356. return _super.prototype._serialize.call(this, {
  34357. name: "SetParentAction",
  34358. properties: [
  34359. BABYLON.Action._GetTargetProperty(this._target),
  34360. BABYLON.Action._GetTargetProperty(this._parent),
  34361. ]
  34362. }, parent);
  34363. };
  34364. return SetParentAction;
  34365. }(BABYLON.Action));
  34366. BABYLON.SetParentAction = SetParentAction;
  34367. var PlaySoundAction = (function (_super) {
  34368. __extends(PlaySoundAction, _super);
  34369. function PlaySoundAction(triggerOptions, sound, condition) {
  34370. _super.call(this, triggerOptions, condition);
  34371. this._sound = sound;
  34372. }
  34373. PlaySoundAction.prototype._prepare = function () {
  34374. };
  34375. PlaySoundAction.prototype.execute = function () {
  34376. if (this._sound !== undefined)
  34377. this._sound.play();
  34378. };
  34379. PlaySoundAction.prototype.serialize = function (parent) {
  34380. return _super.prototype._serialize.call(this, {
  34381. name: "PlaySoundAction",
  34382. properties: [{ name: "sound", value: this._sound.name }]
  34383. }, parent);
  34384. };
  34385. return PlaySoundAction;
  34386. }(BABYLON.Action));
  34387. BABYLON.PlaySoundAction = PlaySoundAction;
  34388. var StopSoundAction = (function (_super) {
  34389. __extends(StopSoundAction, _super);
  34390. function StopSoundAction(triggerOptions, sound, condition) {
  34391. _super.call(this, triggerOptions, condition);
  34392. this._sound = sound;
  34393. }
  34394. StopSoundAction.prototype._prepare = function () {
  34395. };
  34396. StopSoundAction.prototype.execute = function () {
  34397. if (this._sound !== undefined)
  34398. this._sound.stop();
  34399. };
  34400. StopSoundAction.prototype.serialize = function (parent) {
  34401. return _super.prototype._serialize.call(this, {
  34402. name: "StopSoundAction",
  34403. properties: [{ name: "sound", value: this._sound.name }]
  34404. }, parent);
  34405. };
  34406. return StopSoundAction;
  34407. }(BABYLON.Action));
  34408. BABYLON.StopSoundAction = StopSoundAction;
  34409. })(BABYLON || (BABYLON = {}));
  34410. var BABYLON;
  34411. (function (BABYLON) {
  34412. var Geometry = (function () {
  34413. function Geometry(id, scene, vertexData, updatable, mesh) {
  34414. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34415. this._totalVertices = 0;
  34416. this._isDisposed = false;
  34417. this.id = id;
  34418. this._engine = scene.getEngine();
  34419. this._meshes = [];
  34420. this._scene = scene;
  34421. //Init vertex buffer cache
  34422. this._vertexBuffers = {};
  34423. this._indices = [];
  34424. // vertexData
  34425. if (vertexData) {
  34426. this.setAllVerticesData(vertexData, updatable);
  34427. }
  34428. else {
  34429. this._totalVertices = 0;
  34430. this._indices = [];
  34431. }
  34432. // applyToMesh
  34433. if (mesh) {
  34434. if (mesh instanceof BABYLON.LinesMesh) {
  34435. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34436. this.updateExtend();
  34437. }
  34438. this.applyToMesh(mesh);
  34439. mesh.computeWorldMatrix(true);
  34440. }
  34441. }
  34442. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34443. /**
  34444. * 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
  34445. * @returns The Bias Vector
  34446. */
  34447. get: function () {
  34448. return this._boundingBias;
  34449. },
  34450. set: function (value) {
  34451. if (this._boundingBias && this._boundingBias.equals(value)) {
  34452. return;
  34453. }
  34454. this._boundingBias = value.clone();
  34455. this.updateBoundingInfo(true, null);
  34456. },
  34457. enumerable: true,
  34458. configurable: true
  34459. });
  34460. Object.defineProperty(Geometry.prototype, "extend", {
  34461. get: function () {
  34462. return this._extend;
  34463. },
  34464. enumerable: true,
  34465. configurable: true
  34466. });
  34467. Geometry.prototype.getScene = function () {
  34468. return this._scene;
  34469. };
  34470. Geometry.prototype.getEngine = function () {
  34471. return this._engine;
  34472. };
  34473. Geometry.prototype.isReady = function () {
  34474. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34475. };
  34476. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34477. vertexData.applyToGeometry(this, updatable);
  34478. this.notifyUpdate();
  34479. };
  34480. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34481. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34482. this.setVerticesBuffer(buffer);
  34483. };
  34484. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34485. var kind = buffer.getKind();
  34486. if (this._vertexBuffers[kind]) {
  34487. this._vertexBuffers[kind].dispose();
  34488. }
  34489. this._vertexBuffers[kind] = buffer;
  34490. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34491. var data = buffer.getData();
  34492. var stride = buffer.getStrideSize();
  34493. this._totalVertices = data.length / stride;
  34494. this.updateExtend(data, stride);
  34495. var meshes = this._meshes;
  34496. var numOfMeshes = meshes.length;
  34497. for (var index = 0; index < numOfMeshes; index++) {
  34498. var mesh = meshes[index];
  34499. mesh._resetPointsArrayCache();
  34500. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34501. mesh._createGlobalSubMesh();
  34502. mesh.computeWorldMatrix(true);
  34503. }
  34504. }
  34505. this.notifyUpdate(kind);
  34506. };
  34507. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34508. var vertexBuffer = this.getVertexBuffer(kind);
  34509. if (!vertexBuffer) {
  34510. return;
  34511. }
  34512. vertexBuffer.updateDirectly(data, offset);
  34513. this.notifyUpdate(kind);
  34514. };
  34515. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34516. var vertexBuffer = this.getVertexBuffer(kind);
  34517. if (!vertexBuffer) {
  34518. return;
  34519. }
  34520. vertexBuffer.update(data);
  34521. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34522. var stride = vertexBuffer.getStrideSize();
  34523. this._totalVertices = data.length / stride;
  34524. this.updateBoundingInfo(updateExtends, data);
  34525. }
  34526. this.notifyUpdate(kind);
  34527. };
  34528. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34529. if (updateExtends) {
  34530. this.updateExtend(data);
  34531. }
  34532. var meshes = this._meshes;
  34533. var numOfMeshes = meshes.length;
  34534. for (var index = 0; index < numOfMeshes; index++) {
  34535. var mesh = meshes[index];
  34536. mesh._resetPointsArrayCache();
  34537. if (updateExtends) {
  34538. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34539. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34540. var subMesh = mesh.subMeshes[subIndex];
  34541. subMesh.refreshBoundingInfo();
  34542. }
  34543. }
  34544. }
  34545. };
  34546. Geometry.prototype.getTotalVertices = function () {
  34547. if (!this.isReady()) {
  34548. return 0;
  34549. }
  34550. return this._totalVertices;
  34551. };
  34552. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  34553. var vertexBuffer = this.getVertexBuffer(kind);
  34554. if (!vertexBuffer) {
  34555. return null;
  34556. }
  34557. var orig = vertexBuffer.getData();
  34558. if (!copyWhenShared || this._meshes.length === 1) {
  34559. return orig;
  34560. }
  34561. else {
  34562. var len = orig.length;
  34563. var copy = [];
  34564. for (var i = 0; i < len; i++) {
  34565. copy.push(orig[i]);
  34566. }
  34567. return copy;
  34568. }
  34569. };
  34570. Geometry.prototype.getVertexBuffer = function (kind) {
  34571. if (!this.isReady()) {
  34572. return null;
  34573. }
  34574. return this._vertexBuffers[kind];
  34575. };
  34576. Geometry.prototype.getVertexBuffers = function () {
  34577. if (!this.isReady()) {
  34578. return null;
  34579. }
  34580. return this._vertexBuffers;
  34581. };
  34582. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34583. if (!this._vertexBuffers) {
  34584. if (this._delayInfo) {
  34585. return this._delayInfo.indexOf(kind) !== -1;
  34586. }
  34587. return false;
  34588. }
  34589. return this._vertexBuffers[kind] !== undefined;
  34590. };
  34591. Geometry.prototype.getVerticesDataKinds = function () {
  34592. var result = [];
  34593. var kind;
  34594. if (!this._vertexBuffers && this._delayInfo) {
  34595. for (kind in this._delayInfo) {
  34596. result.push(kind);
  34597. }
  34598. }
  34599. else {
  34600. for (kind in this._vertexBuffers) {
  34601. result.push(kind);
  34602. }
  34603. }
  34604. return result;
  34605. };
  34606. Geometry.prototype.setIndices = function (indices, totalVertices) {
  34607. if (this._indexBuffer) {
  34608. this._engine._releaseBuffer(this._indexBuffer);
  34609. }
  34610. this._indices = indices;
  34611. if (this._meshes.length !== 0 && this._indices) {
  34612. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34613. }
  34614. if (totalVertices !== undefined) {
  34615. this._totalVertices = totalVertices;
  34616. }
  34617. var meshes = this._meshes;
  34618. var numOfMeshes = meshes.length;
  34619. for (var index = 0; index < numOfMeshes; index++) {
  34620. meshes[index]._createGlobalSubMesh();
  34621. }
  34622. this.notifyUpdate();
  34623. };
  34624. Geometry.prototype.getTotalIndices = function () {
  34625. if (!this.isReady()) {
  34626. return 0;
  34627. }
  34628. return this._indices.length;
  34629. };
  34630. Geometry.prototype.getIndices = function (copyWhenShared) {
  34631. if (!this.isReady()) {
  34632. return null;
  34633. }
  34634. var orig = this._indices;
  34635. if (!copyWhenShared || this._meshes.length === 1) {
  34636. return orig;
  34637. }
  34638. else {
  34639. var len = orig.length;
  34640. var copy = [];
  34641. for (var i = 0; i < len; i++) {
  34642. copy.push(orig[i]);
  34643. }
  34644. return copy;
  34645. }
  34646. };
  34647. Geometry.prototype.getIndexBuffer = function () {
  34648. if (!this.isReady()) {
  34649. return null;
  34650. }
  34651. return this._indexBuffer;
  34652. };
  34653. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34654. var meshes = this._meshes;
  34655. var index = meshes.indexOf(mesh);
  34656. if (index === -1) {
  34657. return;
  34658. }
  34659. for (var kind in this._vertexBuffers) {
  34660. this._vertexBuffers[kind].dispose();
  34661. }
  34662. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  34663. this._indexBuffer = null;
  34664. }
  34665. meshes.splice(index, 1);
  34666. mesh._geometry = null;
  34667. if (meshes.length === 0 && shouldDispose) {
  34668. this.dispose();
  34669. }
  34670. };
  34671. Geometry.prototype.applyToMesh = function (mesh) {
  34672. if (mesh._geometry === this) {
  34673. return;
  34674. }
  34675. var previousGeometry = mesh._geometry;
  34676. if (previousGeometry) {
  34677. previousGeometry.releaseForMesh(mesh);
  34678. }
  34679. var meshes = this._meshes;
  34680. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34681. mesh._geometry = this;
  34682. this._scene.pushGeometry(this);
  34683. meshes.push(mesh);
  34684. if (this.isReady()) {
  34685. this._applyToMesh(mesh);
  34686. }
  34687. else {
  34688. mesh._boundingInfo = this._boundingInfo;
  34689. }
  34690. };
  34691. Geometry.prototype.updateExtend = function (data, stride) {
  34692. if (data === void 0) { data = null; }
  34693. if (!data) {
  34694. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34695. }
  34696. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34697. };
  34698. Geometry.prototype._applyToMesh = function (mesh) {
  34699. var numOfMeshes = this._meshes.length;
  34700. // vertexBuffers
  34701. for (var kind in this._vertexBuffers) {
  34702. if (numOfMeshes === 1) {
  34703. this._vertexBuffers[kind].create();
  34704. }
  34705. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  34706. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34707. mesh._resetPointsArrayCache();
  34708. if (!this._extend) {
  34709. this.updateExtend(this._vertexBuffers[kind].getData());
  34710. }
  34711. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34712. mesh._createGlobalSubMesh();
  34713. //bounding info was just created again, world matrix should be applied again.
  34714. mesh._updateBoundingInfo();
  34715. }
  34716. }
  34717. // indexBuffer
  34718. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34719. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34720. }
  34721. if (this._indexBuffer) {
  34722. this._indexBuffer.references = numOfMeshes;
  34723. }
  34724. };
  34725. Geometry.prototype.notifyUpdate = function (kind) {
  34726. if (this.onGeometryUpdated) {
  34727. this.onGeometryUpdated(this, kind);
  34728. }
  34729. };
  34730. Geometry.prototype.load = function (scene, onLoaded) {
  34731. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34732. return;
  34733. }
  34734. if (this.isReady()) {
  34735. if (onLoaded) {
  34736. onLoaded();
  34737. }
  34738. return;
  34739. }
  34740. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34741. this._queueLoad(scene, onLoaded);
  34742. };
  34743. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34744. var _this = this;
  34745. scene._addPendingData(this);
  34746. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  34747. _this._delayLoadingFunction(JSON.parse(data), _this);
  34748. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34749. _this._delayInfo = [];
  34750. scene._removePendingData(_this);
  34751. var meshes = _this._meshes;
  34752. var numOfMeshes = meshes.length;
  34753. for (var index = 0; index < numOfMeshes; index++) {
  34754. _this._applyToMesh(meshes[index]);
  34755. }
  34756. if (onLoaded) {
  34757. onLoaded();
  34758. }
  34759. }, function () { }, scene.database);
  34760. };
  34761. /**
  34762. * Invert the geometry to move from a right handed system to a left handed one.
  34763. */
  34764. Geometry.prototype.toLeftHanded = function () {
  34765. // Flip faces
  34766. var tIndices = this.getIndices(false);
  34767. if (tIndices != null && tIndices.length > 0) {
  34768. for (var i = 0; i < tIndices.length; i += 3) {
  34769. var tTemp = tIndices[i + 0];
  34770. tIndices[i + 0] = tIndices[i + 2];
  34771. tIndices[i + 2] = tTemp;
  34772. }
  34773. this.setIndices(tIndices);
  34774. }
  34775. // Negate position.z
  34776. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34777. if (tPositions != null && tPositions.length > 0) {
  34778. for (var i = 0; i < tPositions.length; i += 3) {
  34779. tPositions[i + 2] = -tPositions[i + 2];
  34780. }
  34781. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34782. }
  34783. // Negate normal.z
  34784. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34785. if (tNormals != null && tNormals.length > 0) {
  34786. for (var i = 0; i < tNormals.length; i += 3) {
  34787. tNormals[i + 2] = -tNormals[i + 2];
  34788. }
  34789. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34790. }
  34791. };
  34792. Geometry.prototype.isDisposed = function () {
  34793. return this._isDisposed;
  34794. };
  34795. Geometry.prototype.dispose = function () {
  34796. var meshes = this._meshes;
  34797. var numOfMeshes = meshes.length;
  34798. var index;
  34799. for (index = 0; index < numOfMeshes; index++) {
  34800. this.releaseForMesh(meshes[index]);
  34801. }
  34802. this._meshes = [];
  34803. for (var kind in this._vertexBuffers) {
  34804. this._vertexBuffers[kind].dispose();
  34805. }
  34806. this._vertexBuffers = {};
  34807. this._totalVertices = 0;
  34808. if (this._indexBuffer) {
  34809. this._engine._releaseBuffer(this._indexBuffer);
  34810. }
  34811. this._indexBuffer = null;
  34812. this._indices = [];
  34813. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34814. this.delayLoadingFile = null;
  34815. this._delayLoadingFunction = null;
  34816. this._delayInfo = [];
  34817. this._boundingInfo = null;
  34818. this._scene.removeGeometry(this);
  34819. this._isDisposed = true;
  34820. };
  34821. Geometry.prototype.copy = function (id) {
  34822. var vertexData = new BABYLON.VertexData();
  34823. vertexData.indices = [];
  34824. var indices = this.getIndices();
  34825. for (var index = 0; index < indices.length; index++) {
  34826. vertexData.indices.push(indices[index]);
  34827. }
  34828. var updatable = false;
  34829. var stopChecking = false;
  34830. var kind;
  34831. for (kind in this._vertexBuffers) {
  34832. // using slice() to make a copy of the array and not just reference it
  34833. var data = this.getVerticesData(kind);
  34834. if (data instanceof Float32Array) {
  34835. vertexData.set(new Float32Array(data), kind);
  34836. }
  34837. else {
  34838. vertexData.set(data.slice(0), kind);
  34839. }
  34840. if (!stopChecking) {
  34841. updatable = this.getVertexBuffer(kind).isUpdatable();
  34842. stopChecking = !updatable;
  34843. }
  34844. }
  34845. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  34846. geometry.delayLoadState = this.delayLoadState;
  34847. geometry.delayLoadingFile = this.delayLoadingFile;
  34848. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34849. for (kind in this._delayInfo) {
  34850. geometry._delayInfo = geometry._delayInfo || [];
  34851. geometry._delayInfo.push(kind);
  34852. }
  34853. // Bounding info
  34854. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34855. return geometry;
  34856. };
  34857. Geometry.prototype.serialize = function () {
  34858. var serializationObject = {};
  34859. serializationObject.id = this.id;
  34860. if (BABYLON.Tags.HasTags(this)) {
  34861. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34862. }
  34863. return serializationObject;
  34864. };
  34865. Geometry.prototype.serializeVerticeData = function () {
  34866. var serializationObject = this.serialize();
  34867. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34868. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34869. }
  34870. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34871. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34872. }
  34873. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34874. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34875. }
  34876. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34877. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  34878. }
  34879. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34880. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  34881. }
  34882. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34883. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  34884. }
  34885. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34886. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  34887. }
  34888. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34889. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  34890. }
  34891. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34892. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34893. }
  34894. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34895. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34896. serializationObject.matricesIndices._isExpanded = true;
  34897. }
  34898. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34899. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34900. }
  34901. serializationObject.indices = this.getIndices();
  34902. return serializationObject;
  34903. };
  34904. // Statics
  34905. Geometry.ExtractFromMesh = function (mesh, id) {
  34906. var geometry = mesh._geometry;
  34907. if (!geometry) {
  34908. return null;
  34909. }
  34910. return geometry.copy(id);
  34911. };
  34912. /**
  34913. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34914. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34915. * Be aware Math.random() could cause collisions, but:
  34916. * "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"
  34917. */
  34918. Geometry.RandomId = function () {
  34919. return BABYLON.Tools.RandomId();
  34920. };
  34921. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  34922. var scene = mesh.getScene();
  34923. // Geometry
  34924. var geometryId = parsedGeometry.geometryId;
  34925. if (geometryId) {
  34926. var geometry = scene.getGeometryByID(geometryId);
  34927. if (geometry) {
  34928. geometry.applyToMesh(mesh);
  34929. }
  34930. }
  34931. else if (parsedGeometry instanceof ArrayBuffer) {
  34932. var binaryInfo = mesh._binaryInfo;
  34933. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34934. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34935. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34936. }
  34937. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34938. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34939. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34940. }
  34941. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34942. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34943. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34944. }
  34945. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34946. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34947. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34948. }
  34949. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34950. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34951. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34952. }
  34953. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34954. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34955. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34956. }
  34957. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34958. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34959. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34960. }
  34961. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34962. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34963. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34964. }
  34965. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34966. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34967. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34968. }
  34969. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34970. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34971. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34972. }
  34973. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34974. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34975. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34976. }
  34977. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34978. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34979. mesh.setIndices(indicesData);
  34980. }
  34981. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34982. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34983. mesh.subMeshes = [];
  34984. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34985. var materialIndex = subMeshesData[(i * 5) + 0];
  34986. var verticesStart = subMeshesData[(i * 5) + 1];
  34987. var verticesCount = subMeshesData[(i * 5) + 2];
  34988. var indexStart = subMeshesData[(i * 5) + 3];
  34989. var indexCount = subMeshesData[(i * 5) + 4];
  34990. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34991. }
  34992. }
  34993. }
  34994. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34995. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  34996. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  34997. if (parsedGeometry.uvs) {
  34998. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  34999. }
  35000. if (parsedGeometry.uvs2) {
  35001. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  35002. }
  35003. if (parsedGeometry.uvs3) {
  35004. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  35005. }
  35006. if (parsedGeometry.uvs4) {
  35007. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  35008. }
  35009. if (parsedGeometry.uvs5) {
  35010. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  35011. }
  35012. if (parsedGeometry.uvs6) {
  35013. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  35014. }
  35015. if (parsedGeometry.colors) {
  35016. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  35017. }
  35018. if (parsedGeometry.matricesIndices) {
  35019. if (!parsedGeometry.matricesIndices._isExpanded) {
  35020. var floatIndices = [];
  35021. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35022. var matricesIndex = parsedGeometry.matricesIndices[i];
  35023. floatIndices.push(matricesIndex & 0x000000FF);
  35024. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35025. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35026. floatIndices.push(matricesIndex >> 24);
  35027. }
  35028. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  35029. }
  35030. else {
  35031. delete parsedGeometry.matricesIndices._isExpanded;
  35032. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  35033. }
  35034. }
  35035. if (parsedGeometry.matricesIndicesExtra) {
  35036. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35037. var floatIndices = [];
  35038. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35039. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35040. floatIndices.push(matricesIndex & 0x000000FF);
  35041. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35042. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35043. floatIndices.push(matricesIndex >> 24);
  35044. }
  35045. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  35046. }
  35047. else {
  35048. delete parsedGeometry.matricesIndices._isExpanded;
  35049. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  35050. }
  35051. }
  35052. if (parsedGeometry.matricesWeights) {
  35053. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  35054. }
  35055. if (parsedGeometry.matricesWeightsExtra) {
  35056. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  35057. }
  35058. mesh.setIndices(parsedGeometry.indices);
  35059. }
  35060. // SubMeshes
  35061. if (parsedGeometry.subMeshes) {
  35062. mesh.subMeshes = [];
  35063. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35064. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35065. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35066. }
  35067. }
  35068. // Flat shading
  35069. if (mesh._shouldGenerateFlatShading) {
  35070. mesh.convertToFlatShadedMesh();
  35071. delete mesh._shouldGenerateFlatShading;
  35072. }
  35073. // Update
  35074. mesh.computeWorldMatrix(true);
  35075. // Octree
  35076. if (scene['_selectionOctree']) {
  35077. scene['_selectionOctree'].addMesh(mesh);
  35078. }
  35079. };
  35080. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35081. if (scene.getGeometryByID(parsedVertexData.id)) {
  35082. return null; // null since geometry could be something else than a box...
  35083. }
  35084. var geometry = new Geometry(parsedVertexData.id, scene);
  35085. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35086. if (parsedVertexData.delayLoadingFile) {
  35087. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35088. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35089. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35090. geometry._delayInfo = [];
  35091. if (parsedVertexData.hasUVs) {
  35092. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35093. }
  35094. if (parsedVertexData.hasUVs2) {
  35095. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35096. }
  35097. if (parsedVertexData.hasUVs3) {
  35098. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35099. }
  35100. if (parsedVertexData.hasUVs4) {
  35101. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35102. }
  35103. if (parsedVertexData.hasUVs5) {
  35104. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35105. }
  35106. if (parsedVertexData.hasUVs6) {
  35107. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35108. }
  35109. if (parsedVertexData.hasColors) {
  35110. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35111. }
  35112. if (parsedVertexData.hasMatricesIndices) {
  35113. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35114. }
  35115. if (parsedVertexData.hasMatricesWeights) {
  35116. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35117. }
  35118. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35119. }
  35120. else {
  35121. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35122. }
  35123. scene.pushGeometry(geometry, true);
  35124. return geometry;
  35125. };
  35126. return Geometry;
  35127. }());
  35128. BABYLON.Geometry = Geometry;
  35129. /////// Primitives //////////////////////////////////////////////
  35130. var Geometry;
  35131. (function (Geometry) {
  35132. var Primitives;
  35133. (function (Primitives) {
  35134. /// Abstract class
  35135. var _Primitive = (function (_super) {
  35136. __extends(_Primitive, _super);
  35137. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  35138. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  35139. this._canBeRegenerated = _canBeRegenerated;
  35140. this._beingRegenerated = true;
  35141. this.regenerate();
  35142. this._beingRegenerated = false;
  35143. }
  35144. _Primitive.prototype.canBeRegenerated = function () {
  35145. return this._canBeRegenerated;
  35146. };
  35147. _Primitive.prototype.regenerate = function () {
  35148. if (!this._canBeRegenerated) {
  35149. return;
  35150. }
  35151. this._beingRegenerated = true;
  35152. this.setAllVerticesData(this._regenerateVertexData(), false);
  35153. this._beingRegenerated = false;
  35154. };
  35155. _Primitive.prototype.asNewGeometry = function (id) {
  35156. return _super.prototype.copy.call(this, id);
  35157. };
  35158. // overrides
  35159. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  35160. if (!this._beingRegenerated) {
  35161. return;
  35162. }
  35163. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35164. };
  35165. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  35166. if (!this._beingRegenerated) {
  35167. return;
  35168. }
  35169. _super.prototype.setVerticesData.call(this, kind, data, false);
  35170. };
  35171. // to override
  35172. // protected
  35173. _Primitive.prototype._regenerateVertexData = function () {
  35174. throw new Error("Abstract method");
  35175. };
  35176. _Primitive.prototype.copy = function (id) {
  35177. throw new Error("Must be overriden in sub-classes.");
  35178. };
  35179. _Primitive.prototype.serialize = function () {
  35180. var serializationObject = _super.prototype.serialize.call(this);
  35181. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35182. return serializationObject;
  35183. };
  35184. return _Primitive;
  35185. }(Geometry));
  35186. Primitives._Primitive = _Primitive;
  35187. var Ribbon = (function (_super) {
  35188. __extends(Ribbon, _super);
  35189. // Members
  35190. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  35191. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35192. _super.call(this, id, scene, canBeRegenerated, mesh);
  35193. this.pathArray = pathArray;
  35194. this.closeArray = closeArray;
  35195. this.closePath = closePath;
  35196. this.offset = offset;
  35197. this.side = side;
  35198. }
  35199. Ribbon.prototype._regenerateVertexData = function () {
  35200. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35201. };
  35202. Ribbon.prototype.copy = function (id) {
  35203. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  35204. };
  35205. return Ribbon;
  35206. }(_Primitive));
  35207. Primitives.Ribbon = Ribbon;
  35208. var Box = (function (_super) {
  35209. __extends(Box, _super);
  35210. // Members
  35211. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  35212. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35213. _super.call(this, id, scene, canBeRegenerated, mesh);
  35214. this.size = size;
  35215. this.side = side;
  35216. }
  35217. Box.prototype._regenerateVertexData = function () {
  35218. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35219. };
  35220. Box.prototype.copy = function (id) {
  35221. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35222. };
  35223. Box.prototype.serialize = function () {
  35224. var serializationObject = _super.prototype.serialize.call(this);
  35225. serializationObject.size = this.size;
  35226. return serializationObject;
  35227. };
  35228. Box.Parse = function (parsedBox, scene) {
  35229. if (scene.getGeometryByID(parsedBox.id)) {
  35230. return null; // null since geometry could be something else than a box...
  35231. }
  35232. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35233. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35234. scene.pushGeometry(box, true);
  35235. return box;
  35236. };
  35237. return Box;
  35238. }(_Primitive));
  35239. Primitives.Box = Box;
  35240. var Sphere = (function (_super) {
  35241. __extends(Sphere, _super);
  35242. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  35243. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35244. _super.call(this, id, scene, canBeRegenerated, mesh);
  35245. this.segments = segments;
  35246. this.diameter = diameter;
  35247. this.side = side;
  35248. }
  35249. Sphere.prototype._regenerateVertexData = function () {
  35250. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35251. };
  35252. Sphere.prototype.copy = function (id) {
  35253. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35254. };
  35255. Sphere.prototype.serialize = function () {
  35256. var serializationObject = _super.prototype.serialize.call(this);
  35257. serializationObject.segments = this.segments;
  35258. serializationObject.diameter = this.diameter;
  35259. return serializationObject;
  35260. };
  35261. Sphere.Parse = function (parsedSphere, scene) {
  35262. if (scene.getGeometryByID(parsedSphere.id)) {
  35263. return null; // null since geometry could be something else than a sphere...
  35264. }
  35265. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35266. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35267. scene.pushGeometry(sphere, true);
  35268. return sphere;
  35269. };
  35270. return Sphere;
  35271. }(_Primitive));
  35272. Primitives.Sphere = Sphere;
  35273. var Disc = (function (_super) {
  35274. __extends(Disc, _super);
  35275. // Members
  35276. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  35277. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35278. _super.call(this, id, scene, canBeRegenerated, mesh);
  35279. this.radius = radius;
  35280. this.tessellation = tessellation;
  35281. this.side = side;
  35282. }
  35283. Disc.prototype._regenerateVertexData = function () {
  35284. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35285. };
  35286. Disc.prototype.copy = function (id) {
  35287. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35288. };
  35289. return Disc;
  35290. }(_Primitive));
  35291. Primitives.Disc = Disc;
  35292. var Cylinder = (function (_super) {
  35293. __extends(Cylinder, _super);
  35294. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  35295. if (subdivisions === void 0) { subdivisions = 1; }
  35296. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35297. _super.call(this, id, scene, canBeRegenerated, mesh);
  35298. this.height = height;
  35299. this.diameterTop = diameterTop;
  35300. this.diameterBottom = diameterBottom;
  35301. this.tessellation = tessellation;
  35302. this.subdivisions = subdivisions;
  35303. this.side = side;
  35304. }
  35305. Cylinder.prototype._regenerateVertexData = function () {
  35306. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35307. };
  35308. Cylinder.prototype.copy = function (id) {
  35309. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35310. };
  35311. Cylinder.prototype.serialize = function () {
  35312. var serializationObject = _super.prototype.serialize.call(this);
  35313. serializationObject.height = this.height;
  35314. serializationObject.diameterTop = this.diameterTop;
  35315. serializationObject.diameterBottom = this.diameterBottom;
  35316. serializationObject.tessellation = this.tessellation;
  35317. return serializationObject;
  35318. };
  35319. Cylinder.Parse = function (parsedCylinder, scene) {
  35320. if (scene.getGeometryByID(parsedCylinder.id)) {
  35321. return null; // null since geometry could be something else than a cylinder...
  35322. }
  35323. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35324. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35325. scene.pushGeometry(cylinder, true);
  35326. return cylinder;
  35327. };
  35328. return Cylinder;
  35329. }(_Primitive));
  35330. Primitives.Cylinder = Cylinder;
  35331. var Torus = (function (_super) {
  35332. __extends(Torus, _super);
  35333. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  35334. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35335. _super.call(this, id, scene, canBeRegenerated, mesh);
  35336. this.diameter = diameter;
  35337. this.thickness = thickness;
  35338. this.tessellation = tessellation;
  35339. this.side = side;
  35340. }
  35341. Torus.prototype._regenerateVertexData = function () {
  35342. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35343. };
  35344. Torus.prototype.copy = function (id) {
  35345. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35346. };
  35347. Torus.prototype.serialize = function () {
  35348. var serializationObject = _super.prototype.serialize.call(this);
  35349. serializationObject.diameter = this.diameter;
  35350. serializationObject.thickness = this.thickness;
  35351. serializationObject.tessellation = this.tessellation;
  35352. return serializationObject;
  35353. };
  35354. Torus.Parse = function (parsedTorus, scene) {
  35355. if (scene.getGeometryByID(parsedTorus.id)) {
  35356. return null; // null since geometry could be something else than a torus...
  35357. }
  35358. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35359. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35360. scene.pushGeometry(torus, true);
  35361. return torus;
  35362. };
  35363. return Torus;
  35364. }(_Primitive));
  35365. Primitives.Torus = Torus;
  35366. var Ground = (function (_super) {
  35367. __extends(Ground, _super);
  35368. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  35369. _super.call(this, id, scene, canBeRegenerated, mesh);
  35370. this.width = width;
  35371. this.height = height;
  35372. this.subdivisions = subdivisions;
  35373. }
  35374. Ground.prototype._regenerateVertexData = function () {
  35375. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35376. };
  35377. Ground.prototype.copy = function (id) {
  35378. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35379. };
  35380. Ground.prototype.serialize = function () {
  35381. var serializationObject = _super.prototype.serialize.call(this);
  35382. serializationObject.width = this.width;
  35383. serializationObject.height = this.height;
  35384. serializationObject.subdivisions = this.subdivisions;
  35385. return serializationObject;
  35386. };
  35387. Ground.Parse = function (parsedGround, scene) {
  35388. if (scene.getGeometryByID(parsedGround.id)) {
  35389. return null; // null since geometry could be something else than a ground...
  35390. }
  35391. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35392. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35393. scene.pushGeometry(ground, true);
  35394. return ground;
  35395. };
  35396. return Ground;
  35397. }(_Primitive));
  35398. Primitives.Ground = Ground;
  35399. var TiledGround = (function (_super) {
  35400. __extends(TiledGround, _super);
  35401. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  35402. _super.call(this, id, scene, canBeRegenerated, mesh);
  35403. this.xmin = xmin;
  35404. this.zmin = zmin;
  35405. this.xmax = xmax;
  35406. this.zmax = zmax;
  35407. this.subdivisions = subdivisions;
  35408. this.precision = precision;
  35409. }
  35410. TiledGround.prototype._regenerateVertexData = function () {
  35411. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35412. };
  35413. TiledGround.prototype.copy = function (id) {
  35414. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35415. };
  35416. return TiledGround;
  35417. }(_Primitive));
  35418. Primitives.TiledGround = TiledGround;
  35419. var Plane = (function (_super) {
  35420. __extends(Plane, _super);
  35421. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  35422. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35423. _super.call(this, id, scene, canBeRegenerated, mesh);
  35424. this.size = size;
  35425. this.side = side;
  35426. }
  35427. Plane.prototype._regenerateVertexData = function () {
  35428. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35429. };
  35430. Plane.prototype.copy = function (id) {
  35431. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35432. };
  35433. Plane.prototype.serialize = function () {
  35434. var serializationObject = _super.prototype.serialize.call(this);
  35435. serializationObject.size = this.size;
  35436. return serializationObject;
  35437. };
  35438. Plane.Parse = function (parsedPlane, scene) {
  35439. if (scene.getGeometryByID(parsedPlane.id)) {
  35440. return null; // null since geometry could be something else than a ground...
  35441. }
  35442. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35443. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35444. scene.pushGeometry(plane, true);
  35445. return plane;
  35446. };
  35447. return Plane;
  35448. }(_Primitive));
  35449. Primitives.Plane = Plane;
  35450. var TorusKnot = (function (_super) {
  35451. __extends(TorusKnot, _super);
  35452. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  35453. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35454. _super.call(this, id, scene, canBeRegenerated, mesh);
  35455. this.radius = radius;
  35456. this.tube = tube;
  35457. this.radialSegments = radialSegments;
  35458. this.tubularSegments = tubularSegments;
  35459. this.p = p;
  35460. this.q = q;
  35461. this.side = side;
  35462. }
  35463. TorusKnot.prototype._regenerateVertexData = function () {
  35464. 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 });
  35465. };
  35466. TorusKnot.prototype.copy = function (id) {
  35467. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35468. };
  35469. TorusKnot.prototype.serialize = function () {
  35470. var serializationObject = _super.prototype.serialize.call(this);
  35471. serializationObject.radius = this.radius;
  35472. serializationObject.tube = this.tube;
  35473. serializationObject.radialSegments = this.radialSegments;
  35474. serializationObject.tubularSegments = this.tubularSegments;
  35475. serializationObject.p = this.p;
  35476. serializationObject.q = this.q;
  35477. return serializationObject;
  35478. };
  35479. ;
  35480. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  35481. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35482. return null; // null since geometry could be something else than a ground...
  35483. }
  35484. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35485. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35486. scene.pushGeometry(torusKnot, true);
  35487. return torusKnot;
  35488. };
  35489. return TorusKnot;
  35490. }(_Primitive));
  35491. Primitives.TorusKnot = TorusKnot;
  35492. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  35493. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  35494. })(BABYLON || (BABYLON = {}));
  35495. var BABYLON;
  35496. (function (BABYLON) {
  35497. var GroundMesh = (function (_super) {
  35498. __extends(GroundMesh, _super);
  35499. function GroundMesh(name, scene) {
  35500. _super.call(this, name, scene);
  35501. this.generateOctree = false;
  35502. this._worldInverse = new BABYLON.Matrix();
  35503. }
  35504. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  35505. get: function () {
  35506. return Math.min(this._subdivisionsX, this._subdivisionsY);
  35507. },
  35508. enumerable: true,
  35509. configurable: true
  35510. });
  35511. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  35512. get: function () {
  35513. return this._subdivisionsX;
  35514. },
  35515. enumerable: true,
  35516. configurable: true
  35517. });
  35518. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  35519. get: function () {
  35520. return this._subdivisionsY;
  35521. },
  35522. enumerable: true,
  35523. configurable: true
  35524. });
  35525. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  35526. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  35527. this._subdivisionsX = chunksCount;
  35528. this._subdivisionsY = chunksCount;
  35529. this.subdivide(chunksCount);
  35530. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  35531. };
  35532. /**
  35533. * Returns a height (y) value in the Worl system :
  35534. * the ground altitude at the coordinates (x, z) expressed in the World system.
  35535. * Returns the ground y position if (x, z) are outside the ground surface.
  35536. * Not pertinent if the ground is rotated.
  35537. */
  35538. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  35539. // express x and y in the ground local system
  35540. x -= this.position.x;
  35541. z -= this.position.z;
  35542. x /= this.scaling.x;
  35543. z /= this.scaling.z;
  35544. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35545. return this.position.y;
  35546. }
  35547. if (!this._heightQuads || this._heightQuads.length == 0) {
  35548. this._initHeightQuads();
  35549. this._computeHeightQuads();
  35550. }
  35551. var facet = this._getFacetAt(x, z);
  35552. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  35553. // return y in the World system
  35554. return y * this.scaling.y + this.position.y;
  35555. };
  35556. /**
  35557. * Returns a normalized vector (Vector3) orthogonal to the ground
  35558. * at the ground coordinates (x, z) expressed in the World system.
  35559. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  35560. * Not pertinent if the ground is rotated.
  35561. */
  35562. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  35563. var normal = new BABYLON.Vector3(0, 1, 0);
  35564. this.getNormalAtCoordinatesToRef(x, z, normal);
  35565. return normal;
  35566. };
  35567. /**
  35568. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  35569. * at the ground coordinates (x, z) expressed in the World system.
  35570. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  35571. * Not pertinent if the ground is rotated.
  35572. */
  35573. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  35574. // express x and y in the ground local system
  35575. x -= this.position.x;
  35576. z -= this.position.z;
  35577. x /= this.scaling.x;
  35578. z /= this.scaling.z;
  35579. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35580. return;
  35581. }
  35582. if (!this._heightQuads || this._heightQuads.length == 0) {
  35583. this._initHeightQuads();
  35584. this._computeHeightQuads();
  35585. }
  35586. var facet = this._getFacetAt(x, z);
  35587. ref.x = facet.x;
  35588. ref.y = facet.y;
  35589. ref.z = facet.z;
  35590. };
  35591. /**
  35592. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  35593. * if the ground has been updated.
  35594. * This can be used in the render loop
  35595. */
  35596. GroundMesh.prototype.updateCoordinateHeights = function () {
  35597. if (!this._heightQuads || this._heightQuads.length == 0) {
  35598. this._initHeightQuads();
  35599. }
  35600. this._computeHeightQuads();
  35601. };
  35602. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  35603. GroundMesh.prototype._getFacetAt = function (x, z) {
  35604. // retrieve col and row from x, z coordinates in the ground local system
  35605. var subdivisionsX = this._subdivisionsX;
  35606. var subdivisionsY = this._subdivisionsY;
  35607. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  35608. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  35609. var quad = this._heightQuads[row * this._subdivisionsX + col];
  35610. var facet;
  35611. if (z < quad.slope.x * x + quad.slope.y) {
  35612. facet = quad.facet1;
  35613. }
  35614. else {
  35615. facet = quad.facet2;
  35616. }
  35617. return facet;
  35618. };
  35619. // Creates and populates the heightMap array with "facet" elements :
  35620. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  35621. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35622. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35623. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35624. GroundMesh.prototype._initHeightQuads = function () {
  35625. var subdivisionsX = this._subdivisionsX;
  35626. var subdivisionsY = this._subdivisionsY;
  35627. this._heightQuads = new Array();
  35628. for (var row = 0; row < subdivisionsY; row++) {
  35629. for (var col = 0; col < subdivisionsX; col++) {
  35630. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  35631. this._heightQuads[row * subdivisionsX + col] = quad;
  35632. }
  35633. }
  35634. };
  35635. // Compute each quad element values and update the the heightMap array :
  35636. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35637. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35638. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35639. GroundMesh.prototype._computeHeightQuads = function () {
  35640. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35641. var v1 = BABYLON.Tmp.Vector3[3];
  35642. var v2 = BABYLON.Tmp.Vector3[2];
  35643. var v3 = BABYLON.Tmp.Vector3[1];
  35644. var v4 = BABYLON.Tmp.Vector3[0];
  35645. var v1v2 = BABYLON.Tmp.Vector3[4];
  35646. var v1v3 = BABYLON.Tmp.Vector3[5];
  35647. var v1v4 = BABYLON.Tmp.Vector3[6];
  35648. var norm1 = BABYLON.Tmp.Vector3[7];
  35649. var norm2 = BABYLON.Tmp.Vector3[8];
  35650. var i = 0;
  35651. var j = 0;
  35652. var k = 0;
  35653. var cd = 0; // 2D slope coefficient : z = cd * x + h
  35654. var h = 0;
  35655. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  35656. var d2 = 0;
  35657. var subdivisionsX = this._subdivisionsX;
  35658. var subdivisionsY = this._subdivisionsY;
  35659. for (var row = 0; row < subdivisionsY; row++) {
  35660. for (var col = 0; col < subdivisionsX; col++) {
  35661. i = col * 3;
  35662. j = row * (subdivisionsX + 1) * 3;
  35663. k = (row + 1) * (subdivisionsX + 1) * 3;
  35664. v1.x = positions[j + i];
  35665. v1.y = positions[j + i + 1];
  35666. v1.z = positions[j + i + 2];
  35667. v2.x = positions[j + i + 3];
  35668. v2.y = positions[j + i + 4];
  35669. v2.z = positions[j + i + 5];
  35670. v3.x = positions[k + i];
  35671. v3.y = positions[k + i + 1];
  35672. v3.z = positions[k + i + 2];
  35673. v4.x = positions[k + i + 3];
  35674. v4.y = positions[k + i + 4];
  35675. v4.z = positions[k + i + 5];
  35676. // 2D slope V1V4
  35677. cd = (v4.z - v1.z) / (v4.x - v1.x);
  35678. h = v1.z - cd * v1.x; // v1 belongs to the slope
  35679. // facet equations :
  35680. // we compute each facet normal vector
  35681. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  35682. // we compute the value d by applying the equation to v1 which belongs to the plane
  35683. // then we store the facet equation in a Vector4
  35684. v2.subtractToRef(v1, v1v2);
  35685. v3.subtractToRef(v1, v1v3);
  35686. v4.subtractToRef(v1, v1v4);
  35687. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  35688. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  35689. norm1.normalize();
  35690. norm2.normalize();
  35691. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  35692. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  35693. var quad = this._heightQuads[row * subdivisionsX + col];
  35694. quad.slope.copyFromFloats(cd, h);
  35695. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  35696. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  35697. }
  35698. }
  35699. };
  35700. return GroundMesh;
  35701. }(BABYLON.Mesh));
  35702. BABYLON.GroundMesh = GroundMesh;
  35703. })(BABYLON || (BABYLON = {}));
  35704. var BABYLON;
  35705. (function (BABYLON) {
  35706. var LinesMesh = (function (_super) {
  35707. __extends(LinesMesh, _super);
  35708. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  35709. if (parent === void 0) { parent = null; }
  35710. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  35711. this.color = new BABYLON.Color3(1, 1, 1);
  35712. this.alpha = 1;
  35713. this._positionBuffer = {};
  35714. if (source) {
  35715. this.color = source.color.clone();
  35716. this.alpha = source.alpha;
  35717. }
  35718. this._intersectionThreshold = 0.1;
  35719. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  35720. attributes: [BABYLON.VertexBuffer.PositionKind],
  35721. uniforms: ["worldViewProjection", "color"],
  35722. needAlphaBlending: true
  35723. });
  35724. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  35725. }
  35726. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  35727. /**
  35728. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35729. * This margin is expressed in world space coordinates, so its value may vary.
  35730. * Default value is 0.1
  35731. * @returns the intersection Threshold value.
  35732. */
  35733. get: function () {
  35734. return this._intersectionThreshold;
  35735. },
  35736. /**
  35737. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35738. * This margin is expressed in world space coordinates, so its value may vary.
  35739. * @param value the new threshold to apply
  35740. */
  35741. set: function (value) {
  35742. if (this._intersectionThreshold === value) {
  35743. return;
  35744. }
  35745. this._intersectionThreshold = value;
  35746. if (this.geometry) {
  35747. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  35748. }
  35749. },
  35750. enumerable: true,
  35751. configurable: true
  35752. });
  35753. Object.defineProperty(LinesMesh.prototype, "material", {
  35754. get: function () {
  35755. return this._colorShader;
  35756. },
  35757. enumerable: true,
  35758. configurable: true
  35759. });
  35760. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  35761. get: function () {
  35762. return false;
  35763. },
  35764. enumerable: true,
  35765. configurable: true
  35766. });
  35767. LinesMesh.prototype.createInstance = function (name) {
  35768. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  35769. return null;
  35770. };
  35771. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  35772. var engine = this.getScene().getEngine();
  35773. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  35774. // VBOs
  35775. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  35776. // Color
  35777. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  35778. };
  35779. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  35780. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  35781. return;
  35782. }
  35783. var engine = this.getScene().getEngine();
  35784. // Draw order
  35785. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  35786. };
  35787. LinesMesh.prototype.dispose = function (doNotRecurse) {
  35788. this._colorShader.dispose();
  35789. _super.prototype.dispose.call(this, doNotRecurse);
  35790. };
  35791. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  35792. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  35793. };
  35794. return LinesMesh;
  35795. }(BABYLON.Mesh));
  35796. BABYLON.LinesMesh = LinesMesh;
  35797. })(BABYLON || (BABYLON = {}));
  35798. var BABYLON;
  35799. (function (BABYLON) {
  35800. var DefaultLoadingScreen = (function () {
  35801. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  35802. var _this = this;
  35803. if (_loadingText === void 0) { _loadingText = ""; }
  35804. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  35805. this._renderingCanvas = _renderingCanvas;
  35806. this._loadingText = _loadingText;
  35807. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  35808. // Resize
  35809. this._resizeLoadingUI = function () {
  35810. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  35811. _this._loadingDiv.style.position = "absolute";
  35812. _this._loadingDiv.style.left = canvasRect.left + "px";
  35813. _this._loadingDiv.style.top = canvasRect.top + "px";
  35814. _this._loadingDiv.style.width = canvasRect.width + "px";
  35815. _this._loadingDiv.style.height = canvasRect.height + "px";
  35816. };
  35817. }
  35818. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  35819. var _this = this;
  35820. if (this._loadingDiv) {
  35821. // Do not add a loading screen if there is already one
  35822. return;
  35823. }
  35824. this._loadingDiv = document.createElement("div");
  35825. this._loadingDiv.id = "babylonjsLoadingDiv";
  35826. this._loadingDiv.style.opacity = "0";
  35827. this._loadingDiv.style.transition = "opacity 1.5s ease";
  35828. // Loading text
  35829. this._loadingTextDiv = document.createElement("div");
  35830. this._loadingTextDiv.style.position = "absolute";
  35831. this._loadingTextDiv.style.left = "0";
  35832. this._loadingTextDiv.style.top = "50%";
  35833. this._loadingTextDiv.style.marginTop = "80px";
  35834. this._loadingTextDiv.style.width = "100%";
  35835. this._loadingTextDiv.style.height = "20px";
  35836. this._loadingTextDiv.style.fontFamily = "Arial";
  35837. this._loadingTextDiv.style.fontSize = "14px";
  35838. this._loadingTextDiv.style.color = "white";
  35839. this._loadingTextDiv.style.textAlign = "center";
  35840. this._loadingTextDiv.innerHTML = "Loading";
  35841. this._loadingDiv.appendChild(this._loadingTextDiv);
  35842. //set the predefined text
  35843. this._loadingTextDiv.innerHTML = this._loadingText;
  35844. // Loading img
  35845. var imgBack = new Image();
  35846. 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==";
  35847. imgBack.style.position = "absolute";
  35848. imgBack.style.left = "50%";
  35849. imgBack.style.top = "50%";
  35850. imgBack.style.marginLeft = "-50px";
  35851. imgBack.style.marginTop = "-50px";
  35852. imgBack.style.transition = "transform 1.0s ease";
  35853. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  35854. var deg = 360;
  35855. var onTransitionEnd = function () {
  35856. deg += 360;
  35857. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  35858. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  35859. };
  35860. imgBack.addEventListener("transitionend", onTransitionEnd);
  35861. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  35862. this._loadingDiv.appendChild(imgBack);
  35863. // front image
  35864. var imgFront = new Image();
  35865. 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=";
  35866. imgFront.style.position = "absolute";
  35867. imgFront.style.left = "50%";
  35868. imgFront.style.top = "50%";
  35869. imgFront.style.marginLeft = "-50px";
  35870. imgFront.style.marginTop = "-50px";
  35871. this._loadingDiv.appendChild(imgFront);
  35872. this._resizeLoadingUI();
  35873. window.addEventListener("resize", this._resizeLoadingUI);
  35874. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35875. document.body.appendChild(this._loadingDiv);
  35876. setTimeout(function () {
  35877. _this._loadingDiv.style.opacity = "1";
  35878. imgBack.style.transform = "rotateZ(360deg)";
  35879. imgBack.style.webkitTransform = "rotateZ(360deg)";
  35880. }, 0);
  35881. };
  35882. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  35883. var _this = this;
  35884. if (!this._loadingDiv) {
  35885. return;
  35886. }
  35887. var onTransitionEnd = function () {
  35888. if (!_this._loadingDiv) {
  35889. return;
  35890. }
  35891. document.body.removeChild(_this._loadingDiv);
  35892. window.removeEventListener("resize", _this._resizeLoadingUI);
  35893. _this._loadingDiv = null;
  35894. };
  35895. this._loadingDiv.style.opacity = "0";
  35896. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  35897. };
  35898. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  35899. set: function (text) {
  35900. this._loadingText = text;
  35901. if (this._loadingTextDiv) {
  35902. this._loadingTextDiv.innerHTML = this._loadingText;
  35903. }
  35904. },
  35905. enumerable: true,
  35906. configurable: true
  35907. });
  35908. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  35909. get: function () {
  35910. return this._loadingDivBackgroundColor;
  35911. },
  35912. set: function (color) {
  35913. this._loadingDivBackgroundColor = color;
  35914. if (!this._loadingDiv) {
  35915. return;
  35916. }
  35917. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35918. },
  35919. enumerable: true,
  35920. configurable: true
  35921. });
  35922. return DefaultLoadingScreen;
  35923. }());
  35924. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  35925. })(BABYLON || (BABYLON = {}));
  35926. var BABYLON;
  35927. (function (BABYLON) {
  35928. var AudioEngine = (function () {
  35929. function AudioEngine() {
  35930. this._audioContext = null;
  35931. this._audioContextInitialized = false;
  35932. this.canUseWebAudio = false;
  35933. this.WarnedWebAudioUnsupported = false;
  35934. this.unlocked = false;
  35935. this.isMP3supported = false;
  35936. this.isOGGsupported = false;
  35937. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35938. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35939. this.canUseWebAudio = true;
  35940. }
  35941. var audioElem = document.createElement('audio');
  35942. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  35943. this.isMP3supported = true;
  35944. }
  35945. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  35946. this.isOGGsupported = true;
  35947. }
  35948. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35949. this._unlockiOSaudio();
  35950. }
  35951. else {
  35952. this.unlocked = true;
  35953. }
  35954. }
  35955. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35956. get: function () {
  35957. if (!this._audioContextInitialized) {
  35958. this._initializeAudioContext();
  35959. }
  35960. return this._audioContext;
  35961. },
  35962. enumerable: true,
  35963. configurable: true
  35964. });
  35965. AudioEngine.prototype._unlockiOSaudio = function () {
  35966. var _this = this;
  35967. var unlockaudio = function () {
  35968. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35969. var source = _this.audioContext.createBufferSource();
  35970. source.buffer = buffer;
  35971. source.connect(_this.audioContext.destination);
  35972. source.start(0);
  35973. setTimeout(function () {
  35974. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35975. _this.unlocked = true;
  35976. window.removeEventListener('touchend', unlockaudio, false);
  35977. if (_this.onAudioUnlocked) {
  35978. _this.onAudioUnlocked();
  35979. }
  35980. }
  35981. }, 0);
  35982. };
  35983. window.addEventListener('touchend', unlockaudio, false);
  35984. };
  35985. AudioEngine.prototype._initializeAudioContext = function () {
  35986. try {
  35987. if (this.canUseWebAudio) {
  35988. this._audioContext = new AudioContext();
  35989. // create a global volume gain node
  35990. this.masterGain = this._audioContext.createGain();
  35991. this.masterGain.gain.value = 1;
  35992. this.masterGain.connect(this._audioContext.destination);
  35993. this._audioContextInitialized = true;
  35994. }
  35995. }
  35996. catch (e) {
  35997. this.canUseWebAudio = false;
  35998. BABYLON.Tools.Error("Web Audio: " + e.message);
  35999. }
  36000. };
  36001. AudioEngine.prototype.dispose = function () {
  36002. if (this.canUseWebAudio && this._audioContextInitialized) {
  36003. if (this._connectedAnalyser) {
  36004. this._connectedAnalyser.stopDebugCanvas();
  36005. this._connectedAnalyser.dispose();
  36006. this.masterGain.disconnect();
  36007. this.masterGain.connect(this._audioContext.destination);
  36008. this._connectedAnalyser = null;
  36009. }
  36010. this.masterGain.gain.value = 1;
  36011. }
  36012. this.WarnedWebAudioUnsupported = false;
  36013. };
  36014. AudioEngine.prototype.getGlobalVolume = function () {
  36015. if (this.canUseWebAudio && this._audioContextInitialized) {
  36016. return this.masterGain.gain.value;
  36017. }
  36018. else {
  36019. return -1;
  36020. }
  36021. };
  36022. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  36023. if (this.canUseWebAudio && this._audioContextInitialized) {
  36024. this.masterGain.gain.value = newVolume;
  36025. }
  36026. };
  36027. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  36028. if (this._connectedAnalyser) {
  36029. this._connectedAnalyser.stopDebugCanvas();
  36030. }
  36031. if (this.canUseWebAudio && this._audioContextInitialized) {
  36032. this._connectedAnalyser = analyser;
  36033. this.masterGain.disconnect();
  36034. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  36035. }
  36036. };
  36037. return AudioEngine;
  36038. }());
  36039. BABYLON.AudioEngine = AudioEngine;
  36040. })(BABYLON || (BABYLON = {}));
  36041. var BABYLON;
  36042. (function (BABYLON) {
  36043. var Sound = (function () {
  36044. /**
  36045. * Create a sound and attach it to a scene
  36046. * @param name Name of your sound
  36047. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  36048. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  36049. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  36050. */
  36051. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  36052. var _this = this;
  36053. this.autoplay = false;
  36054. this.loop = false;
  36055. this.useCustomAttenuation = false;
  36056. this.spatialSound = false;
  36057. this.refDistance = 1;
  36058. this.rolloffFactor = 1;
  36059. this.maxDistance = 100;
  36060. this.distanceModel = "linear";
  36061. this._panningModel = "equalpower";
  36062. this._playbackRate = 1;
  36063. this._streaming = false;
  36064. this._startTime = 0;
  36065. this._startOffset = 0;
  36066. this._position = BABYLON.Vector3.Zero();
  36067. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  36068. this._volume = 1;
  36069. this._isLoaded = false;
  36070. this._isReadyToPlay = false;
  36071. this.isPlaying = false;
  36072. this.isPaused = false;
  36073. this._isDirectional = false;
  36074. // Used if you'd like to create a directional sound.
  36075. // If not set, the sound will be omnidirectional
  36076. this._coneInnerAngle = 360;
  36077. this._coneOuterAngle = 360;
  36078. this._coneOuterGain = 0;
  36079. this._isOutputConnected = false;
  36080. this._urlType = "Unknown";
  36081. this.name = name;
  36082. this._scene = scene;
  36083. this._readyToPlayCallback = readyToPlayCallback;
  36084. // Default custom attenuation function is a linear attenuation
  36085. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  36086. if (currentDistance < maxDistance) {
  36087. return currentVolume * (1 - currentDistance / maxDistance);
  36088. }
  36089. else {
  36090. return 0;
  36091. }
  36092. };
  36093. if (options) {
  36094. this.autoplay = options.autoplay || false;
  36095. this.loop = options.loop || false;
  36096. // if volume === 0, we need another way to check this option
  36097. if (options.volume !== undefined) {
  36098. this._volume = options.volume;
  36099. }
  36100. this.spatialSound = options.spatialSound || false;
  36101. this.maxDistance = options.maxDistance || 100;
  36102. this.useCustomAttenuation = options.useCustomAttenuation || false;
  36103. this.rolloffFactor = options.rolloffFactor || 1;
  36104. this.refDistance = options.refDistance || 1;
  36105. this.distanceModel = options.distanceModel || "linear";
  36106. this._playbackRate = options.playbackRate || 1;
  36107. this._streaming = options.streaming || false;
  36108. }
  36109. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36110. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  36111. this._soundGain.gain.value = this._volume;
  36112. this._inputAudioNode = this._soundGain;
  36113. this._ouputAudioNode = this._soundGain;
  36114. if (this.spatialSound) {
  36115. this._createSpatialParameters();
  36116. }
  36117. this._scene.mainSoundTrack.AddSound(this);
  36118. var validParameter = true;
  36119. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  36120. if (urlOrArrayBuffer) {
  36121. if (typeof (urlOrArrayBuffer) === "string")
  36122. this._urlType = "String";
  36123. if (Array.isArray(urlOrArrayBuffer))
  36124. this._urlType = "Array";
  36125. if (urlOrArrayBuffer instanceof ArrayBuffer)
  36126. this._urlType = "ArrayBuffer";
  36127. var urls = [];
  36128. var codecSupportedFound = false;
  36129. switch (this._urlType) {
  36130. case "ArrayBuffer":
  36131. if (urlOrArrayBuffer.byteLength > 0) {
  36132. codecSupportedFound = true;
  36133. this._soundLoaded(urlOrArrayBuffer);
  36134. }
  36135. break;
  36136. case "String":
  36137. urls.push(urlOrArrayBuffer);
  36138. case "Array":
  36139. if (urls.length === 0)
  36140. urls = urlOrArrayBuffer;
  36141. // If we found a supported format, we load it immediately and stop the loop
  36142. for (var i = 0; i < urls.length; i++) {
  36143. var url = urls[i];
  36144. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  36145. codecSupportedFound = true;
  36146. }
  36147. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  36148. codecSupportedFound = true;
  36149. }
  36150. if (url.indexOf(".wav", url.length - 4) !== -1) {
  36151. codecSupportedFound = true;
  36152. }
  36153. if (codecSupportedFound) {
  36154. // Loading sound using XHR2
  36155. if (!this._streaming) {
  36156. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  36157. }
  36158. else {
  36159. this._htmlAudioElement = new Audio(url);
  36160. this._htmlAudioElement.controls = false;
  36161. this._htmlAudioElement.loop = this.loop;
  36162. this._htmlAudioElement.crossOrigin = "anonymous";
  36163. this._htmlAudioElement.preload = "auto";
  36164. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  36165. _this._isReadyToPlay = true;
  36166. if (_this.autoplay) {
  36167. _this.play();
  36168. }
  36169. if (_this._readyToPlayCallback) {
  36170. _this._readyToPlayCallback();
  36171. }
  36172. });
  36173. document.body.appendChild(this._htmlAudioElement);
  36174. }
  36175. break;
  36176. }
  36177. }
  36178. break;
  36179. default:
  36180. validParameter = false;
  36181. break;
  36182. }
  36183. if (!validParameter) {
  36184. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  36185. }
  36186. else {
  36187. if (!codecSupportedFound) {
  36188. this._isReadyToPlay = true;
  36189. // Simulating a ready to play event to avoid breaking code path
  36190. if (this._readyToPlayCallback) {
  36191. window.setTimeout(function () {
  36192. _this._readyToPlayCallback();
  36193. }, 1000);
  36194. }
  36195. }
  36196. }
  36197. }
  36198. }
  36199. else {
  36200. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  36201. this._scene.mainSoundTrack.AddSound(this);
  36202. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  36203. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  36204. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  36205. }
  36206. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  36207. if (this._readyToPlayCallback) {
  36208. window.setTimeout(function () {
  36209. _this._readyToPlayCallback();
  36210. }, 1000);
  36211. }
  36212. }
  36213. }
  36214. Sound.prototype.dispose = function () {
  36215. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  36216. if (this.isPlaying) {
  36217. this.stop();
  36218. }
  36219. this._isReadyToPlay = false;
  36220. if (this.soundTrackId === -1) {
  36221. this._scene.mainSoundTrack.RemoveSound(this);
  36222. }
  36223. else {
  36224. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  36225. }
  36226. if (this._soundGain) {
  36227. this._soundGain.disconnect();
  36228. this._soundGain = null;
  36229. }
  36230. if (this._soundPanner) {
  36231. this._soundPanner.disconnect();
  36232. this._soundPanner = null;
  36233. }
  36234. if (this._soundSource) {
  36235. this._soundSource.disconnect();
  36236. this._soundSource = null;
  36237. }
  36238. this._audioBuffer = null;
  36239. if (this._htmlAudioElement) {
  36240. this._htmlAudioElement.pause();
  36241. this._htmlAudioElement.src = "";
  36242. document.body.removeChild(this._htmlAudioElement);
  36243. }
  36244. if (this._connectedMesh) {
  36245. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36246. this._connectedMesh = null;
  36247. }
  36248. }
  36249. };
  36250. Sound.prototype._soundLoaded = function (audioData) {
  36251. var _this = this;
  36252. this._isLoaded = true;
  36253. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  36254. _this._audioBuffer = buffer;
  36255. _this._isReadyToPlay = true;
  36256. if (_this.autoplay) {
  36257. _this.play();
  36258. }
  36259. if (_this._readyToPlayCallback) {
  36260. _this._readyToPlayCallback();
  36261. }
  36262. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  36263. };
  36264. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  36265. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36266. this._audioBuffer = audioBuffer;
  36267. this._isReadyToPlay = true;
  36268. }
  36269. };
  36270. Sound.prototype.updateOptions = function (options) {
  36271. if (options) {
  36272. this.loop = options.loop || this.loop;
  36273. this.maxDistance = options.maxDistance || this.maxDistance;
  36274. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  36275. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  36276. this.refDistance = options.refDistance || this.refDistance;
  36277. this.distanceModel = options.distanceModel || this.distanceModel;
  36278. this._playbackRate = options.playbackRate || this._playbackRate;
  36279. this._updateSpatialParameters();
  36280. if (this.isPlaying) {
  36281. if (this._streaming) {
  36282. this._htmlAudioElement.playbackRate = this._playbackRate;
  36283. }
  36284. else {
  36285. this._soundSource.playbackRate.value = this._playbackRate;
  36286. }
  36287. }
  36288. }
  36289. };
  36290. Sound.prototype._createSpatialParameters = function () {
  36291. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36292. if (this._scene.headphone) {
  36293. this._panningModel = "HRTF";
  36294. }
  36295. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  36296. this._updateSpatialParameters();
  36297. this._soundPanner.connect(this._ouputAudioNode);
  36298. this._inputAudioNode = this._soundPanner;
  36299. }
  36300. };
  36301. Sound.prototype._updateSpatialParameters = function () {
  36302. if (this.spatialSound) {
  36303. if (this.useCustomAttenuation) {
  36304. // Tricks to disable in a way embedded Web Audio attenuation
  36305. this._soundPanner.distanceModel = "linear";
  36306. this._soundPanner.maxDistance = Number.MAX_VALUE;
  36307. this._soundPanner.refDistance = 1;
  36308. this._soundPanner.rolloffFactor = 1;
  36309. this._soundPanner.panningModel = this._panningModel;
  36310. }
  36311. else {
  36312. this._soundPanner.distanceModel = this.distanceModel;
  36313. this._soundPanner.maxDistance = this.maxDistance;
  36314. this._soundPanner.refDistance = this.refDistance;
  36315. this._soundPanner.rolloffFactor = this.rolloffFactor;
  36316. this._soundPanner.panningModel = this._panningModel;
  36317. }
  36318. }
  36319. };
  36320. Sound.prototype.switchPanningModelToHRTF = function () {
  36321. this._panningModel = "HRTF";
  36322. this._switchPanningModel();
  36323. };
  36324. Sound.prototype.switchPanningModelToEqualPower = function () {
  36325. this._panningModel = "equalpower";
  36326. this._switchPanningModel();
  36327. };
  36328. Sound.prototype._switchPanningModel = function () {
  36329. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36330. this._soundPanner.panningModel = this._panningModel;
  36331. }
  36332. };
  36333. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  36334. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36335. if (this._isOutputConnected) {
  36336. this._ouputAudioNode.disconnect();
  36337. }
  36338. this._ouputAudioNode.connect(soundTrackAudioNode);
  36339. this._isOutputConnected = true;
  36340. }
  36341. };
  36342. /**
  36343. * Transform this sound into a directional source
  36344. * @param coneInnerAngle Size of the inner cone in degree
  36345. * @param coneOuterAngle Size of the outer cone in degree
  36346. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  36347. */
  36348. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  36349. if (coneOuterAngle < coneInnerAngle) {
  36350. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  36351. return;
  36352. }
  36353. this._coneInnerAngle = coneInnerAngle;
  36354. this._coneOuterAngle = coneOuterAngle;
  36355. this._coneOuterGain = coneOuterGain;
  36356. this._isDirectional = true;
  36357. if (this.isPlaying && this.loop) {
  36358. this.stop();
  36359. this.play();
  36360. }
  36361. };
  36362. Sound.prototype.setPosition = function (newPosition) {
  36363. this._position = newPosition;
  36364. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36365. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36366. }
  36367. };
  36368. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  36369. this._localDirection = newLocalDirection;
  36370. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  36371. this._updateDirection();
  36372. }
  36373. };
  36374. Sound.prototype._updateDirection = function () {
  36375. var mat = this._connectedMesh.getWorldMatrix();
  36376. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  36377. direction.normalize();
  36378. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  36379. };
  36380. Sound.prototype.updateDistanceFromListener = function () {
  36381. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  36382. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  36383. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  36384. }
  36385. };
  36386. Sound.prototype.setAttenuationFunction = function (callback) {
  36387. this._customAttenuationFunction = callback;
  36388. };
  36389. /**
  36390. * Play the sound
  36391. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  36392. * @param offset (optional) Start the sound setting it at a specific time
  36393. */
  36394. Sound.prototype.play = function (time, offset) {
  36395. var _this = this;
  36396. if (this._isReadyToPlay && this._scene.audioEnabled) {
  36397. try {
  36398. if (this._startOffset < 0) {
  36399. time = -this._startOffset;
  36400. this._startOffset = 0;
  36401. }
  36402. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36403. if (!this._soundSource || !this._streamingSource) {
  36404. if (this.spatialSound) {
  36405. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36406. if (this._isDirectional) {
  36407. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  36408. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  36409. this._soundPanner.coneOuterGain = this._coneOuterGain;
  36410. if (this._connectedMesh) {
  36411. this._updateDirection();
  36412. }
  36413. else {
  36414. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  36415. }
  36416. }
  36417. }
  36418. }
  36419. if (this._streaming) {
  36420. if (!this._streamingSource) {
  36421. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  36422. this._htmlAudioElement.onended = function () { _this._onended(); };
  36423. this._htmlAudioElement.playbackRate = this._playbackRate;
  36424. }
  36425. this._streamingSource.disconnect();
  36426. this._streamingSource.connect(this._inputAudioNode);
  36427. this._htmlAudioElement.play();
  36428. }
  36429. else {
  36430. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  36431. this._soundSource.buffer = this._audioBuffer;
  36432. this._soundSource.connect(this._inputAudioNode);
  36433. this._soundSource.loop = this.loop;
  36434. this._soundSource.playbackRate.value = this._playbackRate;
  36435. this._soundSource.onended = function () { _this._onended(); };
  36436. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  36437. }
  36438. this._startTime = startTime;
  36439. this.isPlaying = true;
  36440. this.isPaused = false;
  36441. }
  36442. catch (ex) {
  36443. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  36444. }
  36445. }
  36446. };
  36447. Sound.prototype._onended = function () {
  36448. this.isPlaying = false;
  36449. if (this.onended) {
  36450. this.onended();
  36451. }
  36452. };
  36453. /**
  36454. * Stop the sound
  36455. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  36456. */
  36457. Sound.prototype.stop = function (time) {
  36458. if (this.isPlaying) {
  36459. if (this._streaming) {
  36460. this._htmlAudioElement.pause();
  36461. // Test needed for Firefox or it will generate an Invalid State Error
  36462. if (this._htmlAudioElement.currentTime > 0) {
  36463. this._htmlAudioElement.currentTime = 0;
  36464. }
  36465. }
  36466. else {
  36467. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36468. this._soundSource.stop(stopTime);
  36469. this._soundSource.onended = null;
  36470. if (!this.isPaused) {
  36471. this._startOffset = 0;
  36472. }
  36473. }
  36474. this.isPlaying = false;
  36475. }
  36476. };
  36477. Sound.prototype.pause = function () {
  36478. if (this.isPlaying) {
  36479. this.isPaused = true;
  36480. if (this._streaming) {
  36481. this._htmlAudioElement.pause();
  36482. }
  36483. else {
  36484. this.stop(0);
  36485. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  36486. }
  36487. }
  36488. };
  36489. Sound.prototype.setVolume = function (newVolume, time) {
  36490. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36491. if (time) {
  36492. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  36493. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  36494. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  36495. }
  36496. else {
  36497. this._soundGain.gain.value = newVolume;
  36498. }
  36499. }
  36500. this._volume = newVolume;
  36501. };
  36502. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  36503. this._playbackRate = newPlaybackRate;
  36504. if (this.isPlaying) {
  36505. if (this._streaming) {
  36506. this._htmlAudioElement.playbackRate = this._playbackRate;
  36507. }
  36508. else {
  36509. this._soundSource.playbackRate.value = this._playbackRate;
  36510. }
  36511. }
  36512. };
  36513. Sound.prototype.getVolume = function () {
  36514. return this._volume;
  36515. };
  36516. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  36517. var _this = this;
  36518. if (this._connectedMesh) {
  36519. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36520. this._registerFunc = null;
  36521. }
  36522. this._connectedMesh = meshToConnectTo;
  36523. if (!this.spatialSound) {
  36524. this.spatialSound = true;
  36525. this._createSpatialParameters();
  36526. if (this.isPlaying && this.loop) {
  36527. this.stop();
  36528. this.play();
  36529. }
  36530. }
  36531. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  36532. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  36533. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  36534. };
  36535. Sound.prototype.detachFromMesh = function () {
  36536. if (this._connectedMesh) {
  36537. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36538. this._registerFunc = null;
  36539. this._connectedMesh = null;
  36540. }
  36541. };
  36542. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  36543. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  36544. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  36545. this._updateDirection();
  36546. }
  36547. };
  36548. Sound.prototype.clone = function () {
  36549. var _this = this;
  36550. if (!this._streaming) {
  36551. var setBufferAndRun = function () {
  36552. if (_this._isReadyToPlay) {
  36553. clonedSound._audioBuffer = _this.getAudioBuffer();
  36554. clonedSound._isReadyToPlay = true;
  36555. if (clonedSound.autoplay) {
  36556. clonedSound.play();
  36557. }
  36558. }
  36559. else {
  36560. window.setTimeout(setBufferAndRun, 300);
  36561. }
  36562. };
  36563. var currentOptions = {
  36564. autoplay: this.autoplay, loop: this.loop,
  36565. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  36566. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  36567. refDistance: this.refDistance, distanceModel: this.distanceModel
  36568. };
  36569. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  36570. if (this.useCustomAttenuation) {
  36571. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  36572. }
  36573. clonedSound.setPosition(this._position);
  36574. clonedSound.setPlaybackRate(this._playbackRate);
  36575. setBufferAndRun();
  36576. return clonedSound;
  36577. }
  36578. else {
  36579. return null;
  36580. }
  36581. };
  36582. Sound.prototype.getAudioBuffer = function () {
  36583. return this._audioBuffer;
  36584. };
  36585. Sound.prototype.serialize = function () {
  36586. var serializationObject = {
  36587. name: this.name,
  36588. url: this.name,
  36589. autoplay: this.autoplay,
  36590. loop: this.loop,
  36591. volume: this._volume,
  36592. spatialSound: this.spatialSound,
  36593. maxDistance: this.maxDistance,
  36594. rolloffFactor: this.rolloffFactor,
  36595. refDistance: this.refDistance,
  36596. distanceModel: this.distanceModel,
  36597. playbackRate: this._playbackRate,
  36598. panningModel: this._panningModel,
  36599. soundTrackId: this.soundTrackId
  36600. };
  36601. if (this.spatialSound) {
  36602. if (this._connectedMesh)
  36603. serializationObject.connectedMeshId = this._connectedMesh.id;
  36604. serializationObject.position = this._position.asArray();
  36605. serializationObject.refDistance = this.refDistance;
  36606. serializationObject.distanceModel = this.distanceModel;
  36607. serializationObject.isDirectional = this._isDirectional;
  36608. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  36609. serializationObject.coneInnerAngle = this._coneInnerAngle;
  36610. serializationObject.coneOuterAngle = this._coneOuterAngle;
  36611. serializationObject.coneOuterGain = this._coneOuterGain;
  36612. }
  36613. return serializationObject;
  36614. };
  36615. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  36616. var soundName = parsedSound.name;
  36617. var soundUrl;
  36618. if (parsedSound.url) {
  36619. soundUrl = rootUrl + parsedSound.url;
  36620. }
  36621. else {
  36622. soundUrl = rootUrl + soundName;
  36623. }
  36624. var options = {
  36625. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  36626. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  36627. rolloffFactor: parsedSound.rolloffFactor,
  36628. refDistance: parsedSound.refDistance,
  36629. distanceModel: parsedSound.distanceModel,
  36630. playbackRate: parsedSound.playbackRate
  36631. };
  36632. var newSound;
  36633. if (!sourceSound) {
  36634. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  36635. scene._addPendingData(newSound);
  36636. }
  36637. else {
  36638. var setBufferAndRun = function () {
  36639. if (sourceSound._isReadyToPlay) {
  36640. newSound._audioBuffer = sourceSound.getAudioBuffer();
  36641. newSound._isReadyToPlay = true;
  36642. if (newSound.autoplay) {
  36643. newSound.play();
  36644. }
  36645. }
  36646. else {
  36647. window.setTimeout(setBufferAndRun, 300);
  36648. }
  36649. };
  36650. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  36651. setBufferAndRun();
  36652. }
  36653. if (parsedSound.position) {
  36654. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  36655. newSound.setPosition(soundPosition);
  36656. }
  36657. if (parsedSound.isDirectional) {
  36658. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  36659. if (parsedSound.localDirectionToMesh) {
  36660. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  36661. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  36662. }
  36663. }
  36664. if (parsedSound.connectedMeshId) {
  36665. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  36666. if (connectedMesh) {
  36667. newSound.attachToMesh(connectedMesh);
  36668. }
  36669. }
  36670. return newSound;
  36671. };
  36672. return Sound;
  36673. }());
  36674. BABYLON.Sound = Sound;
  36675. })(BABYLON || (BABYLON = {}));
  36676. var BABYLON;
  36677. (function (BABYLON) {
  36678. var SoundTrack = (function () {
  36679. function SoundTrack(scene, options) {
  36680. this.id = -1;
  36681. this._isMainTrack = false;
  36682. this._isInitialized = false;
  36683. this._scene = scene;
  36684. this.soundCollection = new Array();
  36685. this._options = options;
  36686. if (!this._isMainTrack) {
  36687. this._scene.soundTracks.push(this);
  36688. this.id = this._scene.soundTracks.length - 1;
  36689. }
  36690. }
  36691. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  36692. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36693. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  36694. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  36695. if (this._options) {
  36696. if (this._options.volume) {
  36697. this._outputAudioNode.gain.value = this._options.volume;
  36698. }
  36699. if (this._options.mainTrack) {
  36700. this._isMainTrack = this._options.mainTrack;
  36701. }
  36702. }
  36703. this._isInitialized = true;
  36704. }
  36705. };
  36706. SoundTrack.prototype.dispose = function () {
  36707. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36708. if (this._connectedAnalyser) {
  36709. this._connectedAnalyser.stopDebugCanvas();
  36710. }
  36711. while (this.soundCollection.length) {
  36712. this.soundCollection[0].dispose();
  36713. }
  36714. if (this._outputAudioNode) {
  36715. this._outputAudioNode.disconnect();
  36716. }
  36717. this._outputAudioNode = null;
  36718. }
  36719. };
  36720. SoundTrack.prototype.AddSound = function (sound) {
  36721. if (!this._isInitialized) {
  36722. this._initializeSoundTrackAudioGraph();
  36723. }
  36724. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36725. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  36726. }
  36727. if (sound.soundTrackId) {
  36728. if (sound.soundTrackId === -1) {
  36729. this._scene.mainSoundTrack.RemoveSound(sound);
  36730. }
  36731. else {
  36732. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  36733. }
  36734. }
  36735. this.soundCollection.push(sound);
  36736. sound.soundTrackId = this.id;
  36737. };
  36738. SoundTrack.prototype.RemoveSound = function (sound) {
  36739. var index = this.soundCollection.indexOf(sound);
  36740. if (index !== -1) {
  36741. this.soundCollection.splice(index, 1);
  36742. }
  36743. };
  36744. SoundTrack.prototype.setVolume = function (newVolume) {
  36745. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36746. this._outputAudioNode.gain.value = newVolume;
  36747. }
  36748. };
  36749. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  36750. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36751. for (var i = 0; i < this.soundCollection.length; i++) {
  36752. this.soundCollection[i].switchPanningModelToHRTF();
  36753. }
  36754. }
  36755. };
  36756. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  36757. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36758. for (var i = 0; i < this.soundCollection.length; i++) {
  36759. this.soundCollection[i].switchPanningModelToEqualPower();
  36760. }
  36761. }
  36762. };
  36763. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  36764. if (this._connectedAnalyser) {
  36765. this._connectedAnalyser.stopDebugCanvas();
  36766. }
  36767. this._connectedAnalyser = analyser;
  36768. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36769. this._outputAudioNode.disconnect();
  36770. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  36771. }
  36772. };
  36773. return SoundTrack;
  36774. }());
  36775. BABYLON.SoundTrack = SoundTrack;
  36776. })(BABYLON || (BABYLON = {}));
  36777. var BABYLON;
  36778. (function (BABYLON) {
  36779. /**
  36780. * Special Glow Blur post process only blurring the alpha channel
  36781. * It enforces keeping the most luminous color in the color channel.
  36782. */
  36783. var GlowBlurPostProcess = (function (_super) {
  36784. __extends(GlowBlurPostProcess, _super);
  36785. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  36786. var _this = this;
  36787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36788. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  36789. this.direction = direction;
  36790. this.blurWidth = blurWidth;
  36791. this.onApplyObservable.add(function (effect) {
  36792. effect.setFloat2("screenSize", _this.width, _this.height);
  36793. effect.setVector2("direction", _this.direction);
  36794. effect.setFloat("blurWidth", _this.blurWidth);
  36795. });
  36796. }
  36797. return GlowBlurPostProcess;
  36798. }(BABYLON.PostProcess));
  36799. /**
  36800. * The highlight layer Helps adding a glow effect around a mesh.
  36801. *
  36802. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  36803. * glowy meshes to your scene.
  36804. *
  36805. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  36806. */
  36807. var HighlightLayer = (function () {
  36808. /**
  36809. * Instantiates a new highlight Layer and references it to the scene..
  36810. * @param name The name of the layer
  36811. * @param scene The scene to use the layer in
  36812. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  36813. */
  36814. function HighlightLayer(name, scene, options) {
  36815. this._vertexBuffers = {};
  36816. this._mainTextureDesiredSize = { width: 0, height: 0 };
  36817. this._meshes = {};
  36818. this._maxSize = 0;
  36819. this._shouldRender = false;
  36820. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  36821. this._excludedMeshes = {};
  36822. /**
  36823. * Specifies whether or not the inner glow is ACTIVE in the layer.
  36824. */
  36825. this.innerGlow = true;
  36826. /**
  36827. * Specifies whether or not the outer glow is ACTIVE in the layer.
  36828. */
  36829. this.outerGlow = true;
  36830. /**
  36831. * Helps enabling disabling the highlight depending on the layers being rendered.
  36832. */
  36833. this.layerMask = 0xFFFFFFFF;
  36834. /**
  36835. * An event triggered when the highlight layer has been disposed.
  36836. * @type {BABYLON.Observable}
  36837. */
  36838. this.onDisposeObservable = new BABYLON.Observable();
  36839. /**
  36840. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  36841. * @type {BABYLON.Observable}
  36842. */
  36843. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  36844. /**
  36845. * An event triggered when the highlight layer is being blurred.
  36846. * @type {BABYLON.Observable}
  36847. */
  36848. this.onBeforeBlurObservable = new BABYLON.Observable();
  36849. /**
  36850. * An event triggered when the highlight layer has been blurred.
  36851. * @type {BABYLON.Observable}
  36852. */
  36853. this.onAfterBlurObservable = new BABYLON.Observable();
  36854. /**
  36855. * An event triggered when the glowing blurred texture is being merged in the scene.
  36856. * @type {BABYLON.Observable}
  36857. */
  36858. this.onBeforeComposeObservable = new BABYLON.Observable();
  36859. /**
  36860. * An event triggered when the glowing blurred texture has been merged in the scene.
  36861. * @type {BABYLON.Observable}
  36862. */
  36863. this.onAfterComposeObservable = new BABYLON.Observable();
  36864. /**
  36865. * An event triggered when the highlight layer changes its size.
  36866. * @type {BABYLON.Observable}
  36867. */
  36868. this.onSizeChangedObservable = new BABYLON.Observable();
  36869. this._scene = scene;
  36870. var engine = scene.getEngine();
  36871. this._engine = engine;
  36872. this._maxSize = this._engine.getCaps().maxTextureSize;
  36873. this._scene.highlightLayers.push(this);
  36874. // Warn on stencil.
  36875. if (!this._engine.isStencilEnable) {
  36876. 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 }");
  36877. }
  36878. // Adapt options
  36879. this._options = options || {
  36880. mainTextureRatio: 0.25,
  36881. blurTextureSizeRatio: 0.5,
  36882. blurHorizontalSize: 1,
  36883. blurVerticalSize: 1,
  36884. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  36885. };
  36886. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  36887. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  36888. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  36889. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  36890. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  36891. // VBO
  36892. var vertices = [];
  36893. vertices.push(1, 1);
  36894. vertices.push(-1, 1);
  36895. vertices.push(-1, -1);
  36896. vertices.push(1, -1);
  36897. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36898. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  36899. // Indices
  36900. var indices = [];
  36901. indices.push(0);
  36902. indices.push(1);
  36903. indices.push(2);
  36904. indices.push(0);
  36905. indices.push(2);
  36906. indices.push(3);
  36907. this._indexBuffer = engine.createIndexBuffer(indices);
  36908. // Effect
  36909. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  36910. // Render target
  36911. this.setMainTextureSize();
  36912. // Create Textures and post processes
  36913. this.createTextureAndPostProcesses();
  36914. }
  36915. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  36916. /**
  36917. * Gets the horizontal size of the blur.
  36918. */
  36919. get: function () {
  36920. return this._horizontalBlurPostprocess.blurWidth;
  36921. },
  36922. /**
  36923. * Specifies the horizontal size of the blur.
  36924. */
  36925. set: function (value) {
  36926. this._horizontalBlurPostprocess.blurWidth = value;
  36927. },
  36928. enumerable: true,
  36929. configurable: true
  36930. });
  36931. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  36932. /**
  36933. * Gets the vertical size of the blur.
  36934. */
  36935. get: function () {
  36936. return this._verticalBlurPostprocess.blurWidth;
  36937. },
  36938. /**
  36939. * Specifies the vertical size of the blur.
  36940. */
  36941. set: function (value) {
  36942. this._verticalBlurPostprocess.blurWidth = value;
  36943. },
  36944. enumerable: true,
  36945. configurable: true
  36946. });
  36947. /**
  36948. * Creates the render target textures and post processes used in the highlight layer.
  36949. */
  36950. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  36951. var _this = this;
  36952. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  36953. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  36954. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  36955. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  36956. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  36957. width: this._mainTextureDesiredSize.width,
  36958. height: this._mainTextureDesiredSize.height
  36959. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36960. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36961. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36962. this._mainTexture.anisotropicFilteringLevel = 1;
  36963. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36964. this._mainTexture.renderParticles = false;
  36965. this._mainTexture.renderList = null;
  36966. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  36967. width: blurTextureWidth,
  36968. height: blurTextureHeight
  36969. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36970. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36971. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36972. this._blurTexture.anisotropicFilteringLevel = 16;
  36973. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36974. this._blurTexture.renderParticles = false;
  36975. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36976. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  36977. effect.setTexture("textureSampler", _this._mainTexture);
  36978. });
  36979. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36980. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  36981. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  36982. });
  36983. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36984. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  36985. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  36986. });
  36987. this._mainTexture.onAfterUnbindObservable.add(function () {
  36988. _this.onBeforeBlurObservable.notifyObservers(_this);
  36989. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  36990. _this.onAfterBlurObservable.notifyObservers(_this);
  36991. });
  36992. // Custom render function
  36993. var renderSubMesh = function (subMesh) {
  36994. var mesh = subMesh.getRenderingMesh();
  36995. var scene = _this._scene;
  36996. var engine = scene.getEngine();
  36997. // Culling
  36998. engine.setState(subMesh.getMaterial().backFaceCulling);
  36999. // Managing instances
  37000. var batch = mesh._getInstancesRenderList(subMesh._id);
  37001. if (batch.mustReturn) {
  37002. return;
  37003. }
  37004. // Excluded Mesh
  37005. if (_this._excludedMeshes[mesh.id]) {
  37006. return;
  37007. }
  37008. ;
  37009. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37010. var highlightLayerMesh = _this._meshes[mesh.id];
  37011. var material = subMesh.getMaterial();
  37012. var emissiveTexture = null;
  37013. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  37014. emissiveTexture = material.emissiveTexture;
  37015. }
  37016. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  37017. engine.enableEffect(_this._glowMapGenerationEffect);
  37018. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  37019. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  37020. if (highlightLayerMesh) {
  37021. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  37022. }
  37023. else {
  37024. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  37025. }
  37026. // Alpha test
  37027. if (material && material.needAlphaTesting()) {
  37028. var alphaTexture = material.getAlphaTestTexture();
  37029. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  37030. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37031. }
  37032. // Glow emissive only
  37033. if (emissiveTexture) {
  37034. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  37035. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  37036. }
  37037. // Bones
  37038. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37039. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37040. }
  37041. // Draw
  37042. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  37043. }
  37044. else {
  37045. // Need to reset refresh rate of the shadowMap
  37046. _this._mainTexture.resetRefreshCounter();
  37047. }
  37048. };
  37049. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  37050. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  37051. var index;
  37052. for (index = 0; index < opaqueSubMeshes.length; index++) {
  37053. renderSubMesh(opaqueSubMeshes.data[index]);
  37054. }
  37055. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  37056. renderSubMesh(alphaTestSubMeshes.data[index]);
  37057. }
  37058. for (index = 0; index < transparentSubMeshes.length; index++) {
  37059. renderSubMesh(transparentSubMeshes.data[index]);
  37060. }
  37061. };
  37062. this._mainTexture.onClearObservable.add(function (engine) {
  37063. engine.clear(HighlightLayer.neutralColor, true, true, true);
  37064. });
  37065. };
  37066. /**
  37067. * Checks for the readiness of the element composing the layer.
  37068. * @param subMesh the mesh to check for
  37069. * @param useInstances specify wether or not to use instances to render the mesh
  37070. * @param emissiveTexture the associated emissive texture used to generate the glow
  37071. * @return true if ready otherwise, false
  37072. */
  37073. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  37074. if (!subMesh.getMaterial().isReady()) {
  37075. return false;
  37076. }
  37077. var defines = [];
  37078. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37079. var mesh = subMesh.getMesh();
  37080. var material = subMesh.getMaterial();
  37081. var uv1 = false;
  37082. var uv2 = false;
  37083. // Alpha test
  37084. if (material && material.needAlphaTesting()) {
  37085. var alphaTexture = material.getAlphaTestTexture();
  37086. if (alphaTexture) {
  37087. defines.push("#define ALPHATEST");
  37088. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37089. alphaTexture.coordinatesIndex === 1) {
  37090. defines.push("#define DIFFUSEUV2");
  37091. uv2 = true;
  37092. }
  37093. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37094. defines.push("#define DIFFUSEUV1");
  37095. uv1 = true;
  37096. }
  37097. }
  37098. }
  37099. // Emissive
  37100. if (emissiveTexture) {
  37101. defines.push("#define EMISSIVE");
  37102. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37103. emissiveTexture.coordinatesIndex === 1) {
  37104. defines.push("#define EMISSIVEUV2");
  37105. uv2 = true;
  37106. }
  37107. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37108. defines.push("#define EMISSIVEUV1");
  37109. uv1 = true;
  37110. }
  37111. }
  37112. if (uv1) {
  37113. attribs.push(BABYLON.VertexBuffer.UVKind);
  37114. defines.push("#define UV1");
  37115. }
  37116. if (uv2) {
  37117. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37118. defines.push("#define UV2");
  37119. }
  37120. // Bones
  37121. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37122. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37123. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37124. if (mesh.numBoneInfluencers > 4) {
  37125. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37126. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37127. }
  37128. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37129. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37130. }
  37131. else {
  37132. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37133. }
  37134. // Instances
  37135. if (useInstances) {
  37136. defines.push("#define INSTANCES");
  37137. attribs.push("world0");
  37138. attribs.push("world1");
  37139. attribs.push("world2");
  37140. attribs.push("world3");
  37141. }
  37142. // Get correct effect
  37143. var join = defines.join("\n");
  37144. if (this._cachedDefines !== join) {
  37145. this._cachedDefines = join;
  37146. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  37147. }
  37148. return this._glowMapGenerationEffect.isReady();
  37149. };
  37150. /**
  37151. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  37152. */
  37153. HighlightLayer.prototype.render = function () {
  37154. var currentEffect = this._glowMapMergeEffect;
  37155. // Check
  37156. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  37157. return;
  37158. var engine = this._scene.getEngine();
  37159. this.onBeforeComposeObservable.notifyObservers(this);
  37160. // Render
  37161. engine.enableEffect(currentEffect);
  37162. engine.setState(false);
  37163. // Cache
  37164. var previousStencilBuffer = engine.getStencilBuffer();
  37165. var previousStencilFunction = engine.getStencilFunction();
  37166. var previousStencilMask = engine.getStencilMask();
  37167. var previousAlphaMode = engine.getAlphaMode();
  37168. // Texture
  37169. currentEffect.setTexture("textureSampler", this._blurTexture);
  37170. // VBOs
  37171. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  37172. // Draw order
  37173. engine.setAlphaMode(this._options.alphaBlendingMode);
  37174. engine.setStencilMask(0x00);
  37175. engine.setStencilBuffer(true);
  37176. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  37177. if (this.outerGlow) {
  37178. currentEffect.setFloat("offset", 0);
  37179. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  37180. engine.draw(true, 0, 6);
  37181. }
  37182. if (this.innerGlow) {
  37183. currentEffect.setFloat("offset", 1);
  37184. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  37185. engine.draw(true, 0, 6);
  37186. }
  37187. // Restore Cache
  37188. engine.setStencilFunction(previousStencilFunction);
  37189. engine.setStencilMask(previousStencilMask);
  37190. engine.setAlphaMode(previousAlphaMode);
  37191. engine.setStencilBuffer(previousStencilBuffer);
  37192. this.onAfterComposeObservable.notifyObservers(this);
  37193. // Handle size changes.
  37194. var size = this._mainTexture.getSize();
  37195. this.setMainTextureSize();
  37196. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  37197. // Recreate RTT and post processes on size change.
  37198. this.onSizeChangedObservable.notifyObservers(this);
  37199. this.disposeTextureAndPostProcesses();
  37200. this.createTextureAndPostProcesses();
  37201. }
  37202. };
  37203. /**
  37204. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  37205. * @param mesh The mesh to exclude from the highlight layer
  37206. */
  37207. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  37208. var meshExcluded = this._excludedMeshes[mesh.id];
  37209. if (!meshExcluded) {
  37210. this._excludedMeshes[mesh.id] = {
  37211. mesh: mesh,
  37212. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  37213. mesh.getEngine().setStencilBuffer(false);
  37214. }),
  37215. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  37216. mesh.getEngine().setStencilBuffer(true);
  37217. }),
  37218. };
  37219. }
  37220. };
  37221. /**
  37222. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  37223. * @param mesh The mesh to highlight
  37224. */
  37225. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  37226. var meshExcluded = this._excludedMeshes[mesh.id];
  37227. if (meshExcluded) {
  37228. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  37229. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  37230. }
  37231. this._excludedMeshes[mesh.id] = undefined;
  37232. };
  37233. /**
  37234. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  37235. * @param mesh The mesh to highlight
  37236. * @param color The color of the highlight
  37237. * @param glowEmissiveOnly Extract the glow from the emissive texture
  37238. */
  37239. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  37240. var _this = this;
  37241. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  37242. var meshHighlight = this._meshes[mesh.id];
  37243. if (meshHighlight) {
  37244. meshHighlight.color = color;
  37245. }
  37246. else {
  37247. this._meshes[mesh.id] = {
  37248. mesh: mesh,
  37249. color: color,
  37250. // Lambda required for capture due to Observable this context
  37251. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  37252. if (_this._excludedMeshes[mesh.id]) {
  37253. _this.defaultStencilReference(mesh);
  37254. }
  37255. else {
  37256. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  37257. }
  37258. }),
  37259. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  37260. glowEmissiveOnly: glowEmissiveOnly
  37261. };
  37262. }
  37263. this._shouldRender = true;
  37264. };
  37265. /**
  37266. * Remove a mesh from the highlight layer in order to make it stop glowing.
  37267. * @param mesh The mesh to highlight
  37268. */
  37269. HighlightLayer.prototype.removeMesh = function (mesh) {
  37270. var meshHighlight = this._meshes[mesh.id];
  37271. if (meshHighlight) {
  37272. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37273. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37274. }
  37275. this._meshes[mesh.id] = undefined;
  37276. this._shouldRender = false;
  37277. for (var meshHighlightToCheck in this._meshes) {
  37278. if (meshHighlightToCheck) {
  37279. this._shouldRender = true;
  37280. break;
  37281. }
  37282. }
  37283. };
  37284. /**
  37285. * Returns true if the layer contains information to display, otherwise false.
  37286. */
  37287. HighlightLayer.prototype.shouldRender = function () {
  37288. return this._shouldRender;
  37289. };
  37290. /**
  37291. * Sets the main texture desired size which is the closest power of two
  37292. * of the engine canvas size.
  37293. */
  37294. HighlightLayer.prototype.setMainTextureSize = function () {
  37295. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  37296. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  37297. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  37298. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  37299. };
  37300. /**
  37301. * Force the stencil to the normal expected value for none glowing parts
  37302. */
  37303. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  37304. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  37305. };
  37306. /**
  37307. * Dispose only the render target textures and post process.
  37308. */
  37309. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  37310. this._blurTexture.dispose();
  37311. this._mainTexture.dispose();
  37312. this._downSamplePostprocess.dispose();
  37313. this._horizontalBlurPostprocess.dispose();
  37314. this._verticalBlurPostprocess.dispose();
  37315. };
  37316. /**
  37317. * Dispose the highlight layer and free resources.
  37318. */
  37319. HighlightLayer.prototype.dispose = function () {
  37320. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37321. if (vertexBuffer) {
  37322. vertexBuffer.dispose();
  37323. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37324. }
  37325. if (this._indexBuffer) {
  37326. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37327. this._indexBuffer = null;
  37328. }
  37329. // Clean textures and post processes
  37330. this.disposeTextureAndPostProcesses();
  37331. // Clean mesh references
  37332. for (var id in this._meshes) {
  37333. var meshHighlight = this._meshes[id];
  37334. if (meshHighlight && meshHighlight.mesh) {
  37335. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37336. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37337. }
  37338. }
  37339. this._meshes = null;
  37340. for (var id in this._excludedMeshes) {
  37341. var meshHighlight = this._excludedMeshes[id];
  37342. if (meshHighlight) {
  37343. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  37344. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  37345. }
  37346. }
  37347. this._excludedMeshes = null;
  37348. // Remove from scene
  37349. var index = this._scene.highlightLayers.indexOf(this, 0);
  37350. if (index > -1) {
  37351. this._scene.highlightLayers.splice(index, 1);
  37352. }
  37353. // Callback
  37354. this.onDisposeObservable.notifyObservers(this);
  37355. this.onDisposeObservable.clear();
  37356. this.onBeforeRenderMainTextureObservable.clear();
  37357. this.onBeforeBlurObservable.clear();
  37358. this.onBeforeComposeObservable.clear();
  37359. this.onAfterComposeObservable.clear();
  37360. this.onSizeChangedObservable.clear();
  37361. };
  37362. /**
  37363. * The neutral color used during the preparation of the glow effect.
  37364. * This is black by default as the blend operation is a blend operation.
  37365. */
  37366. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  37367. /**
  37368. * Stencil value used for glowing meshes.
  37369. */
  37370. HighlightLayer.glowingMeshStencilReference = 0x02;
  37371. /**
  37372. * Stencil value used for the other meshes in the scene.
  37373. */
  37374. HighlightLayer.normalMeshStencilReference = 0x01;
  37375. return HighlightLayer;
  37376. }());
  37377. BABYLON.HighlightLayer = HighlightLayer;
  37378. })(BABYLON || (BABYLON = {}));
  37379. var BABYLON;
  37380. (function (BABYLON) {
  37381. var SIMDVector3 = (function () {
  37382. function SIMDVector3() {
  37383. }
  37384. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  37385. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  37386. };
  37387. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  37388. var m = transformation.m;
  37389. var m0 = SIMD.Float32x4.load(m, 0);
  37390. var m1 = SIMD.Float32x4.load(m, 4);
  37391. var m2 = SIMD.Float32x4.load(m, 8);
  37392. var m3 = SIMD.Float32x4.load(m, 12);
  37393. 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));
  37394. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  37395. result.x = SIMD.Float32x4.extractLane(r, 0);
  37396. result.y = SIMD.Float32x4.extractLane(r, 1);
  37397. result.z = SIMD.Float32x4.extractLane(r, 2);
  37398. };
  37399. return SIMDVector3;
  37400. }());
  37401. var SIMDMatrix = (function () {
  37402. function SIMDMatrix() {
  37403. }
  37404. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  37405. var tm = this.m;
  37406. var om = other.m;
  37407. var m0 = SIMD.Float32x4.load(om, 0);
  37408. var m1 = SIMD.Float32x4.load(om, 4);
  37409. var m2 = SIMD.Float32x4.load(om, 8);
  37410. var m3 = SIMD.Float32x4.load(om, 12);
  37411. for (var i = 0; i < 16; i += 4) {
  37412. 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)))));
  37413. }
  37414. return this;
  37415. };
  37416. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  37417. var src = this.m;
  37418. var dest = other.m;
  37419. // Load the 4 rows
  37420. var src0 = SIMD.Float32x4.load(src, 0);
  37421. var src1 = SIMD.Float32x4.load(src, 4);
  37422. var src2 = SIMD.Float32x4.load(src, 8);
  37423. var src3 = SIMD.Float32x4.load(src, 12);
  37424. // Transpose the source matrix. Sort of. Not a true transpose operation
  37425. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  37426. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  37427. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  37428. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  37429. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  37430. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  37431. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  37432. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  37433. // This is a true transposition, but it will lead to an incorrect result
  37434. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  37435. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  37436. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37437. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37438. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  37439. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  37440. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37441. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37442. // ----
  37443. tmp1 = SIMD.Float32x4.mul(row2, row3);
  37444. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37445. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  37446. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  37447. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37448. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  37449. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  37450. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  37451. // ----
  37452. tmp1 = SIMD.Float32x4.mul(row1, row2);
  37453. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37454. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  37455. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  37456. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37457. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  37458. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  37459. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  37460. // ----
  37461. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  37462. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37463. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  37464. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  37465. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  37466. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37467. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  37468. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  37469. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  37470. // ----
  37471. tmp1 = SIMD.Float32x4.mul(row0, row1);
  37472. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37473. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37474. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  37475. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37476. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37477. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  37478. // ----
  37479. tmp1 = SIMD.Float32x4.mul(row0, row3);
  37480. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37481. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  37482. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  37483. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37484. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  37485. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  37486. // ----
  37487. tmp1 = SIMD.Float32x4.mul(row0, row2);
  37488. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37489. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  37490. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  37491. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37492. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  37493. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  37494. // Compute determinant
  37495. var det = SIMD.Float32x4.mul(row0, minor0);
  37496. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  37497. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  37498. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  37499. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  37500. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  37501. // These shuffles aren't necessary if the faulty transposition is done
  37502. // up at the top of this function.
  37503. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  37504. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  37505. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  37506. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  37507. // Compute final values by multiplying with 1/det
  37508. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  37509. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  37510. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  37511. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  37512. return this;
  37513. };
  37514. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  37515. var out = result.m;
  37516. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  37517. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  37518. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  37519. // cc.kmVec3Subtract(f, pCenter, pEye);
  37520. var f = SIMD.Float32x4.sub(center, eye);
  37521. // cc.kmVec3Normalize(f, f);
  37522. var tmp = SIMD.Float32x4.mul(f, f);
  37523. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37524. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37525. // cc.kmVec3Assign(up, pUp);
  37526. // cc.kmVec3Normalize(up, up);
  37527. tmp = SIMD.Float32x4.mul(up, up);
  37528. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37529. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37530. // cc.kmVec3Cross(s, f, up);
  37531. 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)));
  37532. // cc.kmVec3Normalize(s, s);
  37533. tmp = SIMD.Float32x4.mul(s, s);
  37534. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37535. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37536. // cc.kmVec3Cross(u, s, f);
  37537. 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)));
  37538. // cc.kmVec3Normalize(s, s);
  37539. tmp = SIMD.Float32x4.mul(s, s);
  37540. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37541. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37542. var zero = SIMD.Float32x4.splat(0.0);
  37543. s = SIMD.Float32x4.neg(s);
  37544. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  37545. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  37546. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  37547. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  37548. 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);
  37549. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  37550. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  37551. 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)))));
  37552. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  37553. 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)))));
  37554. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  37555. 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)))));
  37556. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  37557. 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)))));
  37558. };
  37559. return SIMDMatrix;
  37560. }());
  37561. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  37562. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  37563. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  37564. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  37565. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  37566. var SIMDHelper = (function () {
  37567. function SIMDHelper() {
  37568. }
  37569. Object.defineProperty(SIMDHelper, "IsEnabled", {
  37570. get: function () {
  37571. return SIMDHelper._isEnabled;
  37572. },
  37573. enumerable: true,
  37574. configurable: true
  37575. });
  37576. SIMDHelper.DisableSIMD = function () {
  37577. // Replace functions
  37578. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  37579. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  37580. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  37581. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  37582. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  37583. SIMDHelper._isEnabled = false;
  37584. };
  37585. SIMDHelper.EnableSIMD = function () {
  37586. if (self.SIMD === undefined) {
  37587. return;
  37588. }
  37589. // check if polyfills needed
  37590. if (!self.Math.fround) {
  37591. self.Math.fround = (function (array) { return function (x) {
  37592. return array[0] = x, array[0];
  37593. }; })(new Float32Array(1));
  37594. }
  37595. if (!self.Math.imul) {
  37596. self.Math.imul = function (a, b) {
  37597. var ah = (a >>> 16) & 0xffff;
  37598. var al = a & 0xffff;
  37599. var bh = (b >>> 16) & 0xffff;
  37600. var bl = b & 0xffff;
  37601. // the shift by 0 fixes the sign on the high part
  37602. // the final |0 converts the unsigned value into a signed value
  37603. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  37604. };
  37605. }
  37606. // Replace functions
  37607. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  37608. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  37609. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  37610. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  37611. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  37612. SIMDHelper._isEnabled = true;
  37613. };
  37614. SIMDHelper._isEnabled = false;
  37615. return SIMDHelper;
  37616. }());
  37617. BABYLON.SIMDHelper = SIMDHelper;
  37618. })(BABYLON || (BABYLON = {}));
  37619. var BABYLON;
  37620. (function (BABYLON) {
  37621. /**
  37622. * This class describe a rectangle that were added to the map.
  37623. * You have access to its coordinates either in pixel or normalized (UV)
  37624. */
  37625. var PackedRect = (function () {
  37626. function PackedRect(root, parent, pos, size) {
  37627. this._pos = pos;
  37628. this._size = size;
  37629. this._root = root;
  37630. this._parent = parent;
  37631. }
  37632. Object.defineProperty(PackedRect.prototype, "pos", {
  37633. /**
  37634. * @returns the position of this node into the map
  37635. */
  37636. get: function () {
  37637. return this._pos;
  37638. },
  37639. enumerable: true,
  37640. configurable: true
  37641. });
  37642. Object.defineProperty(PackedRect.prototype, "contentSize", {
  37643. /**
  37644. * @returns the size of the rectangle this node handles
  37645. */
  37646. get: function () {
  37647. return this._contentSize;
  37648. },
  37649. enumerable: true,
  37650. configurable: true
  37651. });
  37652. Object.defineProperty(PackedRect.prototype, "UVs", {
  37653. /**
  37654. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  37655. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  37656. */
  37657. get: function () {
  37658. return this.getUVsForCustomSize(this._root._size);
  37659. },
  37660. enumerable: true,
  37661. configurable: true
  37662. });
  37663. /**
  37664. * 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.
  37665. * This method will return the UVs for this part by given the custom size of what you really use
  37666. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  37667. */
  37668. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  37669. var mainWidth = this._root._size.width;
  37670. var mainHeight = this._root._size.height;
  37671. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  37672. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  37673. var uvs = new Array();
  37674. uvs.push(topLeft);
  37675. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  37676. uvs.push(rightBottom);
  37677. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  37678. return uvs;
  37679. };
  37680. /**
  37681. * Free this rectangle from the map.
  37682. * Call this method when you no longer need the rectangle to be in the map.
  37683. */
  37684. PackedRect.prototype.freeContent = function () {
  37685. if (!this.contentSize) {
  37686. return;
  37687. }
  37688. this._contentSize = null;
  37689. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  37690. this.attemptDefrag();
  37691. };
  37692. Object.defineProperty(PackedRect.prototype, "isUsed", {
  37693. get: function () {
  37694. return this._contentSize != null || this._leftNode != null;
  37695. },
  37696. enumerable: true,
  37697. configurable: true
  37698. });
  37699. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  37700. var node = this.findNode(contentSize);
  37701. // Not enough space...
  37702. if (!node) {
  37703. return null;
  37704. }
  37705. node.splitNode(contentSize);
  37706. return node;
  37707. };
  37708. PackedRect.prototype.findNode = function (size) {
  37709. var resNode = null;
  37710. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  37711. if (this.isUsed) {
  37712. if (this._leftNode) {
  37713. resNode = this._leftNode.findNode(size);
  37714. }
  37715. if (!resNode && this._rightNode) {
  37716. resNode = this._rightNode.findNode(size);
  37717. }
  37718. if (!resNode && this._bottomNode) {
  37719. resNode = this._bottomNode.findNode(size);
  37720. }
  37721. }
  37722. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  37723. resNode = this;
  37724. }
  37725. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  37726. resNode = this;
  37727. }
  37728. return resNode;
  37729. };
  37730. PackedRect.prototype.splitNode = function (contentSize) {
  37731. // 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)
  37732. if (!this._contentSize && this._initialSize) {
  37733. 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));
  37734. return this._leftNode.splitNode(contentSize);
  37735. }
  37736. else {
  37737. this._contentSize = contentSize.clone();
  37738. this._initialSize = contentSize.clone();
  37739. if (contentSize.width !== this._size.width) {
  37740. 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));
  37741. }
  37742. if (contentSize.height !== this._size.height) {
  37743. 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));
  37744. }
  37745. return this;
  37746. }
  37747. };
  37748. PackedRect.prototype.attemptDefrag = function () {
  37749. if (!this.isUsed && this.isRecursiveFree) {
  37750. this.clearNode();
  37751. if (this._parent) {
  37752. this._parent.attemptDefrag();
  37753. }
  37754. }
  37755. };
  37756. PackedRect.prototype.clearNode = function () {
  37757. this._initialSize = null;
  37758. this._rightNode = null;
  37759. this._bottomNode = null;
  37760. };
  37761. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  37762. get: function () {
  37763. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  37764. },
  37765. enumerable: true,
  37766. configurable: true
  37767. });
  37768. PackedRect.prototype.evalFreeSize = function (size) {
  37769. var levelSize = 0;
  37770. if (!this.isUsed) {
  37771. if (this._initialSize) {
  37772. levelSize = this._initialSize.surface;
  37773. }
  37774. else {
  37775. levelSize = this._size.surface;
  37776. }
  37777. }
  37778. if (this._rightNode) {
  37779. levelSize += this._rightNode.evalFreeSize(0);
  37780. }
  37781. if (this._bottomNode) {
  37782. levelSize += this._bottomNode.evalFreeSize(0);
  37783. }
  37784. return levelSize + size;
  37785. };
  37786. return PackedRect;
  37787. }());
  37788. BABYLON.PackedRect = PackedRect;
  37789. /**
  37790. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  37791. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  37792. * 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.
  37793. */
  37794. var RectPackingMap = (function (_super) {
  37795. __extends(RectPackingMap, _super);
  37796. /**
  37797. * Create an instance of the object with a dimension using the given size
  37798. * @param size The dimension of the rectangle that will contain all the sub ones.
  37799. */
  37800. function RectPackingMap(size) {
  37801. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  37802. this._root = this;
  37803. }
  37804. /**
  37805. * Add a rectangle, finding the best location to store it into the map
  37806. * @param size the dimension of the rectangle to store
  37807. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  37808. */
  37809. RectPackingMap.prototype.addRect = function (size) {
  37810. var node = this.findAndSplitNode(size);
  37811. return node;
  37812. };
  37813. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  37814. /**
  37815. * Return the current space free normalized between [0;1]
  37816. * @returns {}
  37817. */
  37818. get: function () {
  37819. var freeSize = 0;
  37820. freeSize = this.evalFreeSize(freeSize);
  37821. return freeSize / (this._size.width * this._size.height);
  37822. },
  37823. enumerable: true,
  37824. configurable: true
  37825. });
  37826. return RectPackingMap;
  37827. }(PackedRect));
  37828. BABYLON.RectPackingMap = RectPackingMap;
  37829. })(BABYLON || (BABYLON = {}));
  37830. var BABYLON;
  37831. (function (BABYLON) {
  37832. var DynamicFloatArrayElementInfo = (function () {
  37833. function DynamicFloatArrayElementInfo() {
  37834. }
  37835. return DynamicFloatArrayElementInfo;
  37836. }());
  37837. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  37838. /**
  37839. * 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.
  37840. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  37841. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  37842. * 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.
  37843. * 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.
  37844. * 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".
  37845. */
  37846. var DynamicFloatArray = (function () {
  37847. /**
  37848. * Construct an instance of the dynamic float array
  37849. * @param stride size of one element in float (i.e. not bytes!)
  37850. * @param initialElementCount the number of available entries at construction
  37851. */
  37852. function DynamicFloatArray(stride, initialElementCount) {
  37853. this.compareValueOffset = null;
  37854. this.sortingAscending = true;
  37855. this._stride = stride;
  37856. this.buffer = new Float32Array(stride * initialElementCount);
  37857. this._lastUsed = 0;
  37858. this._firstFree = 0;
  37859. this._allEntries = new Array(initialElementCount);
  37860. this._freeEntries = new Array(initialElementCount);
  37861. for (var i = 0; i < initialElementCount; i++) {
  37862. var element = new DynamicFloatArrayElementInfo();
  37863. element.offset = i * stride;
  37864. this._allEntries[i] = element;
  37865. this._freeEntries[initialElementCount - i - 1] = element;
  37866. }
  37867. }
  37868. /**
  37869. * Allocate an element in the array.
  37870. * @return the element info instance that contains the offset into the main buffer of the element's location.
  37871. * Beware, this offset may change when you call pack()
  37872. */
  37873. DynamicFloatArray.prototype.allocElement = function () {
  37874. if (this._freeEntries.length === 0) {
  37875. this._growBuffer();
  37876. }
  37877. var el = this._freeEntries.pop();
  37878. this._lastUsed = Math.max(el.offset, this._lastUsed);
  37879. if (el.offset === this._firstFree) {
  37880. if (this._freeEntries.length > 0) {
  37881. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  37882. }
  37883. else {
  37884. this._firstFree += this._stride;
  37885. }
  37886. }
  37887. return el;
  37888. };
  37889. /**
  37890. * Free the element corresponding to the given element info
  37891. * @param elInfo the element that describe the allocated element
  37892. */
  37893. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  37894. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  37895. this._freeEntries.push(elInfo);
  37896. };
  37897. /**
  37898. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  37899. * 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().
  37900. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  37901. */
  37902. DynamicFloatArray.prototype.pack = function () {
  37903. // no free slot? no need to pack
  37904. if (this._freeEntries.length === 0) {
  37905. return this.buffer;
  37906. }
  37907. // If the buffer is already packed the last used will always be lower than the first free
  37908. // 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.
  37909. if (this._lastUsed < this._firstFree) {
  37910. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  37911. return elementsBuffer_1;
  37912. }
  37913. var s = this._stride;
  37914. // 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
  37915. var lastFree = new DynamicFloatArrayElementInfo();
  37916. lastFree.offset = this.totalElementCount * s;
  37917. this._freeEntries.push(lastFree);
  37918. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  37919. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37920. var firstFreeSlotOffset = sortedFree[0].offset;
  37921. var freeZoneSize = 1;
  37922. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  37923. var prevOffset = sortedFree[0].offset;
  37924. for (var i = 1; i < sortedFree.length; i++) {
  37925. // 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
  37926. if (firstFreeSlotOffset >= occupiedZoneSize) {
  37927. break;
  37928. }
  37929. var curFree = sortedFree[i];
  37930. var curOffset = curFree.offset;
  37931. // Compute the distance between this offset and the previous
  37932. var distance = curOffset - prevOffset;
  37933. // If the distance is the stride size, they are adjacent, it good, move to the next
  37934. if (distance === s) {
  37935. // Free zone is one element bigger
  37936. ++freeZoneSize;
  37937. // as we're about to iterate to the next, the cur becomes the previous...
  37938. prevOffset = curOffset;
  37939. continue;
  37940. }
  37941. // Distance is bigger, which means there's x element between the previous free and this one
  37942. var usedRange = (distance / s) - 1;
  37943. // Two cases the free zone is smaller than the data to move or bigger
  37944. // Copy what can fit in the free zone
  37945. var curMoveOffset = curOffset - s;
  37946. var copyCount = Math.min(freeZoneSize, usedRange);
  37947. for (var j = 0; j < copyCount; j++) {
  37948. var freeI = firstFreeSlotOffset / s;
  37949. var curI = curMoveOffset / s;
  37950. var moveEl = sortedAll[curI];
  37951. this._moveElement(moveEl, firstFreeSlotOffset);
  37952. var replacedEl = sortedAll[freeI];
  37953. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  37954. replacedEl.offset = curMoveOffset;
  37955. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  37956. sortedAll[freeI] = moveEl;
  37957. sortedAll[curI] = replacedEl;
  37958. curMoveOffset -= s;
  37959. firstFreeSlotOffset += s;
  37960. }
  37961. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  37962. if (freeZoneSize <= usedRange) {
  37963. firstFreeSlotOffset = curMoveOffset + s;
  37964. freeZoneSize = 1 + copyCount;
  37965. }
  37966. else {
  37967. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  37968. }
  37969. // as we're about to iterate to the next, the cur becomes the previous...
  37970. prevOffset = curOffset;
  37971. }
  37972. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  37973. this._lastUsed = firstFreeSlotOffset - s;
  37974. this._firstFree = firstFreeSlotOffset;
  37975. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  37976. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  37977. this._allEntries = sortedAll;
  37978. return elementsBuffer;
  37979. };
  37980. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  37981. for (var i = 0; i < this._stride; i++) {
  37982. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  37983. }
  37984. element.offset = destOffset;
  37985. };
  37986. DynamicFloatArray.prototype._growBuffer = function () {
  37987. // Allocate the new buffer with 50% more entries, copy the content of the current one
  37988. var newElCount = Math.floor(this.totalElementCount * 1.5);
  37989. var newBuffer = new Float32Array(newElCount * this._stride);
  37990. newBuffer.set(this.buffer);
  37991. var curCount = this.totalElementCount;
  37992. var addedCount = newElCount - this.totalElementCount;
  37993. for (var i = 0; i < addedCount; i++) {
  37994. var element = new DynamicFloatArrayElementInfo();
  37995. element.offset = (curCount + i) * this.stride;
  37996. this._allEntries.push(element);
  37997. this._freeEntries[addedCount - i - 1] = element;
  37998. }
  37999. this._firstFree = curCount * this.stride;
  38000. this.buffer = newBuffer;
  38001. };
  38002. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  38003. /**
  38004. * Get the total count of entries that can fit in the current buffer
  38005. * @returns the elements count
  38006. */
  38007. get: function () {
  38008. return this._allEntries.length;
  38009. },
  38010. enumerable: true,
  38011. configurable: true
  38012. });
  38013. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  38014. /**
  38015. * Get the count of free entries that can still be allocated without resizing the buffer
  38016. * @returns the free elements count
  38017. */
  38018. get: function () {
  38019. return this._freeEntries.length;
  38020. },
  38021. enumerable: true,
  38022. configurable: true
  38023. });
  38024. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  38025. /**
  38026. * Get the count of allocated elements
  38027. * @returns the allocated elements count
  38028. */
  38029. get: function () {
  38030. return this._allEntries.length - this._freeEntries.length;
  38031. },
  38032. enumerable: true,
  38033. configurable: true
  38034. });
  38035. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  38036. /**
  38037. * Return the size of one element in float
  38038. * @returns the size in float
  38039. */
  38040. get: function () {
  38041. return this._stride;
  38042. },
  38043. enumerable: true,
  38044. configurable: true
  38045. });
  38046. DynamicFloatArray.prototype.sort = function () {
  38047. var _this = this;
  38048. if (!this.compareValueOffset) {
  38049. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  38050. }
  38051. var count = this.usedElementCount;
  38052. // Do we have to (re)create the sort table?
  38053. if (!this._sortTable || this._sortTable.length < count) {
  38054. // 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...
  38055. var newCount = Math.min(this.totalElementCount, count * 2);
  38056. this._sortTable = new Array(newCount);
  38057. }
  38058. if (!this._sortedTable || this._sortedTable.length !== count) {
  38059. this._sortedTable = new Array(count);
  38060. }
  38061. // Because, you know...
  38062. this.pack();
  38063. //let stride = this.stride;
  38064. //for (let i = 0; i < count; i++) {
  38065. // let si = this._sortTable[i];
  38066. // if (!si) {
  38067. // si = new SortInfo();
  38068. // this._sortTable[i] = si;
  38069. // }
  38070. // si.entry = this._allEntries[i];
  38071. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  38072. // si.swapedOffset = null;
  38073. // this._sortedTable[i] = si;
  38074. //}
  38075. var curOffset = 0;
  38076. var stride = this.stride;
  38077. for (var i = 0; i < count; i++, curOffset += stride) {
  38078. var si = this._sortTable[i];
  38079. if (!si) {
  38080. si = new SortInfo();
  38081. this._sortTable[i] = si;
  38082. }
  38083. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  38084. si.offset = curOffset;
  38085. si.swapedOffset = null;
  38086. this._sortedTable[i] = si;
  38087. }
  38088. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  38089. if (this.sortingAscending) {
  38090. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  38091. }
  38092. else {
  38093. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  38094. }
  38095. var swapElements = function (src, dst) {
  38096. for (var i = 0; i < stride; i++) {
  38097. var tps = _this.buffer[dst + i];
  38098. _this.buffer[dst + i] = _this.buffer[src + i];
  38099. _this.buffer[src + i] = tps;
  38100. }
  38101. };
  38102. // 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:
  38103. // 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),
  38104. // and I still want something with a good algorithm complexity.
  38105. // 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,
  38106. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  38107. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  38108. // 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
  38109. // until we find a SortInfo object without a swapedOffset which means we got the right location
  38110. // 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
  38111. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  38112. for (var i = 0; i < count; i++) {
  38113. // Get the element to move
  38114. var sourceSI = this._sortedTable[i];
  38115. var destSI = this._sortTable[i];
  38116. var sourceOff = sourceSI.offset;
  38117. // If the source changed location, find the new one
  38118. if (sourceSI.swapedOffset) {
  38119. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  38120. var curSI = sourceSI;
  38121. while (curSI.swapedOffset) {
  38122. curSI = this._sortTable[curSI.swapedOffset / stride];
  38123. }
  38124. // Finally get the right location
  38125. sourceOff = curSI.offset;
  38126. }
  38127. // Tag the element being replaced with its new location
  38128. destSI.swapedOffset = sourceOff;
  38129. // Swap elements (only if needed)
  38130. if (sourceOff !== destSI.offset) {
  38131. swapElements(sourceOff, destSI.offset);
  38132. }
  38133. // Update the offset in the corresponding DFAE
  38134. //sourceSI.entry.offset = destSI.entry.offset;
  38135. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  38136. }
  38137. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  38138. return true;
  38139. };
  38140. return DynamicFloatArray;
  38141. }());
  38142. BABYLON.DynamicFloatArray = DynamicFloatArray;
  38143. var SortInfo = (function () {
  38144. function SortInfo() {
  38145. this.compareData = this.offset = this.swapedOffset = null;
  38146. }
  38147. return SortInfo;
  38148. }());
  38149. })(BABYLON || (BABYLON = {}));
  38150. var BABYLON;
  38151. (function (BABYLON) {
  38152. /**
  38153. * This class given information about a given character.
  38154. */
  38155. var CharInfo = (function () {
  38156. function CharInfo() {
  38157. }
  38158. return CharInfo;
  38159. }());
  38160. BABYLON.CharInfo = CharInfo;
  38161. var FontTexture = (function (_super) {
  38162. __extends(FontTexture, _super);
  38163. /**
  38164. * Create a new instance of the FontTexture class
  38165. * @param name the name of the texture
  38166. * @param font the font to use, use the W3C CSS notation
  38167. * @param scene the scene that owns the texture
  38168. * @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
  38169. * @param samplingMode the texture sampling mode
  38170. * @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.
  38171. */
  38172. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  38173. if (maxCharCount === void 0) { maxCharCount = 200; }
  38174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38175. if (superSample === void 0) { superSample = false; }
  38176. _super.call(this, null, scene, true, false, samplingMode);
  38177. this._charInfos = {};
  38178. this._curCharCount = 0;
  38179. this._lastUpdateCharCount = -1;
  38180. this._usedCounter = 1;
  38181. this.name = name;
  38182. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38183. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38184. this._superSample = false;
  38185. if (superSample) {
  38186. var sfont = this.getSuperSampleFont(font);
  38187. if (sfont) {
  38188. this._superSample = true;
  38189. font = sfont;
  38190. }
  38191. }
  38192. // First canvas creation to determine the size of the texture to create
  38193. this._canvas = document.createElement("canvas");
  38194. this._context = this._canvas.getContext("2d");
  38195. this._context.font = font;
  38196. this._context.fillStyle = "white";
  38197. this._cachedFontId = null;
  38198. var res = this.getFontHeight(font);
  38199. this._lineHeightSuper = res.height;
  38200. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  38201. this._offset = res.offset - 1;
  38202. var maxCharWidth = this._context.measureText("W").width;
  38203. this._spaceWidthSuper = this._context.measureText(" ").width;
  38204. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  38205. // This is an approximate size, but should always be able to fit at least the maxCharCount
  38206. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  38207. var edge = Math.sqrt(totalEstSurface);
  38208. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  38209. // Create the texture that will store the font characters
  38210. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  38211. var textureSize = this.getSize();
  38212. this.hasAlpha = true;
  38213. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  38214. this._canvas = document.createElement("canvas");
  38215. this._canvas.width = textureSize.width;
  38216. this._canvas.height = textureSize.height;
  38217. this._context = this._canvas.getContext("2d");
  38218. this._context.textBaseline = "top";
  38219. this._context.font = font;
  38220. this._context.fillStyle = "white";
  38221. this._context.imageSmoothingEnabled = false;
  38222. this._currentFreePosition = BABYLON.Vector2.Zero();
  38223. // Add the basic ASCII based characters
  38224. for (var i = 0x20; i < 0x7F; i++) {
  38225. var c = String.fromCharCode(i);
  38226. this.getChar(c);
  38227. }
  38228. this.update();
  38229. }
  38230. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  38231. get: function () {
  38232. return this._superSample;
  38233. },
  38234. enumerable: true,
  38235. configurable: true
  38236. });
  38237. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  38238. get: function () {
  38239. return this._spaceWidth;
  38240. },
  38241. enumerable: true,
  38242. configurable: true
  38243. });
  38244. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  38245. get: function () {
  38246. return this._lineHeight;
  38247. },
  38248. enumerable: true,
  38249. configurable: true
  38250. });
  38251. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  38252. if (supersample === void 0) { supersample = false; }
  38253. var s = scene;
  38254. if (!s.__fontTextureCache__) {
  38255. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  38256. }
  38257. var dic = s.__fontTextureCache__;
  38258. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  38259. var ft = dic.get(lfn);
  38260. if (ft) {
  38261. ++ft._usedCounter;
  38262. return ft;
  38263. }
  38264. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  38265. ft._cachedFontId = lfn;
  38266. dic.add(lfn, ft);
  38267. return ft;
  38268. };
  38269. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  38270. if (supersample === void 0) { supersample = false; }
  38271. var s = scene;
  38272. var dic = s.__fontTextureCache__;
  38273. if (!dic) {
  38274. return;
  38275. }
  38276. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  38277. var font = dic.get(lfn);
  38278. if (--font._usedCounter === 0) {
  38279. dic.remove(lfn);
  38280. font.dispose();
  38281. }
  38282. };
  38283. /**
  38284. * Make sure the given char is present in the font map.
  38285. * @param char the character to get or add
  38286. * @return the CharInfo instance corresponding to the given character
  38287. */
  38288. FontTexture.prototype.getChar = function (char) {
  38289. if (char.length !== 1) {
  38290. return null;
  38291. }
  38292. var info = this._charInfos[char];
  38293. if (info) {
  38294. return info;
  38295. }
  38296. info = new CharInfo();
  38297. var measure = this._context.measureText(char);
  38298. var textureSize = this.getSize();
  38299. // we reached the end of the current line?
  38300. var width = Math.round(measure.width);
  38301. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  38302. var yMargin = xMargin;
  38303. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  38304. this._currentFreePosition.x = 0;
  38305. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  38306. // No more room?
  38307. if (this._currentFreePosition.y > textureSize.height) {
  38308. return this.getChar("!");
  38309. }
  38310. }
  38311. // Draw the character in the texture
  38312. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  38313. // Fill the CharInfo object
  38314. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  38315. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  38316. info.charWidth = this._superSample ? (width / 2) : width;
  38317. // Add the info structure
  38318. this._charInfos[char] = info;
  38319. this._curCharCount++;
  38320. // Set the next position
  38321. this._currentFreePosition.x += width + xMargin;
  38322. return info;
  38323. };
  38324. FontTexture.prototype.measureText = function (text, tabulationSize) {
  38325. if (tabulationSize === void 0) { tabulationSize = 4; }
  38326. var maxWidth = 0;
  38327. var curWidth = 0;
  38328. var lineCount = 1;
  38329. var charxpos = 0;
  38330. // Parse each char of the string
  38331. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  38332. var char = text_1[_i];
  38333. // Next line feed?
  38334. if (char === "\n") {
  38335. maxWidth = Math.max(maxWidth, curWidth);
  38336. charxpos = 0;
  38337. curWidth = 0;
  38338. ++lineCount;
  38339. continue;
  38340. }
  38341. // Tabulation ?
  38342. if (char === "\t") {
  38343. var nextPos = charxpos + tabulationSize;
  38344. nextPos = nextPos - (nextPos % tabulationSize);
  38345. curWidth += (nextPos - charxpos) * this.spaceWidth;
  38346. charxpos = nextPos;
  38347. continue;
  38348. }
  38349. if (char < " ") {
  38350. continue;
  38351. }
  38352. curWidth += this.getChar(char).charWidth;
  38353. ++charxpos;
  38354. }
  38355. maxWidth = Math.max(maxWidth, curWidth);
  38356. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  38357. };
  38358. FontTexture.prototype.getSuperSampleFont = function (font) {
  38359. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  38360. 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*$/;
  38361. var res = font.toLocaleLowerCase().match(regex);
  38362. if (res == null) {
  38363. return null;
  38364. }
  38365. var size = parseInt(res[4]);
  38366. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  38367. var newFont = "";
  38368. for (var j = 1; j < res.length; j++) {
  38369. if (res[j] != null) {
  38370. newFont += res[j] + " ";
  38371. }
  38372. }
  38373. return newFont;
  38374. };
  38375. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  38376. FontTexture.prototype.getFontHeight = function (font) {
  38377. var fontDraw = document.createElement("canvas");
  38378. var ctx = fontDraw.getContext('2d');
  38379. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  38380. ctx.textBaseline = 'top';
  38381. ctx.fillStyle = 'white';
  38382. ctx.font = font;
  38383. ctx.fillText('jH|', 0, 0);
  38384. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  38385. var start = -1;
  38386. var end = -1;
  38387. for (var row = 0; row < fontDraw.height; row++) {
  38388. for (var column = 0; column < fontDraw.width; column++) {
  38389. var index = (row * fontDraw.width + column) * 4;
  38390. if (pixels[index] === 0) {
  38391. if (column === fontDraw.width - 1 && start !== -1) {
  38392. end = row;
  38393. row = fontDraw.height;
  38394. break;
  38395. }
  38396. continue;
  38397. }
  38398. else {
  38399. if (start === -1) {
  38400. start = row;
  38401. }
  38402. break;
  38403. }
  38404. }
  38405. }
  38406. return { height: (end - start) + 1, offset: start - 1 };
  38407. };
  38408. Object.defineProperty(FontTexture.prototype, "canRescale", {
  38409. get: function () {
  38410. return false;
  38411. },
  38412. enumerable: true,
  38413. configurable: true
  38414. });
  38415. FontTexture.prototype.getContext = function () {
  38416. return this._context;
  38417. };
  38418. /**
  38419. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  38420. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  38421. */
  38422. FontTexture.prototype.update = function () {
  38423. // Update only if there's new char added since the previous update
  38424. if (this._lastUpdateCharCount < this._curCharCount) {
  38425. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  38426. this._lastUpdateCharCount = this._curCharCount;
  38427. }
  38428. };
  38429. // cloning should be prohibited, there's no point to duplicate this texture at all
  38430. FontTexture.prototype.clone = function () {
  38431. return null;
  38432. };
  38433. /**
  38434. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  38435. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  38436. */
  38437. FontTexture.prototype.incCachedFontTextureCounter = function () {
  38438. ++this._usedCounter;
  38439. };
  38440. /**
  38441. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  38442. */
  38443. FontTexture.prototype.decCachedFontTextureCounter = function () {
  38444. var s = this.getScene();
  38445. var dic = s.__fontTextureCache__;
  38446. if (!dic) {
  38447. return;
  38448. }
  38449. if (--this._usedCounter === 0) {
  38450. dic.remove(this._cachedFontId);
  38451. this.dispose();
  38452. }
  38453. };
  38454. return FontTexture;
  38455. }(BABYLON.Texture));
  38456. BABYLON.FontTexture = FontTexture;
  38457. })(BABYLON || (BABYLON = {}));
  38458. var BABYLON;
  38459. (function (BABYLON) {
  38460. var MapTexture = (function (_super) {
  38461. __extends(MapTexture, _super);
  38462. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  38463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38464. if (useMipMap === void 0) { useMipMap = false; }
  38465. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  38466. this.name = name;
  38467. this._size = size;
  38468. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38469. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38470. // Create the rectPackMap that will allocate portion of the texture
  38471. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  38472. // Create the texture that will store the content
  38473. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  38474. }
  38475. /**
  38476. * Allocate a rectangle of a given size in the texture map
  38477. * @param size the size of the rectangle to allocation
  38478. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  38479. */
  38480. MapTexture.prototype.allocateRect = function (size) {
  38481. return this._rectPackingMap.addRect(size);
  38482. };
  38483. /**
  38484. * Free a given rectangle from the texture map
  38485. * @param rectInfo the instance corresponding to the rect to free.
  38486. */
  38487. MapTexture.prototype.freeRect = function (rectInfo) {
  38488. if (rectInfo) {
  38489. rectInfo.freeContent();
  38490. }
  38491. };
  38492. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  38493. /**
  38494. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  38495. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  38496. * @returns {}
  38497. */
  38498. get: function () {
  38499. return this._rectPackingMap.freeSpace;
  38500. },
  38501. enumerable: true,
  38502. configurable: true
  38503. });
  38504. /**
  38505. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  38506. * 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.
  38507. * Don't forget to call unbindTexture when you're done rendering
  38508. * @param rect the zone to render to
  38509. * @param clear true to clear the portion's color/depth data
  38510. */
  38511. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  38512. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  38513. };
  38514. /**
  38515. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  38516. * 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.
  38517. * Don't forget to call unbindTexture when you're done rendering
  38518. * @param pos the position into the texture
  38519. * @param size the portion to fit the clip space to
  38520. * @param clear true to clear the portion's color/depth data
  38521. */
  38522. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  38523. var engine = this.getScene().getEngine();
  38524. engine.bindFramebuffer(this._texture);
  38525. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  38526. if (clear) {
  38527. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  38528. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  38529. }
  38530. };
  38531. /**
  38532. * Unbind the texture map from the rendering engine.
  38533. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  38534. * @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.
  38535. */
  38536. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  38537. // Dump ?
  38538. if (dumpForDebug) {
  38539. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  38540. }
  38541. var engine = this.getScene().getEngine();
  38542. if (this._replacedViewport) {
  38543. engine.setViewport(this._replacedViewport);
  38544. this._replacedViewport = null;
  38545. }
  38546. engine.unBindFramebuffer(this._texture);
  38547. };
  38548. Object.defineProperty(MapTexture.prototype, "canRescale", {
  38549. get: function () {
  38550. return false;
  38551. },
  38552. enumerable: true,
  38553. configurable: true
  38554. });
  38555. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  38556. // Anyway, there's not much point to use this method for this kind of texture I guess
  38557. MapTexture.prototype.clone = function () {
  38558. return null;
  38559. };
  38560. return MapTexture;
  38561. }(BABYLON.Texture));
  38562. BABYLON.MapTexture = MapTexture;
  38563. })(BABYLON || (BABYLON = {}));
  38564. var BABYLON;
  38565. (function (BABYLON) {
  38566. var ShaderMaterial = (function (_super) {
  38567. __extends(ShaderMaterial, _super);
  38568. function ShaderMaterial(name, scene, shaderPath, options) {
  38569. _super.call(this, name, scene);
  38570. this._textures = {};
  38571. this._textureArrays = {};
  38572. this._floats = {};
  38573. this._floatsArrays = {};
  38574. this._colors3 = {};
  38575. this._colors4 = {};
  38576. this._vectors2 = {};
  38577. this._vectors3 = {};
  38578. this._vectors4 = {};
  38579. this._matrices = {};
  38580. this._matrices3x3 = {};
  38581. this._matrices2x2 = {};
  38582. this._vectors3Arrays = {};
  38583. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  38584. this._shaderPath = shaderPath;
  38585. options.needAlphaBlending = options.needAlphaBlending || false;
  38586. options.needAlphaTesting = options.needAlphaTesting || false;
  38587. options.attributes = options.attributes || ["position", "normal", "uv"];
  38588. options.uniforms = options.uniforms || ["worldViewProjection"];
  38589. options.samplers = options.samplers || [];
  38590. options.defines = options.defines || [];
  38591. this._options = options;
  38592. }
  38593. ShaderMaterial.prototype.needAlphaBlending = function () {
  38594. return this._options.needAlphaBlending;
  38595. };
  38596. ShaderMaterial.prototype.needAlphaTesting = function () {
  38597. return this._options.needAlphaTesting;
  38598. };
  38599. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  38600. if (this._options.uniforms.indexOf(uniformName) === -1) {
  38601. this._options.uniforms.push(uniformName);
  38602. }
  38603. };
  38604. ShaderMaterial.prototype.setTexture = function (name, texture) {
  38605. if (this._options.samplers.indexOf(name) === -1) {
  38606. this._options.samplers.push(name);
  38607. }
  38608. this._textures[name] = texture;
  38609. return this;
  38610. };
  38611. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  38612. if (this._options.samplers.indexOf(name) === -1) {
  38613. this._options.samplers.push(name);
  38614. }
  38615. this._checkUniform(name);
  38616. this._textureArrays[name] = textures;
  38617. return this;
  38618. };
  38619. ShaderMaterial.prototype.setFloat = function (name, value) {
  38620. this._checkUniform(name);
  38621. this._floats[name] = value;
  38622. return this;
  38623. };
  38624. ShaderMaterial.prototype.setFloats = function (name, value) {
  38625. this._checkUniform(name);
  38626. this._floatsArrays[name] = value;
  38627. return this;
  38628. };
  38629. ShaderMaterial.prototype.setColor3 = function (name, value) {
  38630. this._checkUniform(name);
  38631. this._colors3[name] = value;
  38632. return this;
  38633. };
  38634. ShaderMaterial.prototype.setColor4 = function (name, value) {
  38635. this._checkUniform(name);
  38636. this._colors4[name] = value;
  38637. return this;
  38638. };
  38639. ShaderMaterial.prototype.setVector2 = function (name, value) {
  38640. this._checkUniform(name);
  38641. this._vectors2[name] = value;
  38642. return this;
  38643. };
  38644. ShaderMaterial.prototype.setVector3 = function (name, value) {
  38645. this._checkUniform(name);
  38646. this._vectors3[name] = value;
  38647. return this;
  38648. };
  38649. ShaderMaterial.prototype.setVector4 = function (name, value) {
  38650. this._checkUniform(name);
  38651. this._vectors4[name] = value;
  38652. return this;
  38653. };
  38654. ShaderMaterial.prototype.setMatrix = function (name, value) {
  38655. this._checkUniform(name);
  38656. this._matrices[name] = value;
  38657. return this;
  38658. };
  38659. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  38660. this._checkUniform(name);
  38661. this._matrices3x3[name] = value;
  38662. return this;
  38663. };
  38664. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  38665. this._checkUniform(name);
  38666. this._matrices2x2[name] = value;
  38667. return this;
  38668. };
  38669. ShaderMaterial.prototype.setVector3Array = function (name, value) {
  38670. this._checkUniform(name);
  38671. this._vectors3Arrays[name] = value;
  38672. return this;
  38673. };
  38674. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  38675. var scene = this.getScene();
  38676. var engine = scene.getEngine();
  38677. if (!this.checkReadyOnEveryCall) {
  38678. if (this._renderId === scene.getRenderId()) {
  38679. return true;
  38680. }
  38681. }
  38682. // Instances
  38683. var defines = [];
  38684. var fallbacks = new BABYLON.EffectFallbacks();
  38685. if (useInstances) {
  38686. defines.push("#define INSTANCES");
  38687. }
  38688. for (var index = 0; index < this._options.defines.length; index++) {
  38689. defines.push(this._options.defines[index]);
  38690. }
  38691. // Bones
  38692. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  38693. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38694. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38695. fallbacks.addCPUSkinningFallback(0, mesh);
  38696. }
  38697. // Alpha test
  38698. if (engine.getAlphaTesting()) {
  38699. defines.push("#define ALPHATEST");
  38700. }
  38701. var previousEffect = this._effect;
  38702. var join = defines.join("\n");
  38703. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  38704. if (!this._effect.isReady()) {
  38705. return false;
  38706. }
  38707. if (previousEffect !== this._effect) {
  38708. scene.resetCachedMaterial();
  38709. }
  38710. this._renderId = scene.getRenderId();
  38711. return true;
  38712. };
  38713. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38714. var scene = this.getScene();
  38715. if (this._options.uniforms.indexOf("world") !== -1) {
  38716. this._effect.setMatrix("world", world);
  38717. }
  38718. if (this._options.uniforms.indexOf("worldView") !== -1) {
  38719. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  38720. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  38721. }
  38722. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  38723. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  38724. }
  38725. };
  38726. ShaderMaterial.prototype.bind = function (world, mesh) {
  38727. // Std values
  38728. this.bindOnlyWorldMatrix(world);
  38729. if (this.getScene().getCachedMaterial() !== this) {
  38730. if (this._options.uniforms.indexOf("view") !== -1) {
  38731. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  38732. }
  38733. if (this._options.uniforms.indexOf("projection") !== -1) {
  38734. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  38735. }
  38736. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  38737. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  38738. }
  38739. // Bones
  38740. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  38741. var name;
  38742. // Texture
  38743. for (name in this._textures) {
  38744. this._effect.setTexture(name, this._textures[name]);
  38745. }
  38746. // Texture arrays
  38747. for (name in this._textureArrays) {
  38748. this._effect.setTextureArray(name, this._textureArrays[name]);
  38749. }
  38750. // Float
  38751. for (name in this._floats) {
  38752. this._effect.setFloat(name, this._floats[name]);
  38753. }
  38754. // Float s
  38755. for (name in this._floatsArrays) {
  38756. this._effect.setArray(name, this._floatsArrays[name]);
  38757. }
  38758. // Color3
  38759. for (name in this._colors3) {
  38760. this._effect.setColor3(name, this._colors3[name]);
  38761. }
  38762. // Color4
  38763. for (name in this._colors4) {
  38764. var color = this._colors4[name];
  38765. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  38766. }
  38767. // Vector2
  38768. for (name in this._vectors2) {
  38769. this._effect.setVector2(name, this._vectors2[name]);
  38770. }
  38771. // Vector3
  38772. for (name in this._vectors3) {
  38773. this._effect.setVector3(name, this._vectors3[name]);
  38774. }
  38775. // Vector4
  38776. for (name in this._vectors4) {
  38777. this._effect.setVector4(name, this._vectors4[name]);
  38778. }
  38779. // Matrix
  38780. for (name in this._matrices) {
  38781. this._effect.setMatrix(name, this._matrices[name]);
  38782. }
  38783. // Matrix 3x3
  38784. for (name in this._matrices3x3) {
  38785. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  38786. }
  38787. // Matrix 2x2
  38788. for (name in this._matrices2x2) {
  38789. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  38790. }
  38791. // Vector3Array
  38792. for (name in this._vectors3Arrays) {
  38793. this._effect.setArray3(name, this._vectors3Arrays[name]);
  38794. }
  38795. }
  38796. _super.prototype.bind.call(this, world, mesh);
  38797. };
  38798. ShaderMaterial.prototype.clone = function (name) {
  38799. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  38800. return newShaderMaterial;
  38801. };
  38802. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38803. if (forceDisposeTextures) {
  38804. var name;
  38805. for (name in this._textures) {
  38806. this._textures[name].dispose();
  38807. }
  38808. for (name in this._textureArrays) {
  38809. var array = this._textureArrays[name];
  38810. for (var index = 0; index < array.length; index++) {
  38811. array[index].dispose();
  38812. }
  38813. }
  38814. }
  38815. this._textures = {};
  38816. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38817. };
  38818. ShaderMaterial.prototype.serialize = function () {
  38819. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38820. serializationObject.customType = "BABYLON.ShaderMaterial";
  38821. serializationObject.options = this._options;
  38822. serializationObject.shaderPath = this._shaderPath;
  38823. var name;
  38824. // Texture
  38825. serializationObject.textures = {};
  38826. for (name in this._textures) {
  38827. serializationObject.textures[name] = this._textures[name].serialize();
  38828. }
  38829. // Texture arrays
  38830. serializationObject.textureArrays = {};
  38831. for (name in this._textureArrays) {
  38832. serializationObject.textureArrays[name] = [];
  38833. var array = this._textureArrays[name];
  38834. for (var index = 0; index < array.length; index++) {
  38835. serializationObject.textureArrays[name].push(array[index].serialize());
  38836. }
  38837. }
  38838. // Float
  38839. serializationObject.floats = {};
  38840. for (name in this._floats) {
  38841. serializationObject.floats[name] = this._floats[name];
  38842. }
  38843. // Float s
  38844. serializationObject.floatArrays = {};
  38845. for (name in this._floatsArrays) {
  38846. serializationObject.floatArrays[name] = this._floatsArrays[name];
  38847. }
  38848. // Color3
  38849. serializationObject.colors3 = {};
  38850. for (name in this._colors3) {
  38851. serializationObject.colors3[name] = this._colors3[name].asArray();
  38852. }
  38853. // Color4
  38854. serializationObject.colors4 = {};
  38855. for (name in this._colors4) {
  38856. serializationObject.colors4[name] = this._colors4[name].asArray();
  38857. }
  38858. // Vector2
  38859. serializationObject.vectors2 = {};
  38860. for (name in this._vectors2) {
  38861. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  38862. }
  38863. // Vector3
  38864. serializationObject.vectors3 = {};
  38865. for (name in this._vectors3) {
  38866. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  38867. }
  38868. // Vector4
  38869. serializationObject.vectors4 = {};
  38870. for (name in this._vectors4) {
  38871. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  38872. }
  38873. // Matrix
  38874. serializationObject.matrices = {};
  38875. for (name in this._matrices) {
  38876. serializationObject.matrices[name] = this._matrices[name].asArray();
  38877. }
  38878. // Matrix 3x3
  38879. serializationObject.matrices3x3 = {};
  38880. for (name in this._matrices3x3) {
  38881. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  38882. }
  38883. // Matrix 2x2
  38884. serializationObject.matrices2x2 = {};
  38885. for (name in this._matrices2x2) {
  38886. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  38887. }
  38888. // Vector3Array
  38889. serializationObject.vectors3Arrays = {};
  38890. for (name in this._vectors3Arrays) {
  38891. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  38892. }
  38893. return serializationObject;
  38894. };
  38895. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  38896. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  38897. var name;
  38898. // Texture
  38899. for (name in source.textures) {
  38900. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  38901. }
  38902. // Texture arrays
  38903. for (name in source.textureArrays) {
  38904. var array = source.textureArrays[name];
  38905. var textureArray = new Array();
  38906. for (var index = 0; index < array.length; index++) {
  38907. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  38908. }
  38909. material.setTextureArray(name, textureArray);
  38910. }
  38911. // Float
  38912. for (name in source.floats) {
  38913. material.setFloat(name, source.floats[name]);
  38914. }
  38915. // Float s
  38916. for (name in source.floatsArrays) {
  38917. material.setFloats(name, source.floatsArrays[name]);
  38918. }
  38919. // Color3
  38920. for (name in source.colors3) {
  38921. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  38922. }
  38923. // Color4
  38924. for (name in source.colors4) {
  38925. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  38926. }
  38927. // Vector2
  38928. for (name in source.vectors2) {
  38929. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  38930. }
  38931. // Vector3
  38932. for (name in source.vectors3) {
  38933. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  38934. }
  38935. // Vector4
  38936. for (name in source.vectors4) {
  38937. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  38938. }
  38939. // Matrix
  38940. for (name in source.matrices) {
  38941. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  38942. }
  38943. // Matrix 3x3
  38944. for (name in source.matrices3x3) {
  38945. material.setMatrix3x3(name, source.matrices3x3[name]);
  38946. }
  38947. // Matrix 2x2
  38948. for (name in source.matrices2x2) {
  38949. material.setMatrix2x2(name, source.matrices2x2[name]);
  38950. }
  38951. // Vector3Array
  38952. for (name in source.vectors3Arrays) {
  38953. material.setVector3Array(name, source.vectors3Arrays[name]);
  38954. }
  38955. return material;
  38956. };
  38957. return ShaderMaterial;
  38958. }(BABYLON.Material));
  38959. BABYLON.ShaderMaterial = ShaderMaterial;
  38960. })(BABYLON || (BABYLON = {}));
  38961. var BABYLON;
  38962. (function (BABYLON) {
  38963. var Internals;
  38964. (function (Internals) {
  38965. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  38966. // All values and structures referenced from:
  38967. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  38968. var DDS_MAGIC = 0x20534444;
  38969. 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;
  38970. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  38971. 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;
  38972. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  38973. function FourCCToInt32(value) {
  38974. return value.charCodeAt(0) +
  38975. (value.charCodeAt(1) << 8) +
  38976. (value.charCodeAt(2) << 16) +
  38977. (value.charCodeAt(3) << 24);
  38978. }
  38979. function Int32ToFourCC(value) {
  38980. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  38981. }
  38982. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  38983. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  38984. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  38985. var headerLengthInt = 31; // The header length in 32 bit ints
  38986. // Offsets into the header array
  38987. var off_magic = 0;
  38988. var off_size = 1;
  38989. var off_flags = 2;
  38990. var off_height = 3;
  38991. var off_width = 4;
  38992. var off_mipmapCount = 7;
  38993. var off_pfFlags = 20;
  38994. var off_pfFourCC = 21;
  38995. var off_RGBbpp = 22;
  38996. var off_RMask = 23;
  38997. var off_GMask = 24;
  38998. var off_BMask = 25;
  38999. var off_AMask = 26;
  39000. var off_caps1 = 27;
  39001. var off_caps2 = 28;
  39002. ;
  39003. var DDSTools = (function () {
  39004. function DDSTools() {
  39005. }
  39006. DDSTools.GetDDSInfo = function (arrayBuffer) {
  39007. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  39008. var mipmapCount = 1;
  39009. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  39010. mipmapCount = Math.max(1, header[off_mipmapCount]);
  39011. }
  39012. return {
  39013. width: header[off_width],
  39014. height: header[off_height],
  39015. mipmapCount: mipmapCount,
  39016. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  39017. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  39018. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  39019. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  39020. };
  39021. };
  39022. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39023. var byteArray = new Uint8Array(dataLength);
  39024. var srcData = new Uint8Array(arrayBuffer);
  39025. var index = 0;
  39026. for (var y = height - 1; y >= 0; y--) {
  39027. for (var x = 0; x < width; x++) {
  39028. var srcPos = dataOffset + (x + y * width) * 4;
  39029. byteArray[index + 2] = srcData[srcPos];
  39030. byteArray[index + 1] = srcData[srcPos + 1];
  39031. byteArray[index] = srcData[srcPos + 2];
  39032. byteArray[index + 3] = srcData[srcPos + 3];
  39033. index += 4;
  39034. }
  39035. }
  39036. return byteArray;
  39037. };
  39038. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39039. var byteArray = new Uint8Array(dataLength);
  39040. var srcData = new Uint8Array(arrayBuffer);
  39041. var index = 0;
  39042. for (var y = height - 1; y >= 0; y--) {
  39043. for (var x = 0; x < width; x++) {
  39044. var srcPos = dataOffset + (x + y * width) * 3;
  39045. byteArray[index + 2] = srcData[srcPos];
  39046. byteArray[index + 1] = srcData[srcPos + 1];
  39047. byteArray[index] = srcData[srcPos + 2];
  39048. index += 3;
  39049. }
  39050. }
  39051. return byteArray;
  39052. };
  39053. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39054. var byteArray = new Uint8Array(dataLength);
  39055. var srcData = new Uint8Array(arrayBuffer);
  39056. var index = 0;
  39057. for (var y = height - 1; y >= 0; y--) {
  39058. for (var x = 0; x < width; x++) {
  39059. var srcPos = dataOffset + (x + y * width);
  39060. byteArray[index] = srcData[srcPos];
  39061. index++;
  39062. }
  39063. }
  39064. return byteArray;
  39065. };
  39066. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  39067. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  39068. if (header[off_magic] != DDS_MAGIC) {
  39069. BABYLON.Tools.Error("Invalid magic number in DDS header");
  39070. return;
  39071. }
  39072. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  39073. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  39074. return;
  39075. }
  39076. if (info.isFourCC) {
  39077. fourCC = header[off_pfFourCC];
  39078. switch (fourCC) {
  39079. case FOURCC_DXT1:
  39080. blockBytes = 8;
  39081. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39082. break;
  39083. case FOURCC_DXT3:
  39084. blockBytes = 16;
  39085. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39086. break;
  39087. case FOURCC_DXT5:
  39088. blockBytes = 16;
  39089. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39090. break;
  39091. default:
  39092. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  39093. return;
  39094. }
  39095. }
  39096. mipmapCount = 1;
  39097. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  39098. mipmapCount = Math.max(1, header[off_mipmapCount]);
  39099. }
  39100. var bpp = header[off_RGBbpp];
  39101. for (var face = 0; face < faces; face++) {
  39102. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  39103. width = header[off_width];
  39104. height = header[off_height];
  39105. dataOffset = header[off_size] + 4;
  39106. for (i = 0; i < mipmapCount; ++i) {
  39107. if (info.isRGB) {
  39108. if (bpp === 24) {
  39109. dataLength = width * height * 3;
  39110. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39111. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  39112. }
  39113. else {
  39114. dataLength = width * height * 4;
  39115. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39116. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  39117. }
  39118. }
  39119. else if (info.isLuminance) {
  39120. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  39121. var unpaddedRowSize = width;
  39122. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  39123. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  39124. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39125. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  39126. }
  39127. else {
  39128. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  39129. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  39130. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  39131. }
  39132. dataOffset += dataLength;
  39133. width *= 0.5;
  39134. height *= 0.5;
  39135. width = Math.max(1.0, width);
  39136. height = Math.max(1.0, height);
  39137. }
  39138. }
  39139. };
  39140. return DDSTools;
  39141. }());
  39142. Internals.DDSTools = DDSTools;
  39143. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39144. })(BABYLON || (BABYLON = {}));
  39145. var BABYLON;
  39146. (function (BABYLON) {
  39147. var CannonJSPlugin = (function () {
  39148. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  39149. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  39150. if (iterations === void 0) { iterations = 10; }
  39151. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  39152. this.name = "CannonJSPlugin";
  39153. this._physicsMaterials = [];
  39154. this._fixedTimeStep = 1 / 60;
  39155. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  39156. this._currentCollisionGroup = 2;
  39157. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  39158. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  39159. this._tmpPosition = BABYLON.Vector3.Zero();
  39160. this._tmpQuaternion = new BABYLON.Quaternion();
  39161. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  39162. this._tmpDeltaRotation = new BABYLON.Quaternion();
  39163. this._tmpUnityRotation = new BABYLON.Quaternion();
  39164. if (!this.isSupported()) {
  39165. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  39166. return;
  39167. }
  39168. this.world = new CANNON.World();
  39169. this.world.broadphase = new CANNON.NaiveBroadphase();
  39170. this.world.solver.iterations = iterations;
  39171. }
  39172. CannonJSPlugin.prototype.setGravity = function (gravity) {
  39173. this.world.gravity.copy(gravity);
  39174. };
  39175. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  39176. this._fixedTimeStep = timeStep;
  39177. };
  39178. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  39179. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  39180. };
  39181. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  39182. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  39183. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  39184. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  39185. };
  39186. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  39187. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  39188. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  39189. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  39190. };
  39191. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  39192. //parent-child relationship. Does this impostor has a parent impostor?
  39193. if (impostor.parent) {
  39194. if (impostor.physicsBody) {
  39195. this.removePhysicsBody(impostor);
  39196. //TODO is that needed?
  39197. impostor.forceUpdate();
  39198. }
  39199. return;
  39200. }
  39201. //should a new body be created for this impostor?
  39202. if (impostor.isBodyInitRequired()) {
  39203. var shape = this._createShape(impostor);
  39204. //unregister events, if body is being changed
  39205. var oldBody = impostor.physicsBody;
  39206. if (oldBody) {
  39207. this.removePhysicsBody(impostor);
  39208. }
  39209. //create the body and material
  39210. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  39211. var bodyCreationObject = {
  39212. mass: impostor.getParam("mass"),
  39213. material: material
  39214. };
  39215. // A simple extend, in case native options were used.
  39216. var nativeOptions = impostor.getParam("nativeOptions");
  39217. for (var key in nativeOptions) {
  39218. if (nativeOptions.hasOwnProperty(key)) {
  39219. bodyCreationObject[key] = nativeOptions[key];
  39220. }
  39221. }
  39222. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  39223. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  39224. this.world.addEventListener("preStep", impostor.beforeStep);
  39225. this.world.addEventListener("postStep", impostor.afterStep);
  39226. impostor.physicsBody.addShape(shape);
  39227. this.world.add(impostor.physicsBody);
  39228. //try to keep the body moving in the right direction by taking old properties.
  39229. //Should be tested!
  39230. if (oldBody) {
  39231. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  39232. impostor.physicsBody[param].copy(oldBody[param]);
  39233. });
  39234. }
  39235. this._processChildMeshes(impostor);
  39236. }
  39237. //now update the body's transformation
  39238. this._updatePhysicsBodyTransformation(impostor);
  39239. };
  39240. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  39241. var _this = this;
  39242. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  39243. if (meshChildren.length) {
  39244. var processMesh = function (localPosition, mesh) {
  39245. var childImpostor = mesh.getPhysicsImpostor();
  39246. if (childImpostor) {
  39247. var parent = childImpostor.parent;
  39248. if (parent !== mainImpostor) {
  39249. var localPosition = mesh.position;
  39250. if (childImpostor.physicsBody) {
  39251. _this.removePhysicsBody(childImpostor);
  39252. childImpostor.physicsBody = null;
  39253. }
  39254. childImpostor.parent = mainImpostor;
  39255. childImpostor.resetUpdateFlags();
  39256. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  39257. //Add the mass of the children.
  39258. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  39259. }
  39260. }
  39261. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  39262. };
  39263. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  39264. }
  39265. };
  39266. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  39267. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  39268. this.world.removeEventListener("preStep", impostor.beforeStep);
  39269. this.world.removeEventListener("postStep", impostor.afterStep);
  39270. this.world.remove(impostor.physicsBody);
  39271. };
  39272. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  39273. var mainBody = impostorJoint.mainImpostor.physicsBody;
  39274. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  39275. if (!mainBody || !connectedBody) {
  39276. return;
  39277. }
  39278. var constraint;
  39279. var jointData = impostorJoint.joint.jointData;
  39280. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  39281. var constraintData = {
  39282. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  39283. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  39284. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  39285. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  39286. maxForce: jointData.nativeParams.maxForce,
  39287. collideConnected: !!jointData.collision
  39288. };
  39289. //Not needed, Cannon has a collideConnected flag
  39290. /*if (!jointData.collision) {
  39291. //add 1st body to a collision group of its own, if it is not in 1
  39292. if (mainBody.collisionFilterGroup === 1) {
  39293. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  39294. this._currentCollisionGroup <<= 1;
  39295. }
  39296. if (connectedBody.collisionFilterGroup === 1) {
  39297. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  39298. this._currentCollisionGroup <<= 1;
  39299. }
  39300. //add their mask to the collisionFilterMask of each other:
  39301. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  39302. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  39303. }*/
  39304. switch (impostorJoint.joint.type) {
  39305. case BABYLON.PhysicsJoint.HingeJoint:
  39306. case BABYLON.PhysicsJoint.Hinge2Joint:
  39307. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  39308. break;
  39309. case BABYLON.PhysicsJoint.DistanceJoint:
  39310. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  39311. break;
  39312. case BABYLON.PhysicsJoint.SpringJoint:
  39313. var springData = jointData;
  39314. constraint = new CANNON.Spring(mainBody, connectedBody, {
  39315. restLength: springData.length,
  39316. stiffness: springData.stiffness,
  39317. damping: springData.damping,
  39318. localAnchorA: constraintData.pivotA,
  39319. localAnchorB: constraintData.pivotB
  39320. });
  39321. break;
  39322. case BABYLON.PhysicsJoint.LockJoint:
  39323. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  39324. break;
  39325. case BABYLON.PhysicsJoint.PointToPointJoint:
  39326. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  39327. default:
  39328. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  39329. break;
  39330. }
  39331. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  39332. constraint.collideConnected = !!jointData.collision;
  39333. impostorJoint.joint.physicsJoint = constraint;
  39334. //don't add spring as constraint, as it is not one.
  39335. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  39336. this.world.addConstraint(constraint);
  39337. }
  39338. else {
  39339. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  39340. constraint.applyForce();
  39341. });
  39342. }
  39343. };
  39344. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  39345. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  39346. };
  39347. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  39348. var index;
  39349. var mat;
  39350. for (index = 0; index < this._physicsMaterials.length; index++) {
  39351. mat = this._physicsMaterials[index];
  39352. if (mat.friction === friction && mat.restitution === restitution) {
  39353. return mat;
  39354. }
  39355. }
  39356. var currentMat = new CANNON.Material(name);
  39357. currentMat.friction = friction;
  39358. currentMat.restitution = restitution;
  39359. this._physicsMaterials.push(currentMat);
  39360. return currentMat;
  39361. };
  39362. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  39363. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  39364. };
  39365. CannonJSPlugin.prototype._createShape = function (impostor) {
  39366. var object = impostor.object;
  39367. var returnValue;
  39368. var extendSize = impostor.getObjectExtendSize();
  39369. switch (impostor.type) {
  39370. case BABYLON.PhysicsEngine.SphereImpostor:
  39371. var radiusX = extendSize.x;
  39372. var radiusY = extendSize.y;
  39373. var radiusZ = extendSize.z;
  39374. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  39375. break;
  39376. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  39377. case BABYLON.PhysicsImpostor.CylinderImpostor:
  39378. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  39379. break;
  39380. case BABYLON.PhysicsImpostor.BoxImpostor:
  39381. var box = extendSize.scale(0.5);
  39382. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  39383. break;
  39384. case BABYLON.PhysicsImpostor.PlaneImpostor:
  39385. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  39386. returnValue = new CANNON.Plane();
  39387. break;
  39388. case BABYLON.PhysicsImpostor.MeshImpostor:
  39389. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  39390. var rawFaces = object.getIndices ? object.getIndices() : [];
  39391. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  39392. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  39393. break;
  39394. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  39395. returnValue = this._createHeightmap(object);
  39396. break;
  39397. case BABYLON.PhysicsImpostor.ParticleImpostor:
  39398. returnValue = new CANNON.Particle();
  39399. break;
  39400. }
  39401. return returnValue;
  39402. };
  39403. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  39404. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39405. var matrix = [];
  39406. //For now pointDepth will not be used and will be automatically calculated.
  39407. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  39408. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  39409. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  39410. var elementSize = dim * 2 / arraySize;
  39411. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  39412. for (var i = 0; i < pos.length; i = i + 3) {
  39413. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  39414. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  39415. var y = pos[i + 1] + minY;
  39416. if (!matrix[x]) {
  39417. matrix[x] = [];
  39418. }
  39419. if (!matrix[x][z]) {
  39420. matrix[x][z] = y;
  39421. }
  39422. matrix[x][z] = Math.max(y, matrix[x][z]);
  39423. }
  39424. for (var x = 0; x <= arraySize; ++x) {
  39425. if (!matrix[x]) {
  39426. var loc = 1;
  39427. while (!matrix[(x + loc) % arraySize]) {
  39428. loc++;
  39429. }
  39430. matrix[x] = matrix[(x + loc) % arraySize].slice();
  39431. }
  39432. for (var z = 0; z <= arraySize; ++z) {
  39433. if (!matrix[x][z]) {
  39434. var loc = 1;
  39435. var newValue;
  39436. while (newValue === undefined) {
  39437. newValue = matrix[x][(z + loc++) % arraySize];
  39438. }
  39439. matrix[x][z] = newValue;
  39440. }
  39441. }
  39442. }
  39443. var shape = new CANNON.Heightfield(matrix, {
  39444. elementSize: elementSize
  39445. });
  39446. //For future reference, needed for body transformation
  39447. shape.minY = minY;
  39448. return shape;
  39449. };
  39450. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  39451. var object = impostor.object;
  39452. //make sure it is updated...
  39453. object.computeWorldMatrix && object.computeWorldMatrix(true);
  39454. // The delta between the mesh position and the mesh bounding box center
  39455. var center = impostor.getObjectCenter();
  39456. var extendSize = impostor.getObjectExtendSize();
  39457. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  39458. this._tmpPosition.copyFrom(center);
  39459. var quaternion = object.rotationQuaternion;
  39460. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  39461. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  39462. //-90 DEG in X, precalculated
  39463. quaternion = quaternion.multiply(this._minus90X);
  39464. //Invert! (Precalculated, 90 deg in X)
  39465. //No need to clone. this will never change.
  39466. impostor.setDeltaRotation(this._plus90X);
  39467. }
  39468. //If it is a heightfield, if should be centered.
  39469. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  39470. var mesh = object;
  39471. //calculate the correct body position:
  39472. var rotationQuaternion = mesh.rotationQuaternion;
  39473. mesh.rotationQuaternion = this._tmpUnityRotation;
  39474. mesh.computeWorldMatrix(true);
  39475. //get original center with no rotation
  39476. var c = center.clone();
  39477. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  39478. //rotation is back
  39479. mesh.rotationQuaternion = rotationQuaternion;
  39480. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  39481. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  39482. mesh.setPivotMatrix(p);
  39483. mesh.computeWorldMatrix(true);
  39484. //calculate the translation
  39485. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  39486. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  39487. //add it inverted to the delta
  39488. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  39489. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  39490. mesh.setPivotMatrix(oldPivot);
  39491. mesh.computeWorldMatrix(true);
  39492. }
  39493. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  39494. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  39495. this._tmpPosition.copyFrom(object.position);
  39496. }
  39497. impostor.setDeltaPosition(this._tmpDeltaPosition);
  39498. //Now update the impostor object
  39499. impostor.physicsBody.position.copy(this._tmpPosition);
  39500. impostor.physicsBody.quaternion.copy(quaternion);
  39501. };
  39502. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  39503. impostor.object.position.copyFrom(impostor.physicsBody.position);
  39504. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  39505. };
  39506. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  39507. impostor.physicsBody.position.copy(newPosition);
  39508. impostor.physicsBody.quaternion.copy(newRotation);
  39509. };
  39510. CannonJSPlugin.prototype.isSupported = function () {
  39511. return window.CANNON !== undefined;
  39512. };
  39513. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  39514. impostor.physicsBody.velocity.copy(velocity);
  39515. };
  39516. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  39517. impostor.physicsBody.angularVelocity.copy(velocity);
  39518. };
  39519. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  39520. var v = impostor.physicsBody.velocity;
  39521. if (!v)
  39522. return null;
  39523. return new BABYLON.Vector3(v.x, v.y, v.z);
  39524. };
  39525. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  39526. var v = impostor.physicsBody.angularVelocity;
  39527. if (!v)
  39528. return null;
  39529. return new BABYLON.Vector3(v.x, v.y, v.z);
  39530. };
  39531. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  39532. impostor.physicsBody.mass = mass;
  39533. impostor.physicsBody.updateMassProperties();
  39534. };
  39535. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  39536. impostor.physicsBody.sleep();
  39537. };
  39538. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  39539. impostor.physicsBody.wakeUp();
  39540. };
  39541. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  39542. joint.physicsJoint.distance = maxDistance;
  39543. };
  39544. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  39545. if (!motorIndex) {
  39546. joint.physicsJoint.enableMotor();
  39547. }
  39548. };
  39549. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  39550. if (!motorIndex) {
  39551. joint.physicsJoint.disableMotor();
  39552. }
  39553. };
  39554. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  39555. if (!motorIndex) {
  39556. joint.physicsJoint.enableMotor();
  39557. joint.physicsJoint.setMotorSpeed(speed);
  39558. if (maxForce) {
  39559. this.setLimit(joint, maxForce);
  39560. }
  39561. }
  39562. };
  39563. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  39564. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  39565. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  39566. };
  39567. CannonJSPlugin.prototype.dispose = function () {
  39568. //nothing to do, actually.
  39569. };
  39570. return CannonJSPlugin;
  39571. }());
  39572. BABYLON.CannonJSPlugin = CannonJSPlugin;
  39573. })(BABYLON || (BABYLON = {}));
  39574. var BABYLON;
  39575. (function (BABYLON) {
  39576. var OimoJSPlugin = (function () {
  39577. function OimoJSPlugin(iterations) {
  39578. this.name = "OimoJSPlugin";
  39579. this._tmpImpostorsArray = [];
  39580. this._tmpPositionVector = BABYLON.Vector3.Zero();
  39581. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  39582. this.world.clear();
  39583. //making sure no stats are calculated
  39584. this.world.isNoStat = true;
  39585. }
  39586. OimoJSPlugin.prototype.setGravity = function (gravity) {
  39587. this.world.gravity.copy(gravity);
  39588. };
  39589. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  39590. this.world.timeStep = timeStep;
  39591. };
  39592. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  39593. var _this = this;
  39594. impostors.forEach(function (impostor) {
  39595. impostor.beforeStep();
  39596. });
  39597. this.world.step();
  39598. impostors.forEach(function (impostor) {
  39599. impostor.afterStep();
  39600. //update the ordered impostors array
  39601. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  39602. });
  39603. //check for collisions
  39604. var contact = this.world.contacts;
  39605. while (contact !== null) {
  39606. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  39607. contact = contact.next;
  39608. continue;
  39609. }
  39610. //is this body colliding with any other? get the impostor
  39611. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  39612. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  39613. if (!mainImpostor || !collidingImpostor) {
  39614. contact = contact.next;
  39615. continue;
  39616. }
  39617. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  39618. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  39619. contact = contact.next;
  39620. }
  39621. };
  39622. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  39623. var mass = impostor.physicsBody.massInfo.mass;
  39624. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  39625. };
  39626. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  39627. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  39628. this.applyImpulse(impostor, force, contactPoint);
  39629. };
  39630. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  39631. var _this = this;
  39632. //parent-child relationship. Does this impostor has a parent impostor?
  39633. if (impostor.parent) {
  39634. if (impostor.physicsBody) {
  39635. this.removePhysicsBody(impostor);
  39636. //TODO is that needed?
  39637. impostor.forceUpdate();
  39638. }
  39639. return;
  39640. }
  39641. if (impostor.isBodyInitRequired()) {
  39642. var bodyConfig = {
  39643. name: impostor.uniqueId,
  39644. //Oimo must have mass, also for static objects.
  39645. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  39646. size: [],
  39647. type: [],
  39648. pos: [],
  39649. rot: [],
  39650. move: impostor.getParam("mass") !== 0,
  39651. //Supporting older versions of Oimo
  39652. world: this.world
  39653. };
  39654. var impostors = [impostor];
  39655. var addToArray = function (parent) {
  39656. if (!parent.getChildMeshes)
  39657. return;
  39658. parent.getChildMeshes().forEach(function (m) {
  39659. if (m.physicsImpostor) {
  39660. impostors.push(m.physicsImpostor);
  39661. m.physicsImpostor._init();
  39662. }
  39663. });
  39664. };
  39665. addToArray(impostor.object);
  39666. var checkWithEpsilon_1 = function (value) {
  39667. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  39668. };
  39669. impostors.forEach(function (i) {
  39670. //get the correct bounding box
  39671. var oldQuaternion = i.object.rotationQuaternion;
  39672. var rot = new OIMO.Euler().setFromQuaternion({
  39673. x: impostor.object.rotationQuaternion.x,
  39674. y: impostor.object.rotationQuaternion.y,
  39675. z: impostor.object.rotationQuaternion.z,
  39676. s: impostor.object.rotationQuaternion.w
  39677. });
  39678. var extendSize = i.getObjectExtendSize();
  39679. if (i === impostor) {
  39680. var center = impostor.getObjectCenter();
  39681. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  39682. //Can also use Array.prototype.push.apply
  39683. bodyConfig.pos.push(center.x);
  39684. bodyConfig.pos.push(center.y);
  39685. bodyConfig.pos.push(center.z);
  39686. //tmp solution
  39687. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  39688. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  39689. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  39690. }
  39691. else {
  39692. bodyConfig.pos.push(i.object.position.x);
  39693. bodyConfig.pos.push(i.object.position.y);
  39694. bodyConfig.pos.push(i.object.position.z);
  39695. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  39696. bodyConfig.rot.push(0);
  39697. bodyConfig.rot.push(0);
  39698. bodyConfig.rot.push(0);
  39699. }
  39700. // register mesh
  39701. switch (i.type) {
  39702. case BABYLON.PhysicsImpostor.ParticleImpostor:
  39703. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  39704. case BABYLON.PhysicsImpostor.SphereImpostor:
  39705. var radiusX = extendSize.x;
  39706. var radiusY = extendSize.y;
  39707. var radiusZ = extendSize.z;
  39708. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  39709. bodyConfig.type.push('sphere');
  39710. //due to the way oimo works with compounds, add 3 times
  39711. bodyConfig.size.push(size);
  39712. bodyConfig.size.push(size);
  39713. bodyConfig.size.push(size);
  39714. break;
  39715. case BABYLON.PhysicsImpostor.CylinderImpostor:
  39716. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  39717. var sizeY = checkWithEpsilon_1(extendSize.y);
  39718. bodyConfig.type.push('cylinder');
  39719. bodyConfig.size.push(sizeX);
  39720. bodyConfig.size.push(sizeY);
  39721. //due to the way oimo works with compounds, add one more value.
  39722. bodyConfig.size.push(sizeY);
  39723. break;
  39724. case BABYLON.PhysicsImpostor.PlaneImpostor:
  39725. case BABYLON.PhysicsImpostor.BoxImpostor:
  39726. default:
  39727. var sizeX = checkWithEpsilon_1(extendSize.x);
  39728. var sizeY = checkWithEpsilon_1(extendSize.y);
  39729. var sizeZ = checkWithEpsilon_1(extendSize.z);
  39730. bodyConfig.type.push('box');
  39731. bodyConfig.size.push(sizeX);
  39732. bodyConfig.size.push(sizeY);
  39733. bodyConfig.size.push(sizeZ);
  39734. break;
  39735. }
  39736. //actually not needed, but hey...
  39737. i.object.rotationQuaternion = oldQuaternion;
  39738. });
  39739. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  39740. }
  39741. else {
  39742. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  39743. }
  39744. impostor.setDeltaPosition(this._tmpPositionVector);
  39745. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  39746. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  39747. };
  39748. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  39749. //impostor.physicsBody.dispose();
  39750. //Same as : (older oimo versions)
  39751. this.world.removeRigidBody(impostor.physicsBody);
  39752. };
  39753. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  39754. var mainBody = impostorJoint.mainImpostor.physicsBody;
  39755. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  39756. if (!mainBody || !connectedBody) {
  39757. return;
  39758. }
  39759. var jointData = impostorJoint.joint.jointData;
  39760. var options = jointData.nativeParams || {};
  39761. var type;
  39762. var nativeJointData = {
  39763. body1: mainBody,
  39764. body2: connectedBody,
  39765. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  39766. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  39767. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  39768. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  39769. min: options.min,
  39770. max: options.max,
  39771. collision: options.collision || jointData.collision,
  39772. spring: options.spring,
  39773. //supporting older version of Oimo
  39774. world: this.world
  39775. };
  39776. switch (impostorJoint.joint.type) {
  39777. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  39778. type = "jointBall";
  39779. break;
  39780. case BABYLON.PhysicsJoint.SpringJoint:
  39781. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  39782. var springData = jointData;
  39783. nativeJointData.min = springData.length || nativeJointData.min;
  39784. //Max should also be set, just make sure it is at least min
  39785. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  39786. case BABYLON.PhysicsJoint.DistanceJoint:
  39787. type = "jointDistance";
  39788. nativeJointData.max = jointData.maxDistance;
  39789. break;
  39790. case BABYLON.PhysicsJoint.PrismaticJoint:
  39791. type = "jointPrisme";
  39792. break;
  39793. case BABYLON.PhysicsJoint.SliderJoint:
  39794. type = "jointSlide";
  39795. break;
  39796. case BABYLON.PhysicsJoint.WheelJoint:
  39797. type = "jointWheel";
  39798. break;
  39799. case BABYLON.PhysicsJoint.HingeJoint:
  39800. default:
  39801. type = "jointHinge";
  39802. break;
  39803. }
  39804. nativeJointData.type = type;
  39805. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  39806. };
  39807. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  39808. //Bug in Oimo prevents us from disposing a joint in the playground
  39809. //joint.joint.physicsJoint.dispose();
  39810. //So we will bruteforce it!
  39811. try {
  39812. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  39813. }
  39814. catch (e) {
  39815. BABYLON.Tools.Warn(e);
  39816. }
  39817. };
  39818. OimoJSPlugin.prototype.isSupported = function () {
  39819. return OIMO !== undefined;
  39820. };
  39821. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  39822. if (!impostor.physicsBody.sleeping) {
  39823. //TODO check that
  39824. if (impostor.physicsBody.shapes.next) {
  39825. var parentShape = this._getLastShape(impostor.physicsBody);
  39826. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  39827. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  39828. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  39829. }
  39830. else {
  39831. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  39832. }
  39833. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  39834. impostor.object.rotationQuaternion.normalize();
  39835. }
  39836. };
  39837. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  39838. var body = impostor.physicsBody;
  39839. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  39840. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  39841. body.syncShapes();
  39842. body.awake();
  39843. };
  39844. OimoJSPlugin.prototype._getLastShape = function (body) {
  39845. var lastShape = body.shapes;
  39846. while (lastShape.next) {
  39847. lastShape = lastShape.next;
  39848. }
  39849. return lastShape;
  39850. };
  39851. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  39852. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  39853. };
  39854. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  39855. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  39856. };
  39857. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  39858. var v = impostor.physicsBody.linearVelocity;
  39859. if (!v)
  39860. return null;
  39861. return new BABYLON.Vector3(v.x, v.y, v.z);
  39862. };
  39863. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  39864. var v = impostor.physicsBody.angularVelocity;
  39865. if (!v)
  39866. return null;
  39867. return new BABYLON.Vector3(v.x, v.y, v.z);
  39868. };
  39869. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  39870. var staticBody = mass === 0;
  39871. //this will actually set the body's density and not its mass.
  39872. //But this is how oimo treats the mass variable.
  39873. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  39874. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  39875. };
  39876. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  39877. impostor.physicsBody.sleep();
  39878. };
  39879. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  39880. impostor.physicsBody.awake();
  39881. };
  39882. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  39883. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  39884. if (minDistance !== void 0) {
  39885. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  39886. }
  39887. };
  39888. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  39889. //TODO separate rotational and transational motors.
  39890. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  39891. if (motor) {
  39892. motor.setMotor(speed, maxForce);
  39893. }
  39894. };
  39895. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  39896. //TODO separate rotational and transational motors.
  39897. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  39898. if (motor) {
  39899. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  39900. }
  39901. };
  39902. OimoJSPlugin.prototype.dispose = function () {
  39903. this.world.clear();
  39904. };
  39905. return OimoJSPlugin;
  39906. }());
  39907. BABYLON.OimoJSPlugin = OimoJSPlugin;
  39908. })(BABYLON || (BABYLON = {}));
  39909. var BABYLON;
  39910. (function (BABYLON) {
  39911. var DisplayPassPostProcess = (function (_super) {
  39912. __extends(DisplayPassPostProcess, _super);
  39913. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  39914. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  39915. }
  39916. return DisplayPassPostProcess;
  39917. }(BABYLON.PostProcess));
  39918. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  39919. })(BABYLON || (BABYLON = {}));
  39920. var BABYLON;
  39921. (function (BABYLON) {
  39922. var SimplificationSettings = (function () {
  39923. function SimplificationSettings(quality, distance, optimizeMesh) {
  39924. this.quality = quality;
  39925. this.distance = distance;
  39926. this.optimizeMesh = optimizeMesh;
  39927. }
  39928. return SimplificationSettings;
  39929. }());
  39930. BABYLON.SimplificationSettings = SimplificationSettings;
  39931. var SimplificationQueue = (function () {
  39932. function SimplificationQueue() {
  39933. this.running = false;
  39934. this._simplificationArray = [];
  39935. }
  39936. SimplificationQueue.prototype.addTask = function (task) {
  39937. this._simplificationArray.push(task);
  39938. };
  39939. SimplificationQueue.prototype.executeNext = function () {
  39940. var task = this._simplificationArray.pop();
  39941. if (task) {
  39942. this.running = true;
  39943. this.runSimplification(task);
  39944. }
  39945. else {
  39946. this.running = false;
  39947. }
  39948. };
  39949. SimplificationQueue.prototype.runSimplification = function (task) {
  39950. var _this = this;
  39951. if (task.parallelProcessing) {
  39952. //parallel simplifier
  39953. task.settings.forEach(function (setting) {
  39954. var simplifier = _this.getSimplifier(task);
  39955. simplifier.simplify(setting, function (newMesh) {
  39956. task.mesh.addLODLevel(setting.distance, newMesh);
  39957. newMesh.isVisible = true;
  39958. //check if it is the last
  39959. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  39960. //all done, run the success callback.
  39961. task.successCallback();
  39962. }
  39963. _this.executeNext();
  39964. });
  39965. });
  39966. }
  39967. else {
  39968. //single simplifier.
  39969. var simplifier = this.getSimplifier(task);
  39970. var runDecimation = function (setting, callback) {
  39971. simplifier.simplify(setting, function (newMesh) {
  39972. task.mesh.addLODLevel(setting.distance, newMesh);
  39973. newMesh.isVisible = true;
  39974. //run the next quality level
  39975. callback();
  39976. });
  39977. };
  39978. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  39979. runDecimation(task.settings[loop.index], function () {
  39980. loop.executeNext();
  39981. });
  39982. }, function () {
  39983. //execution ended, run the success callback.
  39984. if (task.successCallback) {
  39985. task.successCallback();
  39986. }
  39987. _this.executeNext();
  39988. });
  39989. }
  39990. };
  39991. SimplificationQueue.prototype.getSimplifier = function (task) {
  39992. switch (task.simplificationType) {
  39993. case SimplificationType.QUADRATIC:
  39994. default:
  39995. return new QuadraticErrorSimplification(task.mesh);
  39996. }
  39997. };
  39998. return SimplificationQueue;
  39999. }());
  40000. BABYLON.SimplificationQueue = SimplificationQueue;
  40001. /**
  40002. * The implemented types of simplification.
  40003. * At the moment only Quadratic Error Decimation is implemented.
  40004. */
  40005. (function (SimplificationType) {
  40006. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  40007. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  40008. var SimplificationType = BABYLON.SimplificationType;
  40009. var DecimationTriangle = (function () {
  40010. function DecimationTriangle(vertices) {
  40011. this.vertices = vertices;
  40012. this.error = new Array(4);
  40013. this.deleted = false;
  40014. this.isDirty = false;
  40015. this.deletePending = false;
  40016. this.borderFactor = 0;
  40017. }
  40018. return DecimationTriangle;
  40019. }());
  40020. BABYLON.DecimationTriangle = DecimationTriangle;
  40021. var DecimationVertex = (function () {
  40022. function DecimationVertex(position, id) {
  40023. this.position = position;
  40024. this.id = id;
  40025. this.isBorder = true;
  40026. this.q = new QuadraticMatrix();
  40027. this.triangleCount = 0;
  40028. this.triangleStart = 0;
  40029. this.originalOffsets = [];
  40030. }
  40031. DecimationVertex.prototype.updatePosition = function (newPosition) {
  40032. this.position.copyFrom(newPosition);
  40033. };
  40034. return DecimationVertex;
  40035. }());
  40036. BABYLON.DecimationVertex = DecimationVertex;
  40037. var QuadraticMatrix = (function () {
  40038. function QuadraticMatrix(data) {
  40039. this.data = new Array(10);
  40040. for (var i = 0; i < 10; ++i) {
  40041. if (data && data[i]) {
  40042. this.data[i] = data[i];
  40043. }
  40044. else {
  40045. this.data[i] = 0;
  40046. }
  40047. }
  40048. }
  40049. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  40050. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  40051. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  40052. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  40053. return det;
  40054. };
  40055. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  40056. for (var i = 0; i < 10; ++i) {
  40057. this.data[i] += matrix.data[i];
  40058. }
  40059. };
  40060. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  40061. for (var i = 0; i < 10; ++i) {
  40062. this.data[i] += data[i];
  40063. }
  40064. };
  40065. QuadraticMatrix.prototype.add = function (matrix) {
  40066. var m = new QuadraticMatrix();
  40067. for (var i = 0; i < 10; ++i) {
  40068. m.data[i] = this.data[i] + matrix.data[i];
  40069. }
  40070. return m;
  40071. };
  40072. QuadraticMatrix.FromData = function (a, b, c, d) {
  40073. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  40074. };
  40075. //returning an array to avoid garbage collection
  40076. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  40077. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  40078. };
  40079. return QuadraticMatrix;
  40080. }());
  40081. BABYLON.QuadraticMatrix = QuadraticMatrix;
  40082. var Reference = (function () {
  40083. function Reference(vertexId, triangleId) {
  40084. this.vertexId = vertexId;
  40085. this.triangleId = triangleId;
  40086. }
  40087. return Reference;
  40088. }());
  40089. BABYLON.Reference = Reference;
  40090. /**
  40091. * An implementation of the Quadratic Error simplification algorithm.
  40092. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  40093. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  40094. * @author RaananW
  40095. */
  40096. var QuadraticErrorSimplification = (function () {
  40097. function QuadraticErrorSimplification(_mesh) {
  40098. this._mesh = _mesh;
  40099. this.initialized = false;
  40100. this.syncIterations = 5000;
  40101. this.aggressiveness = 7;
  40102. this.decimationIterations = 100;
  40103. this.boundingBoxEpsilon = BABYLON.Epsilon;
  40104. }
  40105. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  40106. var _this = this;
  40107. this.initDecimatedMesh();
  40108. //iterating through the submeshes array, one after the other.
  40109. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  40110. _this.initWithMesh(loop.index, function () {
  40111. _this.runDecimation(settings, loop.index, function () {
  40112. loop.executeNext();
  40113. });
  40114. }, settings.optimizeMesh);
  40115. }, function () {
  40116. setTimeout(function () {
  40117. successCallback(_this._reconstructedMesh);
  40118. }, 0);
  40119. });
  40120. };
  40121. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  40122. var _this = this;
  40123. var gCount = 0;
  40124. triangle.vertices.forEach(function (vertex) {
  40125. var count = 0;
  40126. var vPos = vertex.position;
  40127. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  40128. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  40129. ++count;
  40130. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  40131. ++count;
  40132. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  40133. ++count;
  40134. if (count > 1) {
  40135. ++gCount;
  40136. }
  40137. ;
  40138. });
  40139. if (gCount > 1) {
  40140. console.log(triangle, gCount);
  40141. }
  40142. return gCount > 1;
  40143. };
  40144. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  40145. var _this = this;
  40146. var targetCount = ~~(this.triangles.length * settings.quality);
  40147. var deletedTriangles = 0;
  40148. var triangleCount = this.triangles.length;
  40149. var iterationFunction = function (iteration, callback) {
  40150. setTimeout(function () {
  40151. if (iteration % 5 === 0) {
  40152. _this.updateMesh(iteration === 0);
  40153. }
  40154. for (var i = 0; i < _this.triangles.length; ++i) {
  40155. _this.triangles[i].isDirty = false;
  40156. }
  40157. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  40158. var trianglesIterator = function (i) {
  40159. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  40160. var t = _this.triangles[tIdx];
  40161. if (!t)
  40162. return;
  40163. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  40164. return;
  40165. }
  40166. for (var j = 0; j < 3; ++j) {
  40167. if (t.error[j] < threshold) {
  40168. var deleted0 = [];
  40169. var deleted1 = [];
  40170. var v0 = t.vertices[j];
  40171. var v1 = t.vertices[(j + 1) % 3];
  40172. if (v0.isBorder || v1.isBorder)
  40173. continue;
  40174. var p = BABYLON.Vector3.Zero();
  40175. var n = BABYLON.Vector3.Zero();
  40176. var uv = BABYLON.Vector2.Zero();
  40177. var color = new BABYLON.Color4(0, 0, 0, 1);
  40178. _this.calculateError(v0, v1, p, n, uv, color);
  40179. var delTr = [];
  40180. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  40181. continue;
  40182. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  40183. continue;
  40184. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  40185. continue;
  40186. var uniqueArray = [];
  40187. delTr.forEach(function (deletedT) {
  40188. if (uniqueArray.indexOf(deletedT) === -1) {
  40189. deletedT.deletePending = true;
  40190. uniqueArray.push(deletedT);
  40191. }
  40192. });
  40193. if (uniqueArray.length % 2 !== 0) {
  40194. continue;
  40195. }
  40196. v0.q = v1.q.add(v0.q);
  40197. v0.updatePosition(p);
  40198. var tStart = _this.references.length;
  40199. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  40200. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  40201. var tCount = _this.references.length - tStart;
  40202. if (tCount <= v0.triangleCount) {
  40203. if (tCount) {
  40204. for (var c = 0; c < tCount; c++) {
  40205. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  40206. }
  40207. }
  40208. }
  40209. else {
  40210. v0.triangleStart = tStart;
  40211. }
  40212. v0.triangleCount = tCount;
  40213. break;
  40214. }
  40215. }
  40216. };
  40217. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  40218. }, 0);
  40219. };
  40220. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  40221. if (triangleCount - deletedTriangles <= targetCount)
  40222. loop.breakLoop();
  40223. else {
  40224. iterationFunction(loop.index, function () {
  40225. loop.executeNext();
  40226. });
  40227. }
  40228. }, function () {
  40229. setTimeout(function () {
  40230. //reconstruct this part of the mesh
  40231. _this.reconstructMesh(submeshIndex);
  40232. successCallback();
  40233. }, 0);
  40234. });
  40235. };
  40236. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  40237. var _this = this;
  40238. this.vertices = [];
  40239. this.triangles = [];
  40240. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40241. var indices = this._mesh.getIndices();
  40242. var submesh = this._mesh.subMeshes[submeshIndex];
  40243. var findInVertices = function (positionToSearch) {
  40244. if (optimizeMesh) {
  40245. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  40246. if (_this.vertices[ii].position.equals(positionToSearch)) {
  40247. return _this.vertices[ii];
  40248. }
  40249. }
  40250. }
  40251. return null;
  40252. };
  40253. var vertexReferences = [];
  40254. var vertexInit = function (i) {
  40255. var offset = i + submesh.verticesStart;
  40256. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  40257. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  40258. vertex.originalOffsets.push(offset);
  40259. if (vertex.id === _this.vertices.length) {
  40260. _this.vertices.push(vertex);
  40261. }
  40262. vertexReferences.push(vertex.id);
  40263. };
  40264. //var totalVertices = mesh.getTotalVertices();
  40265. var totalVertices = submesh.verticesCount;
  40266. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  40267. var indicesInit = function (i) {
  40268. var offset = (submesh.indexStart / 3) + i;
  40269. var pos = (offset * 3);
  40270. var i0 = indices[pos + 0];
  40271. var i1 = indices[pos + 1];
  40272. var i2 = indices[pos + 2];
  40273. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  40274. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  40275. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  40276. var triangle = new DecimationTriangle([v0, v1, v2]);
  40277. triangle.originalOffset = pos;
  40278. _this.triangles.push(triangle);
  40279. };
  40280. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  40281. _this.init(callback);
  40282. });
  40283. });
  40284. };
  40285. QuadraticErrorSimplification.prototype.init = function (callback) {
  40286. var _this = this;
  40287. var triangleInit1 = function (i) {
  40288. var t = _this.triangles[i];
  40289. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  40290. for (var j = 0; j < 3; j++) {
  40291. 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))));
  40292. }
  40293. };
  40294. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  40295. var triangleInit2 = function (i) {
  40296. var t = _this.triangles[i];
  40297. for (var j = 0; j < 3; ++j) {
  40298. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  40299. }
  40300. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  40301. };
  40302. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  40303. _this.initialized = true;
  40304. callback();
  40305. });
  40306. });
  40307. };
  40308. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  40309. var newTriangles = [];
  40310. var i;
  40311. for (i = 0; i < this.vertices.length; ++i) {
  40312. this.vertices[i].triangleCount = 0;
  40313. }
  40314. var t;
  40315. var j;
  40316. for (i = 0; i < this.triangles.length; ++i) {
  40317. if (!this.triangles[i].deleted) {
  40318. t = this.triangles[i];
  40319. for (j = 0; j < 3; ++j) {
  40320. t.vertices[j].triangleCount = 1;
  40321. }
  40322. newTriangles.push(t);
  40323. }
  40324. }
  40325. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  40326. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  40327. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  40328. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  40329. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40330. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40331. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40332. var vertexCount = 0;
  40333. for (i = 0; i < this.vertices.length; ++i) {
  40334. var vertex = this.vertices[i];
  40335. vertex.id = vertexCount;
  40336. if (vertex.triangleCount) {
  40337. vertex.originalOffsets.forEach(function (originalOffset) {
  40338. newPositionData.push(vertex.position.x);
  40339. newPositionData.push(vertex.position.y);
  40340. newPositionData.push(vertex.position.z);
  40341. newNormalData.push(normalData[originalOffset * 3]);
  40342. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  40343. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  40344. if (uvs && uvs.length) {
  40345. newUVsData.push(uvs[(originalOffset * 2)]);
  40346. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  40347. }
  40348. else if (colorsData && colorsData.length) {
  40349. newColorsData.push(colorsData[(originalOffset * 4)]);
  40350. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  40351. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  40352. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  40353. }
  40354. ++vertexCount;
  40355. });
  40356. }
  40357. }
  40358. var startingIndex = this._reconstructedMesh.getTotalIndices();
  40359. var startingVertex = this._reconstructedMesh.getTotalVertices();
  40360. var submeshesArray = this._reconstructedMesh.subMeshes;
  40361. this._reconstructedMesh.subMeshes = [];
  40362. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  40363. var originalIndices = this._mesh.getIndices();
  40364. for (i = 0; i < newTriangles.length; ++i) {
  40365. t = newTriangles[i]; //now get the new referencing point for each vertex
  40366. [0, 1, 2].forEach(function (idx) {
  40367. var id = originalIndices[t.originalOffset + idx];
  40368. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  40369. if (offset < 0)
  40370. offset = 0;
  40371. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  40372. });
  40373. }
  40374. //overwriting the old vertex buffers and indices.
  40375. this._reconstructedMesh.setIndices(newIndicesArray);
  40376. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  40377. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  40378. if (newUVsData.length > 0)
  40379. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  40380. if (newColorsData.length > 0)
  40381. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  40382. //create submesh
  40383. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  40384. if (submeshIndex > 0) {
  40385. this._reconstructedMesh.subMeshes = [];
  40386. submeshesArray.forEach(function (submesh) {
  40387. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  40388. });
  40389. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  40390. }
  40391. };
  40392. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  40393. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  40394. this._reconstructedMesh.material = this._mesh.material;
  40395. this._reconstructedMesh.parent = this._mesh.parent;
  40396. this._reconstructedMesh.isVisible = false;
  40397. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  40398. };
  40399. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  40400. for (var i = 0; i < vertex1.triangleCount; ++i) {
  40401. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  40402. if (t.deleted)
  40403. continue;
  40404. var s = this.references[vertex1.triangleStart + i].vertexId;
  40405. var v1 = t.vertices[(s + 1) % 3];
  40406. var v2 = t.vertices[(s + 2) % 3];
  40407. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  40408. deletedArray[i] = true;
  40409. delTr.push(t);
  40410. continue;
  40411. }
  40412. var d1 = v1.position.subtract(point);
  40413. d1 = d1.normalize();
  40414. var d2 = v2.position.subtract(point);
  40415. d2 = d2.normalize();
  40416. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  40417. return true;
  40418. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  40419. deletedArray[i] = false;
  40420. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  40421. return true;
  40422. }
  40423. return false;
  40424. };
  40425. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  40426. var newDeleted = deletedTriangles;
  40427. for (var i = 0; i < vertex.triangleCount; ++i) {
  40428. var ref = this.references[vertex.triangleStart + i];
  40429. var t = this.triangles[ref.triangleId];
  40430. if (t.deleted)
  40431. continue;
  40432. if (deletedArray[i] && t.deletePending) {
  40433. t.deleted = true;
  40434. newDeleted++;
  40435. continue;
  40436. }
  40437. t.vertices[ref.vertexId] = origVertex;
  40438. t.isDirty = true;
  40439. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  40440. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  40441. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  40442. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  40443. this.references.push(ref);
  40444. }
  40445. return newDeleted;
  40446. };
  40447. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  40448. for (var i = 0; i < this.vertices.length; ++i) {
  40449. var vCount = [];
  40450. var vId = [];
  40451. var v = this.vertices[i];
  40452. var j;
  40453. for (j = 0; j < v.triangleCount; ++j) {
  40454. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  40455. for (var ii = 0; ii < 3; ii++) {
  40456. var ofs = 0;
  40457. var vv = triangle.vertices[ii];
  40458. while (ofs < vCount.length) {
  40459. if (vId[ofs] === vv.id)
  40460. break;
  40461. ++ofs;
  40462. }
  40463. if (ofs === vCount.length) {
  40464. vCount.push(1);
  40465. vId.push(vv.id);
  40466. }
  40467. else {
  40468. vCount[ofs]++;
  40469. }
  40470. }
  40471. }
  40472. for (j = 0; j < vCount.length; ++j) {
  40473. if (vCount[j] === 1) {
  40474. this.vertices[vId[j]].isBorder = true;
  40475. }
  40476. else {
  40477. this.vertices[vId[j]].isBorder = false;
  40478. }
  40479. }
  40480. }
  40481. };
  40482. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  40483. if (identifyBorders === void 0) { identifyBorders = false; }
  40484. var i;
  40485. if (!identifyBorders) {
  40486. var newTrianglesVector = [];
  40487. for (i = 0; i < this.triangles.length; ++i) {
  40488. if (!this.triangles[i].deleted) {
  40489. newTrianglesVector.push(this.triangles[i]);
  40490. }
  40491. }
  40492. this.triangles = newTrianglesVector;
  40493. }
  40494. for (i = 0; i < this.vertices.length; ++i) {
  40495. this.vertices[i].triangleCount = 0;
  40496. this.vertices[i].triangleStart = 0;
  40497. }
  40498. var t;
  40499. var j;
  40500. var v;
  40501. for (i = 0; i < this.triangles.length; ++i) {
  40502. t = this.triangles[i];
  40503. for (j = 0; j < 3; ++j) {
  40504. v = t.vertices[j];
  40505. v.triangleCount++;
  40506. }
  40507. }
  40508. var tStart = 0;
  40509. for (i = 0; i < this.vertices.length; ++i) {
  40510. this.vertices[i].triangleStart = tStart;
  40511. tStart += this.vertices[i].triangleCount;
  40512. this.vertices[i].triangleCount = 0;
  40513. }
  40514. var newReferences = new Array(this.triangles.length * 3);
  40515. for (i = 0; i < this.triangles.length; ++i) {
  40516. t = this.triangles[i];
  40517. for (j = 0; j < 3; ++j) {
  40518. v = t.vertices[j];
  40519. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  40520. v.triangleCount++;
  40521. }
  40522. }
  40523. this.references = newReferences;
  40524. if (identifyBorders) {
  40525. this.identifyBorder();
  40526. }
  40527. };
  40528. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  40529. var x = point.x;
  40530. var y = point.y;
  40531. var z = point.z;
  40532. 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
  40533. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  40534. };
  40535. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  40536. var q = vertex1.q.add(vertex2.q);
  40537. var border = vertex1.isBorder && vertex2.isBorder;
  40538. var error = 0;
  40539. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  40540. if (qDet !== 0 && !border) {
  40541. if (!pointResult) {
  40542. pointResult = BABYLON.Vector3.Zero();
  40543. }
  40544. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  40545. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  40546. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  40547. error = this.vertexError(q, pointResult);
  40548. }
  40549. else {
  40550. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  40551. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  40552. var error1 = this.vertexError(q, vertex1.position);
  40553. var error2 = this.vertexError(q, vertex2.position);
  40554. var error3 = this.vertexError(q, p3);
  40555. error = Math.min(error1, error2, error3);
  40556. if (error === error1) {
  40557. if (pointResult) {
  40558. pointResult.copyFrom(vertex1.position);
  40559. }
  40560. }
  40561. else if (error === error2) {
  40562. if (pointResult) {
  40563. pointResult.copyFrom(vertex2.position);
  40564. }
  40565. }
  40566. else {
  40567. if (pointResult) {
  40568. pointResult.copyFrom(p3);
  40569. }
  40570. }
  40571. }
  40572. return error;
  40573. };
  40574. return QuadraticErrorSimplification;
  40575. }());
  40576. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  40577. })(BABYLON || (BABYLON = {}));
  40578. var BABYLON;
  40579. (function (BABYLON) {
  40580. var serializedGeometries = [];
  40581. var serializeGeometry = function (geometry, serializationGeometries) {
  40582. if (serializedGeometries[geometry.id]) {
  40583. return;
  40584. }
  40585. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  40586. serializationGeometries.boxes.push(geometry.serialize());
  40587. }
  40588. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  40589. serializationGeometries.spheres.push(geometry.serialize());
  40590. }
  40591. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  40592. serializationGeometries.cylinders.push(geometry.serialize());
  40593. }
  40594. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  40595. serializationGeometries.toruses.push(geometry.serialize());
  40596. }
  40597. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  40598. serializationGeometries.grounds.push(geometry.serialize());
  40599. }
  40600. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  40601. serializationGeometries.planes.push(geometry.serialize());
  40602. }
  40603. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  40604. serializationGeometries.torusKnots.push(geometry.serialize());
  40605. }
  40606. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  40607. throw new Error("Unknown primitive type");
  40608. }
  40609. else {
  40610. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  40611. }
  40612. serializedGeometries[geometry.id] = true;
  40613. };
  40614. var serializeMesh = function (mesh, serializationScene) {
  40615. var serializationObject = {};
  40616. serializationObject.name = mesh.name;
  40617. serializationObject.id = mesh.id;
  40618. if (BABYLON.Tags.HasTags(mesh)) {
  40619. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  40620. }
  40621. serializationObject.position = mesh.position.asArray();
  40622. if (mesh.rotationQuaternion) {
  40623. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  40624. }
  40625. else if (mesh.rotation) {
  40626. serializationObject.rotation = mesh.rotation.asArray();
  40627. }
  40628. serializationObject.scaling = mesh.scaling.asArray();
  40629. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  40630. serializationObject.isEnabled = mesh.isEnabled();
  40631. serializationObject.isVisible = mesh.isVisible;
  40632. serializationObject.infiniteDistance = mesh.infiniteDistance;
  40633. serializationObject.pickable = mesh.isPickable;
  40634. serializationObject.receiveShadows = mesh.receiveShadows;
  40635. serializationObject.billboardMode = mesh.billboardMode;
  40636. serializationObject.visibility = mesh.visibility;
  40637. serializationObject.checkCollisions = mesh.checkCollisions;
  40638. // Parent
  40639. if (mesh.parent) {
  40640. serializationObject.parentId = mesh.parent.id;
  40641. }
  40642. // Geometry
  40643. var geometry = mesh._geometry;
  40644. if (geometry) {
  40645. var geometryId = geometry.id;
  40646. serializationObject.geometryId = geometryId;
  40647. if (!mesh.getScene().getGeometryByID(geometryId)) {
  40648. // 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
  40649. serializeGeometry(geometry, serializationScene.geometries);
  40650. }
  40651. // SubMeshes
  40652. serializationObject.subMeshes = [];
  40653. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40654. var subMesh = mesh.subMeshes[subIndex];
  40655. serializationObject.subMeshes.push({
  40656. materialIndex: subMesh.materialIndex,
  40657. verticesStart: subMesh.verticesStart,
  40658. verticesCount: subMesh.verticesCount,
  40659. indexStart: subMesh.indexStart,
  40660. indexCount: subMesh.indexCount
  40661. });
  40662. }
  40663. }
  40664. // Material
  40665. if (mesh.material) {
  40666. serializationObject.materialId = mesh.material.id;
  40667. }
  40668. else {
  40669. mesh.material = null;
  40670. }
  40671. // Skeleton
  40672. if (mesh.skeleton) {
  40673. serializationObject.skeletonId = mesh.skeleton.id;
  40674. }
  40675. // Physics
  40676. //TODO implement correct serialization for physics impostors.
  40677. if (mesh.getPhysicsImpostor()) {
  40678. serializationObject.physicsMass = mesh.getPhysicsMass();
  40679. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  40680. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  40681. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  40682. }
  40683. // Instances
  40684. serializationObject.instances = [];
  40685. for (var index = 0; index < mesh.instances.length; index++) {
  40686. var instance = mesh.instances[index];
  40687. var serializationInstance = {
  40688. name: instance.name,
  40689. position: instance.position.asArray(),
  40690. scaling: instance.scaling.asArray()
  40691. };
  40692. if (instance.rotationQuaternion) {
  40693. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  40694. }
  40695. else if (instance.rotation) {
  40696. serializationInstance.rotation = instance.rotation.asArray();
  40697. }
  40698. serializationObject.instances.push(serializationInstance);
  40699. // Animations
  40700. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  40701. serializationInstance.ranges = instance.serializeAnimationRanges();
  40702. }
  40703. // Animations
  40704. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  40705. serializationObject.ranges = mesh.serializeAnimationRanges();
  40706. // Layer mask
  40707. serializationObject.layerMask = mesh.layerMask;
  40708. // Action Manager
  40709. if (mesh.actionManager) {
  40710. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  40711. }
  40712. return serializationObject;
  40713. };
  40714. var finalizeSingleMesh = function (mesh, serializationObject) {
  40715. //only works if the mesh is already loaded
  40716. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  40717. //serialize material
  40718. if (mesh.material) {
  40719. if (mesh.material instanceof BABYLON.StandardMaterial) {
  40720. serializationObject.materials = serializationObject.materials || [];
  40721. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  40722. serializationObject.materials.push(mesh.material.serialize());
  40723. }
  40724. }
  40725. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  40726. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  40727. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  40728. serializationObject.multiMaterials.push(mesh.material.serialize());
  40729. }
  40730. }
  40731. }
  40732. //serialize geometry
  40733. var geometry = mesh._geometry;
  40734. if (geometry) {
  40735. if (!serializationObject.geometries) {
  40736. serializationObject.geometries = {};
  40737. serializationObject.geometries.boxes = [];
  40738. serializationObject.geometries.spheres = [];
  40739. serializationObject.geometries.cylinders = [];
  40740. serializationObject.geometries.toruses = [];
  40741. serializationObject.geometries.grounds = [];
  40742. serializationObject.geometries.planes = [];
  40743. serializationObject.geometries.torusKnots = [];
  40744. serializationObject.geometries.vertexData = [];
  40745. }
  40746. serializeGeometry(geometry, serializationObject.geometries);
  40747. }
  40748. // Skeletons
  40749. if (mesh.skeleton) {
  40750. serializationObject.skeletons = serializationObject.skeletons || [];
  40751. serializationObject.skeletons.push(mesh.skeleton.serialize());
  40752. }
  40753. //serialize the actual mesh
  40754. serializationObject.meshes = serializationObject.meshes || [];
  40755. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  40756. }
  40757. };
  40758. var SceneSerializer = (function () {
  40759. function SceneSerializer() {
  40760. }
  40761. SceneSerializer.ClearCache = function () {
  40762. serializedGeometries = [];
  40763. };
  40764. SceneSerializer.Serialize = function (scene) {
  40765. var serializationObject = {};
  40766. // Scene
  40767. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  40768. serializationObject.autoClear = scene.autoClear;
  40769. serializationObject.clearColor = scene.clearColor.asArray();
  40770. serializationObject.ambientColor = scene.ambientColor.asArray();
  40771. serializationObject.gravity = scene.gravity.asArray();
  40772. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  40773. serializationObject.workerCollisions = scene.workerCollisions;
  40774. // Fog
  40775. if (scene.fogMode && scene.fogMode !== 0) {
  40776. serializationObject.fogMode = scene.fogMode;
  40777. serializationObject.fogColor = scene.fogColor.asArray();
  40778. serializationObject.fogStart = scene.fogStart;
  40779. serializationObject.fogEnd = scene.fogEnd;
  40780. serializationObject.fogDensity = scene.fogDensity;
  40781. }
  40782. //Physics
  40783. if (scene.isPhysicsEnabled()) {
  40784. serializationObject.physicsEnabled = true;
  40785. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  40786. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  40787. }
  40788. // Lights
  40789. serializationObject.lights = [];
  40790. var index;
  40791. var light;
  40792. for (index = 0; index < scene.lights.length; index++) {
  40793. light = scene.lights[index];
  40794. serializationObject.lights.push(light.serialize());
  40795. }
  40796. // Cameras
  40797. serializationObject.cameras = [];
  40798. for (index = 0; index < scene.cameras.length; index++) {
  40799. var camera = scene.cameras[index];
  40800. serializationObject.cameras.push(camera.serialize());
  40801. }
  40802. if (scene.activeCamera) {
  40803. serializationObject.activeCameraID = scene.activeCamera.id;
  40804. }
  40805. // Animations
  40806. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  40807. // Materials
  40808. serializationObject.materials = [];
  40809. serializationObject.multiMaterials = [];
  40810. var material;
  40811. for (index = 0; index < scene.materials.length; index++) {
  40812. material = scene.materials[index];
  40813. serializationObject.materials.push(material.serialize());
  40814. }
  40815. // MultiMaterials
  40816. serializationObject.multiMaterials = [];
  40817. for (index = 0; index < scene.multiMaterials.length; index++) {
  40818. var multiMaterial = scene.multiMaterials[index];
  40819. serializationObject.multiMaterials.push(multiMaterial.serialize());
  40820. }
  40821. // Skeletons
  40822. serializationObject.skeletons = [];
  40823. for (index = 0; index < scene.skeletons.length; index++) {
  40824. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  40825. }
  40826. // Geometries
  40827. serializationObject.geometries = {};
  40828. serializationObject.geometries.boxes = [];
  40829. serializationObject.geometries.spheres = [];
  40830. serializationObject.geometries.cylinders = [];
  40831. serializationObject.geometries.toruses = [];
  40832. serializationObject.geometries.grounds = [];
  40833. serializationObject.geometries.planes = [];
  40834. serializationObject.geometries.torusKnots = [];
  40835. serializationObject.geometries.vertexData = [];
  40836. serializedGeometries = [];
  40837. var geometries = scene.getGeometries();
  40838. for (index = 0; index < geometries.length; index++) {
  40839. var geometry = geometries[index];
  40840. if (geometry.isReady()) {
  40841. serializeGeometry(geometry, serializationObject.geometries);
  40842. }
  40843. }
  40844. // Meshes
  40845. serializationObject.meshes = [];
  40846. for (index = 0; index < scene.meshes.length; index++) {
  40847. var abstractMesh = scene.meshes[index];
  40848. if (abstractMesh instanceof BABYLON.Mesh) {
  40849. var mesh = abstractMesh;
  40850. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  40851. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  40852. }
  40853. }
  40854. }
  40855. // Particles Systems
  40856. serializationObject.particleSystems = [];
  40857. for (index = 0; index < scene.particleSystems.length; index++) {
  40858. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  40859. }
  40860. // Lens flares
  40861. serializationObject.lensFlareSystems = [];
  40862. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  40863. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  40864. }
  40865. // Shadows
  40866. serializationObject.shadowGenerators = [];
  40867. for (index = 0; index < scene.lights.length; index++) {
  40868. light = scene.lights[index];
  40869. var shadowGenerator = light.getShadowGenerator();
  40870. // Only support serialization for official generator so far.
  40871. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  40872. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  40873. }
  40874. }
  40875. // Action Manager
  40876. if (scene.actionManager) {
  40877. serializationObject.actions = scene.actionManager.serialize("scene");
  40878. }
  40879. // Audio
  40880. serializationObject.sounds = [];
  40881. for (index = 0; index < scene.soundTracks.length; index++) {
  40882. var soundtrack = scene.soundTracks[index];
  40883. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  40884. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  40885. }
  40886. }
  40887. return serializationObject;
  40888. };
  40889. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  40890. if (withParents === void 0) { withParents = false; }
  40891. if (withChildren === void 0) { withChildren = false; }
  40892. var serializationObject = {};
  40893. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  40894. if (withParents || withChildren) {
  40895. //deliberate for loop! not for each, appended should be processed as well.
  40896. for (var i = 0; i < toSerialize.length; ++i) {
  40897. if (withChildren) {
  40898. toSerialize[i].getDescendants().forEach(function (node) {
  40899. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  40900. toSerialize.push(node);
  40901. }
  40902. });
  40903. }
  40904. //make sure the array doesn't contain the object already
  40905. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  40906. toSerialize.push(toSerialize[i].parent);
  40907. }
  40908. }
  40909. }
  40910. toSerialize.forEach(function (mesh) {
  40911. finalizeSingleMesh(mesh, serializationObject);
  40912. });
  40913. return serializationObject;
  40914. };
  40915. return SceneSerializer;
  40916. }());
  40917. BABYLON.SceneSerializer = SceneSerializer;
  40918. })(BABYLON || (BABYLON = {}));
  40919. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  40920. // Huge respect for a such great lib.
  40921. // Earcut license:
  40922. // Copyright (c) 2016, Mapbox
  40923. //
  40924. // Permission to use, copy, modify, and/or distribute this software for any purpose
  40925. // with or without fee is hereby granted, provided that the above copyright notice
  40926. // and this permission notice appear in all copies.
  40927. //
  40928. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  40929. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  40930. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  40931. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  40932. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  40933. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  40934. // THIS SOFTWARE.
  40935. var Earcut;
  40936. (function (Earcut) {
  40937. /**
  40938. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  40939. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  40940. * @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).
  40941. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  40942. */
  40943. function earcut(data, holeIndices, dim) {
  40944. dim = dim || 2;
  40945. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  40946. if (!outerNode)
  40947. return triangles;
  40948. var minX, minY, maxX, maxY, x, y, size;
  40949. if (hasHoles)
  40950. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  40951. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  40952. if (data.length > 80 * dim) {
  40953. minX = maxX = data[0];
  40954. minY = maxY = data[1];
  40955. for (var i = dim; i < outerLen; i += dim) {
  40956. x = data[i];
  40957. y = data[i + 1];
  40958. if (x < minX)
  40959. minX = x;
  40960. if (y < minY)
  40961. minY = y;
  40962. if (x > maxX)
  40963. maxX = x;
  40964. if (y > maxY)
  40965. maxY = y;
  40966. }
  40967. // minX, minY and size are later used to transform coords into integers for z-order calculation
  40968. size = Math.max(maxX - minX, maxY - minY);
  40969. }
  40970. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  40971. return triangles;
  40972. }
  40973. Earcut.earcut = earcut;
  40974. // create a circular doubly linked list from polygon points in the specified winding order
  40975. function linkedList(data, start, end, dim, clockwise) {
  40976. var i, last;
  40977. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  40978. for (i = start; i < end; i += dim)
  40979. last = insertNode(i, data[i], data[i + 1], last);
  40980. }
  40981. else {
  40982. for (i = end - dim; i >= start; i -= dim)
  40983. last = insertNode(i, data[i], data[i + 1], last);
  40984. }
  40985. if (last && equals(last, last.next)) {
  40986. removeNode(last);
  40987. last = last.next;
  40988. }
  40989. return last;
  40990. }
  40991. // eliminate colinear or duplicate points
  40992. function filterPoints(start, end) {
  40993. if (!start)
  40994. return start;
  40995. if (!end)
  40996. end = start;
  40997. var p = start, again;
  40998. do {
  40999. again = false;
  41000. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  41001. removeNode(p);
  41002. p = end = p.prev;
  41003. if (p === p.next)
  41004. return null;
  41005. again = true;
  41006. }
  41007. else {
  41008. p = p.next;
  41009. }
  41010. } while (again || p !== end);
  41011. return end;
  41012. }
  41013. // main ear slicing loop which triangulates a polygon (given as a linked list)
  41014. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  41015. if (!ear)
  41016. return;
  41017. // interlink polygon nodes in z-order
  41018. if (!pass && size)
  41019. indexCurve(ear, minX, minY, size);
  41020. var stop = ear, prev, next;
  41021. // iterate through ears, slicing them one by one
  41022. while (ear.prev !== ear.next) {
  41023. prev = ear.prev;
  41024. next = ear.next;
  41025. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  41026. // cut off the triangle
  41027. triangles.push(prev.i / dim);
  41028. triangles.push(ear.i / dim);
  41029. triangles.push(next.i / dim);
  41030. removeNode(ear);
  41031. // skipping the next vertice leads to less sliver triangles
  41032. ear = next.next;
  41033. stop = next.next;
  41034. continue;
  41035. }
  41036. ear = next;
  41037. // if we looped through the whole remaining polygon and can't find any more ears
  41038. if (ear === stop) {
  41039. // try filtering points and slicing again
  41040. if (!pass) {
  41041. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  41042. }
  41043. else if (pass === 1) {
  41044. ear = cureLocalIntersections(ear, triangles, dim);
  41045. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  41046. }
  41047. else if (pass === 2) {
  41048. splitEarcut(ear, triangles, dim, minX, minY, size);
  41049. }
  41050. break;
  41051. }
  41052. }
  41053. }
  41054. // check whether a polygon node forms a valid ear with adjacent nodes
  41055. function isEar(ear) {
  41056. var a = ear.prev, b = ear, c = ear.next;
  41057. if (area(a, b, c) >= 0)
  41058. return false; // reflex, can't be an ear
  41059. // now make sure we don't have other points inside the potential ear
  41060. var p = ear.next.next;
  41061. while (p !== ear.prev) {
  41062. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41063. area(p.prev, p, p.next) >= 0)
  41064. return false;
  41065. p = p.next;
  41066. }
  41067. return true;
  41068. }
  41069. function isEarHashed(ear, minX, minY, size) {
  41070. var a = ear.prev, b = ear, c = ear.next;
  41071. if (area(a, b, c) >= 0)
  41072. return false; // reflex, can't be an ear
  41073. // triangle bbox; min & max are calculated like this for speed
  41074. 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);
  41075. // z-order range for the current triangle bbox;
  41076. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  41077. // first look for points inside the triangle in increasing z-order
  41078. var p = ear.nextZ;
  41079. while (p && p.z <= maxZ) {
  41080. if (p !== ear.prev &&
  41081. p !== ear.next &&
  41082. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41083. area(p.prev, p, p.next) >= 0)
  41084. return false;
  41085. p = p.nextZ;
  41086. }
  41087. // then look for points in decreasing z-order
  41088. p = ear.prevZ;
  41089. while (p && p.z >= minZ) {
  41090. if (p !== ear.prev &&
  41091. p !== ear.next &&
  41092. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41093. area(p.prev, p, p.next) >= 0)
  41094. return false;
  41095. p = p.prevZ;
  41096. }
  41097. return true;
  41098. }
  41099. // go through all polygon nodes and cure small local self-intersections
  41100. function cureLocalIntersections(start, triangles, dim) {
  41101. var p = start;
  41102. do {
  41103. var a = p.prev, b = p.next.next;
  41104. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  41105. triangles.push(a.i / dim);
  41106. triangles.push(p.i / dim);
  41107. triangles.push(b.i / dim);
  41108. // remove two nodes involved
  41109. removeNode(p);
  41110. removeNode(p.next);
  41111. p = start = b;
  41112. }
  41113. p = p.next;
  41114. } while (p !== start);
  41115. return p;
  41116. }
  41117. // try splitting polygon into two and triangulate them independently
  41118. function splitEarcut(start, triangles, dim, minX, minY, size) {
  41119. // look for a valid diagonal that divides the polygon into two
  41120. var a = start;
  41121. do {
  41122. var b = a.next.next;
  41123. while (b !== a.prev) {
  41124. if (a.i !== b.i && isValidDiagonal(a, b)) {
  41125. // split the polygon in two by the diagonal
  41126. var c = splitPolygon(a, b);
  41127. // filter colinear points around the cuts
  41128. a = filterPoints(a, a.next);
  41129. c = filterPoints(c, c.next);
  41130. // run earcut on each half
  41131. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  41132. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  41133. return;
  41134. }
  41135. b = b.next;
  41136. }
  41137. a = a.next;
  41138. } while (a !== start);
  41139. }
  41140. // link every hole into the outer loop, producing a single-ring polygon without holes
  41141. function eliminateHoles(data, holeIndices, outerNode, dim) {
  41142. var queue = [], i, len, start, end, list;
  41143. for (i = 0, len = holeIndices.length; i < len; i++) {
  41144. start = holeIndices[i] * dim;
  41145. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  41146. list = linkedList(data, start, end, dim, false);
  41147. if (list === list.next)
  41148. list.steiner = true;
  41149. queue.push(getLeftmost(list));
  41150. }
  41151. queue.sort(compareX);
  41152. // process holes from left to right
  41153. for (i = 0; i < queue.length; i++) {
  41154. eliminateHole(queue[i], outerNode);
  41155. outerNode = filterPoints(outerNode, outerNode.next);
  41156. }
  41157. return outerNode;
  41158. }
  41159. function compareX(a, b) {
  41160. return a.x - b.x;
  41161. }
  41162. // find a bridge between vertices that connects hole with an outer ring and and link it
  41163. function eliminateHole(hole, outerNode) {
  41164. outerNode = findHoleBridge(hole, outerNode);
  41165. if (outerNode) {
  41166. var b = splitPolygon(outerNode, hole);
  41167. filterPoints(b, b.next);
  41168. }
  41169. }
  41170. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  41171. function findHoleBridge(hole, outerNode) {
  41172. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  41173. // find a segment intersected by a ray from the hole's leftmost point to the left;
  41174. // segment's endpoint with lesser x will be potential connection point
  41175. do {
  41176. if (hy <= p.y && hy >= p.next.y) {
  41177. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  41178. if (x <= hx && x > qx) {
  41179. qx = x;
  41180. if (x === hx) {
  41181. if (hy === p.y)
  41182. return p;
  41183. if (hy === p.next.y)
  41184. return p.next;
  41185. }
  41186. m = p.x < p.next.x ? p : p.next;
  41187. }
  41188. }
  41189. p = p.next;
  41190. } while (p !== outerNode);
  41191. if (!m)
  41192. return null;
  41193. if (hx === qx)
  41194. return m.prev; // hole touches outer segment; pick lower endpoint
  41195. // look for points inside the triangle of hole point, segment intersection and endpoint;
  41196. // if there are no points found, we have a valid connection;
  41197. // otherwise choose the point of the minimum angle with the ray as connection point
  41198. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  41199. p = m.next;
  41200. while (p !== stop) {
  41201. if (hx >= p.x &&
  41202. p.x >= mx &&
  41203. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  41204. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  41205. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  41206. m = p;
  41207. tanMin = tan;
  41208. }
  41209. }
  41210. p = p.next;
  41211. }
  41212. return m;
  41213. }
  41214. // interlink polygon nodes in z-order
  41215. function indexCurve(start, minX, minY, size) {
  41216. var p = start;
  41217. do {
  41218. if (p.z === null)
  41219. p.z = zOrder(p.x, p.y, minX, minY, size);
  41220. p.prevZ = p.prev;
  41221. p.nextZ = p.next;
  41222. p = p.next;
  41223. } while (p !== start);
  41224. p.prevZ.nextZ = null;
  41225. p.prevZ = null;
  41226. sortLinked(p);
  41227. }
  41228. // Simon Tatham's linked list merge sort algorithm
  41229. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  41230. function sortLinked(list) {
  41231. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  41232. do {
  41233. p = list;
  41234. list = null;
  41235. tail = null;
  41236. numMerges = 0;
  41237. while (p) {
  41238. numMerges++;
  41239. q = p;
  41240. pSize = 0;
  41241. for (i = 0; i < inSize; i++) {
  41242. pSize++;
  41243. q = q.nextZ;
  41244. if (!q)
  41245. break;
  41246. }
  41247. qSize = inSize;
  41248. while (pSize > 0 || (qSize > 0 && q)) {
  41249. if (pSize === 0) {
  41250. e = q;
  41251. q = q.nextZ;
  41252. qSize--;
  41253. }
  41254. else if (qSize === 0 || !q) {
  41255. e = p;
  41256. p = p.nextZ;
  41257. pSize--;
  41258. }
  41259. else if (p.z <= q.z) {
  41260. e = p;
  41261. p = p.nextZ;
  41262. pSize--;
  41263. }
  41264. else {
  41265. e = q;
  41266. q = q.nextZ;
  41267. qSize--;
  41268. }
  41269. if (tail)
  41270. tail.nextZ = e;
  41271. else
  41272. list = e;
  41273. e.prevZ = tail;
  41274. tail = e;
  41275. }
  41276. p = q;
  41277. }
  41278. tail.nextZ = null;
  41279. inSize *= 2;
  41280. } while (numMerges > 1);
  41281. return list;
  41282. }
  41283. // z-order of a point given coords and size of the data bounding box
  41284. function zOrder(x, y, minX, minY, size) {
  41285. // coords are transformed into non-negative 15-bit integer range
  41286. x = 32767 * (x - minX) / size;
  41287. y = 32767 * (y - minY) / size;
  41288. x = (x | (x << 8)) & 0x00FF00FF;
  41289. x = (x | (x << 4)) & 0x0F0F0F0F;
  41290. x = (x | (x << 2)) & 0x33333333;
  41291. x = (x | (x << 1)) & 0x55555555;
  41292. y = (y | (y << 8)) & 0x00FF00FF;
  41293. y = (y | (y << 4)) & 0x0F0F0F0F;
  41294. y = (y | (y << 2)) & 0x33333333;
  41295. y = (y | (y << 1)) & 0x55555555;
  41296. return x | (y << 1);
  41297. }
  41298. // find the leftmost node of a polygon ring
  41299. function getLeftmost(start) {
  41300. var p = start, leftmost = start;
  41301. do {
  41302. if (p.x < leftmost.x)
  41303. leftmost = p;
  41304. p = p.next;
  41305. } while (p !== start);
  41306. return leftmost;
  41307. }
  41308. // check if a point lies within a convex triangle
  41309. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  41310. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  41311. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  41312. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  41313. }
  41314. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  41315. function isValidDiagonal(a, b) {
  41316. return a.next.i !== b.i &&
  41317. a.prev.i !== b.i &&
  41318. !intersectsPolygon(a, b) &&
  41319. locallyInside(a, b) &&
  41320. locallyInside(b, a) &&
  41321. middleInside(a, b);
  41322. }
  41323. // signed area of a triangle
  41324. function area(p, q, r) {
  41325. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  41326. }
  41327. // check if two points are equal
  41328. function equals(p1, p2) {
  41329. return p1.x === p2.x && p1.y === p2.y;
  41330. }
  41331. // check if two segments intersect
  41332. function intersects(p1, q1, p2, q2) {
  41333. if ((equals(p1, q1) && equals(p2, q2)) ||
  41334. (equals(p1, q2) && equals(p2, q1)))
  41335. return true;
  41336. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  41337. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  41338. }
  41339. // check if a polygon diagonal intersects any polygon segments
  41340. function intersectsPolygon(a, b) {
  41341. var p = a;
  41342. do {
  41343. if (p.i !== a.i &&
  41344. p.next.i !== a.i &&
  41345. p.i !== b.i &&
  41346. p.next.i !== b.i &&
  41347. intersects(p, p.next, a, b))
  41348. return true;
  41349. p = p.next;
  41350. } while (p !== a);
  41351. return false;
  41352. }
  41353. // check if a polygon diagonal is locally inside the polygon
  41354. function locallyInside(a, b) {
  41355. return area(a.prev, a, a.next) < 0
  41356. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  41357. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  41358. }
  41359. // check if the middle point of a polygon diagonal is inside the polygon
  41360. function middleInside(a, b) {
  41361. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  41362. do {
  41363. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  41364. inside = !inside;
  41365. p = p.next;
  41366. } while (p !== a);
  41367. return inside;
  41368. }
  41369. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  41370. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  41371. function splitPolygon(a, b) {
  41372. 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;
  41373. a.next = b;
  41374. b.prev = a;
  41375. a2.next = an;
  41376. an.prev = a2;
  41377. b2.next = a2;
  41378. a2.prev = b2;
  41379. bp.next = b2;
  41380. b2.prev = bp;
  41381. return b2;
  41382. }
  41383. // create a node and optionally link it with previous one (in a circular doubly linked list)
  41384. function insertNode(i, x, y, last) {
  41385. var p = new Node(i, x, y);
  41386. if (!last) {
  41387. p.prev = p;
  41388. p.next = p;
  41389. }
  41390. else {
  41391. p.next = last.next;
  41392. p.prev = last;
  41393. last.next.prev = p;
  41394. last.next = p;
  41395. }
  41396. return p;
  41397. }
  41398. function removeNode(p) {
  41399. p.next.prev = p.prev;
  41400. p.prev.next = p.next;
  41401. if (p.prevZ)
  41402. p.prevZ.nextZ = p.nextZ;
  41403. if (p.nextZ)
  41404. p.nextZ.prevZ = p.prevZ;
  41405. }
  41406. function Node(i, x, y) {
  41407. // vertice index in coordinates array
  41408. this.i = i;
  41409. // vertex coordinates
  41410. this.x = x;
  41411. this.y = y;
  41412. // previous and next vertice nodes in a polygon ring
  41413. this.prev = null;
  41414. this.next = null;
  41415. // z-order curve value
  41416. this.z = null;
  41417. // previous and next nodes in z-order
  41418. this.prevZ = null;
  41419. this.nextZ = null;
  41420. // indicates whether this is a steiner point
  41421. this.steiner = false;
  41422. }
  41423. /**
  41424. * return a percentage difference between the polygon area and its triangulation area;
  41425. * used to verify correctness of triangulation
  41426. */
  41427. function deviation(data, holeIndices, dim, triangles) {
  41428. var hasHoles = holeIndices && holeIndices.length;
  41429. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  41430. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  41431. if (hasHoles) {
  41432. for (var i = 0, len = holeIndices.length; i < len; i++) {
  41433. var start = holeIndices[i] * dim;
  41434. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  41435. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  41436. }
  41437. }
  41438. var trianglesArea = 0;
  41439. for (i = 0; i < triangles.length; i += 3) {
  41440. var a = triangles[i] * dim;
  41441. var b = triangles[i + 1] * dim;
  41442. var c = triangles[i + 2] * dim;
  41443. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  41444. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  41445. }
  41446. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  41447. }
  41448. Earcut.deviation = deviation;
  41449. ;
  41450. function signedArea(data, start, end, dim) {
  41451. var sum = 0;
  41452. for (var i = start, j = end - dim; i < end; i += dim) {
  41453. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  41454. j = i;
  41455. }
  41456. return sum;
  41457. }
  41458. /**
  41459. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  41460. */
  41461. function flatten(data) {
  41462. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  41463. for (var i = 0; i < data.length; i++) {
  41464. for (var j = 0; j < data[i].length; j++) {
  41465. for (var d = 0; d < dim; d++)
  41466. result.vertices.push(data[i][j][d]);
  41467. }
  41468. if (i > 0) {
  41469. holeIndex += data[i - 1].length;
  41470. result.holes.push(holeIndex);
  41471. }
  41472. }
  41473. return result;
  41474. }
  41475. Earcut.flatten = flatten;
  41476. ;
  41477. })(Earcut || (Earcut = {}));
  41478. var BABYLON;
  41479. (function (BABYLON) {
  41480. // Unique ID when we import meshes from Babylon to CSG
  41481. var currentCSGMeshId = 0;
  41482. // # class Vertex
  41483. // Represents a vertex of a polygon. Use your own vertex class instead of this
  41484. // one to provide additional features like texture coordinates and vertex
  41485. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  41486. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  41487. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  41488. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  41489. // is not used anywhere else.
  41490. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  41491. var Vertex = (function () {
  41492. function Vertex(pos, normal, uv) {
  41493. this.pos = pos;
  41494. this.normal = normal;
  41495. this.uv = uv;
  41496. }
  41497. Vertex.prototype.clone = function () {
  41498. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  41499. };
  41500. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  41501. // orientation of a polygon is flipped.
  41502. Vertex.prototype.flip = function () {
  41503. this.normal = this.normal.scale(-1);
  41504. };
  41505. // Create a new vertex between this vertex and `other` by linearly
  41506. // interpolating all properties using a parameter of `t`. Subclasses should
  41507. // override this to interpolate additional properties.
  41508. Vertex.prototype.interpolate = function (other, t) {
  41509. 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));
  41510. };
  41511. return Vertex;
  41512. }());
  41513. // # class Plane
  41514. // Represents a plane in 3D space.
  41515. var Plane = (function () {
  41516. function Plane(normal, w) {
  41517. this.normal = normal;
  41518. this.w = w;
  41519. }
  41520. Plane.FromPoints = function (a, b, c) {
  41521. var v0 = c.subtract(a);
  41522. var v1 = b.subtract(a);
  41523. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  41524. return null;
  41525. }
  41526. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  41527. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  41528. };
  41529. Plane.prototype.clone = function () {
  41530. return new Plane(this.normal.clone(), this.w);
  41531. };
  41532. Plane.prototype.flip = function () {
  41533. this.normal.scaleInPlace(-1);
  41534. this.w = -this.w;
  41535. };
  41536. // Split `polygon` by this plane if needed, then put the polygon or polygon
  41537. // fragments in the appropriate lists. Coplanar polygons go into either
  41538. // `coplanarFront` or `coplanarBack` depending on their orientation with
  41539. // respect to this plane. Polygons in front or in back of this plane go into
  41540. // either `front` or `back`.
  41541. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  41542. var COPLANAR = 0;
  41543. var FRONT = 1;
  41544. var BACK = 2;
  41545. var SPANNING = 3;
  41546. // Classify each point as well as the entire polygon into one of the above
  41547. // four classes.
  41548. var polygonType = 0;
  41549. var types = [];
  41550. var i;
  41551. var t;
  41552. for (i = 0; i < polygon.vertices.length; i++) {
  41553. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  41554. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  41555. polygonType |= type;
  41556. types.push(type);
  41557. }
  41558. // Put the polygon in the correct list, splitting it when necessary.
  41559. switch (polygonType) {
  41560. case COPLANAR:
  41561. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  41562. break;
  41563. case FRONT:
  41564. front.push(polygon);
  41565. break;
  41566. case BACK:
  41567. back.push(polygon);
  41568. break;
  41569. case SPANNING:
  41570. var f = [], b = [];
  41571. for (i = 0; i < polygon.vertices.length; i++) {
  41572. var j = (i + 1) % polygon.vertices.length;
  41573. var ti = types[i], tj = types[j];
  41574. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  41575. if (ti !== BACK)
  41576. f.push(vi);
  41577. if (ti !== FRONT)
  41578. b.push(ti !== BACK ? vi.clone() : vi);
  41579. if ((ti | tj) === SPANNING) {
  41580. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  41581. var v = vi.interpolate(vj, t);
  41582. f.push(v);
  41583. b.push(v.clone());
  41584. }
  41585. }
  41586. var poly;
  41587. if (f.length >= 3) {
  41588. poly = new Polygon(f, polygon.shared);
  41589. if (poly.plane)
  41590. front.push(poly);
  41591. }
  41592. if (b.length >= 3) {
  41593. poly = new Polygon(b, polygon.shared);
  41594. if (poly.plane)
  41595. back.push(poly);
  41596. }
  41597. break;
  41598. }
  41599. };
  41600. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  41601. // point is on the plane.
  41602. Plane.EPSILON = 1e-5;
  41603. return Plane;
  41604. }());
  41605. // # class Polygon
  41606. // Represents a convex polygon. The vertices used to initialize a polygon must
  41607. // be coplanar and form a convex loop.
  41608. //
  41609. // Each convex polygon has a `shared` property, which is shared between all
  41610. // polygons that are clones of each other or were split from the same polygon.
  41611. // This can be used to define per-polygon properties (such as surface color).
  41612. var Polygon = (function () {
  41613. function Polygon(vertices, shared) {
  41614. this.vertices = vertices;
  41615. this.shared = shared;
  41616. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  41617. }
  41618. Polygon.prototype.clone = function () {
  41619. var vertices = this.vertices.map(function (v) { return v.clone(); });
  41620. return new Polygon(vertices, this.shared);
  41621. };
  41622. Polygon.prototype.flip = function () {
  41623. this.vertices.reverse().map(function (v) { v.flip(); });
  41624. this.plane.flip();
  41625. };
  41626. return Polygon;
  41627. }());
  41628. // # class Node
  41629. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  41630. // by picking a polygon to split along. That polygon (and all other coplanar
  41631. // polygons) are added directly to that node and the other polygons are added to
  41632. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  41633. // no distinction between internal and leaf nodes.
  41634. var Node = (function () {
  41635. function Node(polygons) {
  41636. this.plane = null;
  41637. this.front = null;
  41638. this.back = null;
  41639. this.polygons = [];
  41640. if (polygons) {
  41641. this.build(polygons);
  41642. }
  41643. }
  41644. Node.prototype.clone = function () {
  41645. var node = new Node();
  41646. node.plane = this.plane && this.plane.clone();
  41647. node.front = this.front && this.front.clone();
  41648. node.back = this.back && this.back.clone();
  41649. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  41650. return node;
  41651. };
  41652. // Convert solid space to empty space and empty space to solid space.
  41653. Node.prototype.invert = function () {
  41654. for (var i = 0; i < this.polygons.length; i++) {
  41655. this.polygons[i].flip();
  41656. }
  41657. if (this.plane) {
  41658. this.plane.flip();
  41659. }
  41660. if (this.front) {
  41661. this.front.invert();
  41662. }
  41663. if (this.back) {
  41664. this.back.invert();
  41665. }
  41666. var temp = this.front;
  41667. this.front = this.back;
  41668. this.back = temp;
  41669. };
  41670. // Recursively remove all polygons in `polygons` that are inside this BSP
  41671. // tree.
  41672. Node.prototype.clipPolygons = function (polygons) {
  41673. if (!this.plane)
  41674. return polygons.slice();
  41675. var front = [], back = [];
  41676. for (var i = 0; i < polygons.length; i++) {
  41677. this.plane.splitPolygon(polygons[i], front, back, front, back);
  41678. }
  41679. if (this.front) {
  41680. front = this.front.clipPolygons(front);
  41681. }
  41682. if (this.back) {
  41683. back = this.back.clipPolygons(back);
  41684. }
  41685. else {
  41686. back = [];
  41687. }
  41688. return front.concat(back);
  41689. };
  41690. // Remove all polygons in this BSP tree that are inside the other BSP tree
  41691. // `bsp`.
  41692. Node.prototype.clipTo = function (bsp) {
  41693. this.polygons = bsp.clipPolygons(this.polygons);
  41694. if (this.front)
  41695. this.front.clipTo(bsp);
  41696. if (this.back)
  41697. this.back.clipTo(bsp);
  41698. };
  41699. // Return a list of all polygons in this BSP tree.
  41700. Node.prototype.allPolygons = function () {
  41701. var polygons = this.polygons.slice();
  41702. if (this.front)
  41703. polygons = polygons.concat(this.front.allPolygons());
  41704. if (this.back)
  41705. polygons = polygons.concat(this.back.allPolygons());
  41706. return polygons;
  41707. };
  41708. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  41709. // new polygons are filtered down to the bottom of the tree and become new
  41710. // nodes there. Each set of polygons is partitioned using the first polygon
  41711. // (no heuristic is used to pick a good split).
  41712. Node.prototype.build = function (polygons) {
  41713. if (!polygons.length)
  41714. return;
  41715. if (!this.plane)
  41716. this.plane = polygons[0].plane.clone();
  41717. var front = [], back = [];
  41718. for (var i = 0; i < polygons.length; i++) {
  41719. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  41720. }
  41721. if (front.length) {
  41722. if (!this.front)
  41723. this.front = new Node();
  41724. this.front.build(front);
  41725. }
  41726. if (back.length) {
  41727. if (!this.back)
  41728. this.back = new Node();
  41729. this.back.build(back);
  41730. }
  41731. };
  41732. return Node;
  41733. }());
  41734. var CSG = (function () {
  41735. function CSG() {
  41736. this.polygons = new Array();
  41737. }
  41738. // Convert BABYLON.Mesh to BABYLON.CSG
  41739. CSG.FromMesh = function (mesh) {
  41740. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  41741. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  41742. if (mesh instanceof BABYLON.Mesh) {
  41743. mesh.computeWorldMatrix(true);
  41744. matrix = mesh.getWorldMatrix();
  41745. meshPosition = mesh.position.clone();
  41746. meshRotation = mesh.rotation.clone();
  41747. if (mesh.rotationQuaternion) {
  41748. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  41749. }
  41750. meshScaling = mesh.scaling.clone();
  41751. }
  41752. else {
  41753. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  41754. }
  41755. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41756. var subMeshes = mesh.subMeshes;
  41757. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  41758. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  41759. vertices = [];
  41760. for (var j = 0; j < 3; j++) {
  41761. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  41762. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  41763. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  41764. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  41765. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  41766. vertex = new Vertex(position, normal, uv);
  41767. vertices.push(vertex);
  41768. }
  41769. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  41770. // To handle the case of degenerated triangle
  41771. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  41772. if (polygon.plane)
  41773. polygons.push(polygon);
  41774. }
  41775. }
  41776. var csg = CSG.FromPolygons(polygons);
  41777. csg.matrix = matrix;
  41778. csg.position = meshPosition;
  41779. csg.rotation = meshRotation;
  41780. csg.scaling = meshScaling;
  41781. csg.rotationQuaternion = meshRotationQuaternion;
  41782. currentCSGMeshId++;
  41783. return csg;
  41784. };
  41785. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  41786. CSG.FromPolygons = function (polygons) {
  41787. var csg = new CSG();
  41788. csg.polygons = polygons;
  41789. return csg;
  41790. };
  41791. CSG.prototype.clone = function () {
  41792. var csg = new CSG();
  41793. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  41794. csg.copyTransformAttributes(this);
  41795. return csg;
  41796. };
  41797. CSG.prototype.toPolygons = function () {
  41798. return this.polygons;
  41799. };
  41800. CSG.prototype.union = function (csg) {
  41801. var a = new Node(this.clone().polygons);
  41802. var b = new Node(csg.clone().polygons);
  41803. a.clipTo(b);
  41804. b.clipTo(a);
  41805. b.invert();
  41806. b.clipTo(a);
  41807. b.invert();
  41808. a.build(b.allPolygons());
  41809. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  41810. };
  41811. CSG.prototype.unionInPlace = function (csg) {
  41812. var a = new Node(this.polygons);
  41813. var b = new Node(csg.polygons);
  41814. a.clipTo(b);
  41815. b.clipTo(a);
  41816. b.invert();
  41817. b.clipTo(a);
  41818. b.invert();
  41819. a.build(b.allPolygons());
  41820. this.polygons = a.allPolygons();
  41821. };
  41822. CSG.prototype.subtract = function (csg) {
  41823. var a = new Node(this.clone().polygons);
  41824. var b = new Node(csg.clone().polygons);
  41825. a.invert();
  41826. a.clipTo(b);
  41827. b.clipTo(a);
  41828. b.invert();
  41829. b.clipTo(a);
  41830. b.invert();
  41831. a.build(b.allPolygons());
  41832. a.invert();
  41833. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  41834. };
  41835. CSG.prototype.subtractInPlace = function (csg) {
  41836. var a = new Node(this.polygons);
  41837. var b = new Node(csg.polygons);
  41838. a.invert();
  41839. a.clipTo(b);
  41840. b.clipTo(a);
  41841. b.invert();
  41842. b.clipTo(a);
  41843. b.invert();
  41844. a.build(b.allPolygons());
  41845. a.invert();
  41846. this.polygons = a.allPolygons();
  41847. };
  41848. CSG.prototype.intersect = function (csg) {
  41849. var a = new Node(this.clone().polygons);
  41850. var b = new Node(csg.clone().polygons);
  41851. a.invert();
  41852. b.clipTo(a);
  41853. b.invert();
  41854. a.clipTo(b);
  41855. b.clipTo(a);
  41856. a.build(b.allPolygons());
  41857. a.invert();
  41858. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  41859. };
  41860. CSG.prototype.intersectInPlace = function (csg) {
  41861. var a = new Node(this.polygons);
  41862. var b = new Node(csg.polygons);
  41863. a.invert();
  41864. b.clipTo(a);
  41865. b.invert();
  41866. a.clipTo(b);
  41867. b.clipTo(a);
  41868. a.build(b.allPolygons());
  41869. a.invert();
  41870. this.polygons = a.allPolygons();
  41871. };
  41872. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  41873. // not modified.
  41874. CSG.prototype.inverse = function () {
  41875. var csg = this.clone();
  41876. csg.inverseInPlace();
  41877. return csg;
  41878. };
  41879. CSG.prototype.inverseInPlace = function () {
  41880. this.polygons.map(function (p) { p.flip(); });
  41881. };
  41882. // This is used to keep meshes transformations so they can be restored
  41883. // when we build back a Babylon Mesh
  41884. // NB : All CSG operations are performed in world coordinates
  41885. CSG.prototype.copyTransformAttributes = function (csg) {
  41886. this.matrix = csg.matrix;
  41887. this.position = csg.position;
  41888. this.rotation = csg.rotation;
  41889. this.scaling = csg.scaling;
  41890. this.rotationQuaternion = csg.rotationQuaternion;
  41891. return this;
  41892. };
  41893. // Build Raw mesh from CSG
  41894. // Coordinates here are in world space
  41895. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  41896. var matrix = this.matrix.clone();
  41897. matrix.invert();
  41898. 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;
  41899. if (keepSubMeshes) {
  41900. // Sort Polygons, since subMeshes are indices range
  41901. polygons.sort(function (a, b) {
  41902. if (a.shared.meshId === b.shared.meshId) {
  41903. return a.shared.subMeshId - b.shared.subMeshId;
  41904. }
  41905. else {
  41906. return a.shared.meshId - b.shared.meshId;
  41907. }
  41908. });
  41909. }
  41910. for (var i = 0, il = polygons.length; i < il; i++) {
  41911. polygon = polygons[i];
  41912. // Building SubMeshes
  41913. if (!subMesh_dict[polygon.shared.meshId]) {
  41914. subMesh_dict[polygon.shared.meshId] = {};
  41915. }
  41916. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  41917. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  41918. indexStart: +Infinity,
  41919. indexEnd: -Infinity,
  41920. materialIndex: polygon.shared.materialIndex
  41921. };
  41922. }
  41923. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  41924. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  41925. polygonIndices[0] = 0;
  41926. polygonIndices[1] = j - 1;
  41927. polygonIndices[2] = j;
  41928. for (var k = 0; k < 3; k++) {
  41929. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  41930. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  41931. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  41932. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  41933. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  41934. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  41935. // Check if 2 points can be merged
  41936. if (!(typeof vertex_idx !== 'undefined' &&
  41937. normals[vertex_idx * 3] === localNormal.x &&
  41938. normals[vertex_idx * 3 + 1] === localNormal.y &&
  41939. normals[vertex_idx * 3 + 2] === localNormal.z &&
  41940. uvs[vertex_idx * 2] === uv.x &&
  41941. uvs[vertex_idx * 2 + 1] === uv.y)) {
  41942. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  41943. uvs.push(uv.x, uv.y);
  41944. normals.push(normal.x, normal.y, normal.z);
  41945. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  41946. }
  41947. indices.push(vertex_idx);
  41948. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  41949. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  41950. currentIndex++;
  41951. }
  41952. }
  41953. }
  41954. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  41955. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  41956. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  41957. mesh.setIndices(indices);
  41958. if (keepSubMeshes) {
  41959. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  41960. var materialIndexOffset = 0, materialMaxIndex;
  41961. mesh.subMeshes = new Array();
  41962. for (var m in subMesh_dict) {
  41963. materialMaxIndex = -1;
  41964. for (var sm in subMesh_dict[m]) {
  41965. subMesh_obj = subMesh_dict[m][sm];
  41966. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  41967. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  41968. }
  41969. materialIndexOffset += ++materialMaxIndex;
  41970. }
  41971. }
  41972. return mesh;
  41973. };
  41974. // Build Mesh from CSG taking material and transforms into account
  41975. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  41976. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  41977. mesh.material = material;
  41978. mesh.position.copyFrom(this.position);
  41979. mesh.rotation.copyFrom(this.rotation);
  41980. if (this.rotationQuaternion) {
  41981. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  41982. }
  41983. mesh.scaling.copyFrom(this.scaling);
  41984. mesh.computeWorldMatrix(true);
  41985. return mesh;
  41986. };
  41987. return CSG;
  41988. }());
  41989. BABYLON.CSG = CSG;
  41990. })(BABYLON || (BABYLON = {}));
  41991. var BABYLON;
  41992. (function (BABYLON) {
  41993. var VRDistortionCorrectionPostProcess = (function (_super) {
  41994. __extends(VRDistortionCorrectionPostProcess, _super);
  41995. //ANY
  41996. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  41997. var _this = this;
  41998. _super.call(this, name, "vrDistortionCorrection", [
  41999. 'LensCenter',
  42000. 'Scale',
  42001. 'ScaleIn',
  42002. 'HmdWarpParam'
  42003. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  42004. this._isRightEye = isRightEye;
  42005. this._distortionFactors = vrMetrics.distortionK;
  42006. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  42007. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  42008. this.onSizeChangedObservable.add(function () {
  42009. _this.aspectRatio = _this.width * .5 / _this.height;
  42010. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  42011. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  42012. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  42013. });
  42014. this.onApplyObservable.add(function (effect) {
  42015. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  42016. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  42017. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  42018. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  42019. });
  42020. }
  42021. return VRDistortionCorrectionPostProcess;
  42022. }(BABYLON.PostProcess));
  42023. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  42024. })(BABYLON || (BABYLON = {}));
  42025. // Mainly based on these 2 articles :
  42026. // 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
  42027. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  42028. var BABYLON;
  42029. (function (BABYLON) {
  42030. (function (JoystickAxis) {
  42031. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  42032. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  42033. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  42034. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  42035. var JoystickAxis = BABYLON.JoystickAxis;
  42036. var VirtualJoystick = (function () {
  42037. function VirtualJoystick(leftJoystick) {
  42038. var _this = this;
  42039. if (leftJoystick) {
  42040. this._leftJoystick = true;
  42041. }
  42042. else {
  42043. this._leftJoystick = false;
  42044. }
  42045. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  42046. VirtualJoystick._globalJoystickIndex++;
  42047. // By default left & right arrow keys are moving the X
  42048. // and up & down keys are moving the Y
  42049. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42050. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42051. this.reverseLeftRight = false;
  42052. this.reverseUpDown = false;
  42053. // collections of pointers
  42054. this._touches = new BABYLON.StringDictionary();
  42055. this.deltaPosition = BABYLON.Vector3.Zero();
  42056. this._joystickSensibility = 25;
  42057. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42058. this._rotationSpeed = 25;
  42059. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  42060. this._rotateOnAxisRelativeToMesh = false;
  42061. this._onResize = function (evt) {
  42062. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42063. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42064. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  42065. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  42066. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  42067. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  42068. };
  42069. // injecting a canvas element on top of the canvas 3D game
  42070. if (!VirtualJoystick.vjCanvas) {
  42071. window.addEventListener("resize", this._onResize, false);
  42072. VirtualJoystick.vjCanvas = document.createElement("canvas");
  42073. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42074. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42075. VirtualJoystick.vjCanvas.width = window.innerWidth;
  42076. VirtualJoystick.vjCanvas.height = window.innerHeight;
  42077. VirtualJoystick.vjCanvas.style.width = "100%";
  42078. VirtualJoystick.vjCanvas.style.height = "100%";
  42079. VirtualJoystick.vjCanvas.style.position = "absolute";
  42080. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  42081. VirtualJoystick.vjCanvas.style.top = "0px";
  42082. VirtualJoystick.vjCanvas.style.left = "0px";
  42083. VirtualJoystick.vjCanvas.style.zIndex = "5";
  42084. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  42085. // Support for jQuery PEP polyfill
  42086. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  42087. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  42088. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  42089. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42090. document.body.appendChild(VirtualJoystick.vjCanvas);
  42091. }
  42092. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  42093. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  42094. this.pressed = false;
  42095. // default joystick color
  42096. this._joystickColor = "cyan";
  42097. this._joystickPointerID = -1;
  42098. // current joystick position
  42099. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  42100. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  42101. // origin joystick position
  42102. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  42103. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  42104. this._onPointerDownHandlerRef = function (evt) {
  42105. _this._onPointerDown(evt);
  42106. };
  42107. this._onPointerMoveHandlerRef = function (evt) {
  42108. _this._onPointerMove(evt);
  42109. };
  42110. this._onPointerOutHandlerRef = function (evt) {
  42111. _this._onPointerUp(evt);
  42112. };
  42113. this._onPointerUpHandlerRef = function (evt) {
  42114. _this._onPointerUp(evt);
  42115. };
  42116. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  42117. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  42118. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  42119. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  42120. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  42121. evt.preventDefault(); // Disables system menu
  42122. }, false);
  42123. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42124. }
  42125. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  42126. this._joystickSensibility = newJoystickSensibility;
  42127. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42128. };
  42129. VirtualJoystick.prototype._onPointerDown = function (e) {
  42130. var positionOnScreenCondition;
  42131. e.preventDefault();
  42132. if (this._leftJoystick === true) {
  42133. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  42134. }
  42135. else {
  42136. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  42137. }
  42138. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  42139. // First contact will be dedicated to the virtual joystick
  42140. this._joystickPointerID = e.pointerId;
  42141. this._joystickPointerStartPos.x = e.clientX;
  42142. this._joystickPointerStartPos.y = e.clientY;
  42143. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  42144. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  42145. this._deltaJoystickVector.x = 0;
  42146. this._deltaJoystickVector.y = 0;
  42147. this.pressed = true;
  42148. this._touches.add(e.pointerId.toString(), e);
  42149. }
  42150. else {
  42151. // You can only trigger the action buttons with a joystick declared
  42152. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  42153. this._action();
  42154. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  42155. }
  42156. }
  42157. };
  42158. VirtualJoystick.prototype._onPointerMove = function (e) {
  42159. // If the current pointer is the one associated to the joystick (first touch contact)
  42160. if (this._joystickPointerID == e.pointerId) {
  42161. this._joystickPointerPos.x = e.clientX;
  42162. this._joystickPointerPos.y = e.clientY;
  42163. this._deltaJoystickVector = this._joystickPointerPos.clone();
  42164. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  42165. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  42166. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  42167. switch (this._axisTargetedByLeftAndRight) {
  42168. case JoystickAxis.X:
  42169. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  42170. break;
  42171. case JoystickAxis.Y:
  42172. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  42173. break;
  42174. case JoystickAxis.Z:
  42175. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  42176. break;
  42177. }
  42178. var directionUpDown = this.reverseUpDown ? 1 : -1;
  42179. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  42180. switch (this._axisTargetedByUpAndDown) {
  42181. case JoystickAxis.X:
  42182. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  42183. break;
  42184. case JoystickAxis.Y:
  42185. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  42186. break;
  42187. case JoystickAxis.Z:
  42188. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  42189. break;
  42190. }
  42191. }
  42192. else {
  42193. var data = this._touches.get(e.pointerId.toString());
  42194. if (data) {
  42195. data.x = e.clientX;
  42196. data.y = e.clientY;
  42197. }
  42198. }
  42199. };
  42200. VirtualJoystick.prototype._onPointerUp = function (e) {
  42201. if (this._joystickPointerID == e.pointerId) {
  42202. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  42203. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  42204. this._joystickPointerID = -1;
  42205. this.pressed = false;
  42206. }
  42207. else {
  42208. var touch = this._touches.get(e.pointerId.toString());
  42209. if (touch) {
  42210. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  42211. }
  42212. }
  42213. this._deltaJoystickVector.x = 0;
  42214. this._deltaJoystickVector.y = 0;
  42215. this._touches.remove(e.pointerId.toString());
  42216. };
  42217. /**
  42218. * Change the color of the virtual joystick
  42219. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  42220. */
  42221. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  42222. this._joystickColor = newColor;
  42223. };
  42224. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  42225. this._action = action;
  42226. };
  42227. // Define which axis you'd like to control for left & right
  42228. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  42229. switch (axis) {
  42230. case JoystickAxis.X:
  42231. case JoystickAxis.Y:
  42232. case JoystickAxis.Z:
  42233. this._axisTargetedByLeftAndRight = axis;
  42234. break;
  42235. default:
  42236. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42237. break;
  42238. }
  42239. };
  42240. // Define which axis you'd like to control for up & down
  42241. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  42242. switch (axis) {
  42243. case JoystickAxis.X:
  42244. case JoystickAxis.Y:
  42245. case JoystickAxis.Z:
  42246. this._axisTargetedByUpAndDown = axis;
  42247. break;
  42248. default:
  42249. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42250. break;
  42251. }
  42252. };
  42253. VirtualJoystick.prototype._clearCanvas = function () {
  42254. if (this._leftJoystick) {
  42255. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  42256. }
  42257. else {
  42258. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  42259. }
  42260. };
  42261. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  42262. var _this = this;
  42263. if (this.pressed) {
  42264. this._touches.forEach(function (touch) {
  42265. if (touch.pointerId === _this._joystickPointerID) {
  42266. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  42267. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  42268. VirtualJoystick.vjCanvasContext.beginPath();
  42269. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  42270. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42271. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  42272. VirtualJoystick.vjCanvasContext.stroke();
  42273. VirtualJoystick.vjCanvasContext.closePath();
  42274. VirtualJoystick.vjCanvasContext.beginPath();
  42275. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42276. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42277. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  42278. VirtualJoystick.vjCanvasContext.stroke();
  42279. VirtualJoystick.vjCanvasContext.closePath();
  42280. VirtualJoystick.vjCanvasContext.beginPath();
  42281. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42282. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  42283. VirtualJoystick.vjCanvasContext.stroke();
  42284. VirtualJoystick.vjCanvasContext.closePath();
  42285. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  42286. }
  42287. else {
  42288. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  42289. VirtualJoystick.vjCanvasContext.beginPath();
  42290. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  42291. VirtualJoystick.vjCanvasContext.beginPath();
  42292. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  42293. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  42294. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  42295. VirtualJoystick.vjCanvasContext.stroke();
  42296. VirtualJoystick.vjCanvasContext.closePath();
  42297. touch.prevX = touch.x;
  42298. touch.prevY = touch.y;
  42299. }
  42300. ;
  42301. });
  42302. }
  42303. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42304. };
  42305. VirtualJoystick.prototype.releaseCanvas = function () {
  42306. if (VirtualJoystick.vjCanvas) {
  42307. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  42308. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  42309. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  42310. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  42311. window.removeEventListener("resize", this._onResize);
  42312. document.body.removeChild(VirtualJoystick.vjCanvas);
  42313. VirtualJoystick.vjCanvas = null;
  42314. }
  42315. };
  42316. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  42317. VirtualJoystick._globalJoystickIndex = 0;
  42318. return VirtualJoystick;
  42319. }());
  42320. BABYLON.VirtualJoystick = VirtualJoystick;
  42321. })(BABYLON || (BABYLON = {}));
  42322. var BABYLON;
  42323. (function (BABYLON) {
  42324. // We're mainly based on the logic defined into the FreeCamera code
  42325. var VirtualJoysticksCamera = (function (_super) {
  42326. __extends(VirtualJoysticksCamera, _super);
  42327. function VirtualJoysticksCamera(name, position, scene) {
  42328. _super.call(this, name, position, scene);
  42329. this.inputs.addVirtualJoystick();
  42330. }
  42331. return VirtualJoysticksCamera;
  42332. }(BABYLON.FreeCamera));
  42333. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  42334. })(BABYLON || (BABYLON = {}));
  42335. var BABYLON;
  42336. (function (BABYLON) {
  42337. var FreeCameraVirtualJoystickInput = (function () {
  42338. function FreeCameraVirtualJoystickInput() {
  42339. }
  42340. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  42341. return this._leftjoystick;
  42342. };
  42343. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  42344. return this._rightjoystick;
  42345. };
  42346. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  42347. if (this._leftjoystick) {
  42348. var camera = this.camera;
  42349. var speed = camera._computeLocalCameraSpeed() * 50;
  42350. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  42351. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  42352. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  42353. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  42354. if (!this._leftjoystick.pressed) {
  42355. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  42356. }
  42357. if (!this._rightjoystick.pressed) {
  42358. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  42359. }
  42360. }
  42361. };
  42362. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  42363. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  42364. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  42365. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  42366. this._leftjoystick.setJoystickSensibility(0.15);
  42367. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  42368. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  42369. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  42370. this._rightjoystick.reverseUpDown = true;
  42371. this._rightjoystick.setJoystickSensibility(0.05);
  42372. this._rightjoystick.setJoystickColor("yellow");
  42373. };
  42374. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  42375. this._leftjoystick.releaseCanvas();
  42376. this._rightjoystick.releaseCanvas();
  42377. };
  42378. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  42379. return "FreeCameraVirtualJoystickInput";
  42380. };
  42381. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  42382. return "virtualJoystick";
  42383. };
  42384. return FreeCameraVirtualJoystickInput;
  42385. }());
  42386. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  42387. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  42388. })(BABYLON || (BABYLON = {}));
  42389. var BABYLON;
  42390. (function (BABYLON) {
  42391. var AnaglyphPostProcess = (function (_super) {
  42392. __extends(AnaglyphPostProcess, _super);
  42393. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  42394. var _this = this;
  42395. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  42396. this._passedProcess = rigCameras[0]._rigPostProcess;
  42397. this.onApplyObservable.add(function (effect) {
  42398. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  42399. });
  42400. }
  42401. return AnaglyphPostProcess;
  42402. }(BABYLON.PostProcess));
  42403. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  42404. })(BABYLON || (BABYLON = {}));
  42405. var BABYLON;
  42406. (function (BABYLON) {
  42407. var OutlineRenderer = (function () {
  42408. function OutlineRenderer(scene) {
  42409. this._scene = scene;
  42410. }
  42411. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  42412. var _this = this;
  42413. if (useOverlay === void 0) { useOverlay = false; }
  42414. var scene = this._scene;
  42415. var engine = this._scene.getEngine();
  42416. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  42417. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  42418. return;
  42419. }
  42420. var mesh = subMesh.getRenderingMesh();
  42421. var material = subMesh.getMaterial();
  42422. engine.enableEffect(this._effect);
  42423. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  42424. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  42425. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  42426. // Bones
  42427. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42428. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  42429. }
  42430. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  42431. // Alpha test
  42432. if (material && material.needAlphaTesting()) {
  42433. var alphaTexture = material.getAlphaTestTexture();
  42434. this._effect.setTexture("diffuseSampler", alphaTexture);
  42435. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  42436. }
  42437. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  42438. };
  42439. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  42440. var defines = [];
  42441. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  42442. var mesh = subMesh.getMesh();
  42443. var material = subMesh.getMaterial();
  42444. // Alpha test
  42445. if (material && material.needAlphaTesting()) {
  42446. defines.push("#define ALPHATEST");
  42447. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42448. attribs.push(BABYLON.VertexBuffer.UVKind);
  42449. defines.push("#define UV1");
  42450. }
  42451. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  42452. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42453. defines.push("#define UV2");
  42454. }
  42455. }
  42456. // Bones
  42457. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42458. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42459. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42460. if (mesh.numBoneInfluencers > 4) {
  42461. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42462. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42463. }
  42464. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42465. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42466. }
  42467. else {
  42468. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42469. }
  42470. // Instances
  42471. if (useInstances) {
  42472. defines.push("#define INSTANCES");
  42473. attribs.push("world0");
  42474. attribs.push("world1");
  42475. attribs.push("world2");
  42476. attribs.push("world3");
  42477. }
  42478. // Get correct effect
  42479. var join = defines.join("\n");
  42480. if (this._cachedDefines !== join) {
  42481. this._cachedDefines = join;
  42482. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  42483. }
  42484. return this._effect.isReady();
  42485. };
  42486. return OutlineRenderer;
  42487. }());
  42488. BABYLON.OutlineRenderer = OutlineRenderer;
  42489. })(BABYLON || (BABYLON = {}));
  42490. var BABYLON;
  42491. (function (BABYLON) {
  42492. var MeshAssetTask = (function () {
  42493. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  42494. this.name = name;
  42495. this.meshesNames = meshesNames;
  42496. this.rootUrl = rootUrl;
  42497. this.sceneFilename = sceneFilename;
  42498. this.isCompleted = false;
  42499. }
  42500. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42501. var _this = this;
  42502. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  42503. _this.loadedMeshes = meshes;
  42504. _this.loadedParticleSystems = particleSystems;
  42505. _this.loadedSkeletons = skeletons;
  42506. _this.isCompleted = true;
  42507. if (_this.onSuccess) {
  42508. _this.onSuccess(_this);
  42509. }
  42510. onSuccess();
  42511. }, null, function () {
  42512. if (_this.onError) {
  42513. _this.onError(_this);
  42514. }
  42515. onError();
  42516. });
  42517. };
  42518. return MeshAssetTask;
  42519. }());
  42520. BABYLON.MeshAssetTask = MeshAssetTask;
  42521. var TextFileAssetTask = (function () {
  42522. function TextFileAssetTask(name, url) {
  42523. this.name = name;
  42524. this.url = url;
  42525. this.isCompleted = false;
  42526. }
  42527. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42528. var _this = this;
  42529. BABYLON.Tools.LoadFile(this.url, function (data) {
  42530. _this.text = data;
  42531. _this.isCompleted = true;
  42532. if (_this.onSuccess) {
  42533. _this.onSuccess(_this);
  42534. }
  42535. onSuccess();
  42536. }, null, scene.database, false, function () {
  42537. if (_this.onError) {
  42538. _this.onError(_this);
  42539. }
  42540. onError();
  42541. });
  42542. };
  42543. return TextFileAssetTask;
  42544. }());
  42545. BABYLON.TextFileAssetTask = TextFileAssetTask;
  42546. var BinaryFileAssetTask = (function () {
  42547. function BinaryFileAssetTask(name, url) {
  42548. this.name = name;
  42549. this.url = url;
  42550. this.isCompleted = false;
  42551. }
  42552. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42553. var _this = this;
  42554. BABYLON.Tools.LoadFile(this.url, function (data) {
  42555. _this.data = data;
  42556. _this.isCompleted = true;
  42557. if (_this.onSuccess) {
  42558. _this.onSuccess(_this);
  42559. }
  42560. onSuccess();
  42561. }, null, scene.database, true, function () {
  42562. if (_this.onError) {
  42563. _this.onError(_this);
  42564. }
  42565. onError();
  42566. });
  42567. };
  42568. return BinaryFileAssetTask;
  42569. }());
  42570. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  42571. var ImageAssetTask = (function () {
  42572. function ImageAssetTask(name, url) {
  42573. this.name = name;
  42574. this.url = url;
  42575. this.isCompleted = false;
  42576. }
  42577. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42578. var _this = this;
  42579. var img = new Image();
  42580. BABYLON.Tools.SetCorsBehavior(this.url, img);
  42581. img.onload = function () {
  42582. _this.image = img;
  42583. _this.isCompleted = true;
  42584. if (_this.onSuccess) {
  42585. _this.onSuccess(_this);
  42586. }
  42587. onSuccess();
  42588. };
  42589. img.onerror = function () {
  42590. if (_this.onError) {
  42591. _this.onError(_this);
  42592. }
  42593. onError();
  42594. };
  42595. img.src = this.url;
  42596. };
  42597. return ImageAssetTask;
  42598. }());
  42599. BABYLON.ImageAssetTask = ImageAssetTask;
  42600. var TextureAssetTask = (function () {
  42601. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  42602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42603. this.name = name;
  42604. this.url = url;
  42605. this.noMipmap = noMipmap;
  42606. this.invertY = invertY;
  42607. this.samplingMode = samplingMode;
  42608. this.isCompleted = false;
  42609. }
  42610. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42611. var _this = this;
  42612. var onload = function () {
  42613. _this.isCompleted = true;
  42614. if (_this.onSuccess) {
  42615. _this.onSuccess(_this);
  42616. }
  42617. onSuccess();
  42618. };
  42619. var onerror = function () {
  42620. if (_this.onError) {
  42621. _this.onError(_this);
  42622. }
  42623. onError();
  42624. };
  42625. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  42626. };
  42627. return TextureAssetTask;
  42628. }());
  42629. BABYLON.TextureAssetTask = TextureAssetTask;
  42630. var CubeTextureAssetTask = (function () {
  42631. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  42632. this.name = name;
  42633. this.url = url;
  42634. this.extensions = extensions;
  42635. this.noMipmap = noMipmap;
  42636. this.files = files;
  42637. this.isCompleted = false;
  42638. }
  42639. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42640. var _this = this;
  42641. var onload = function () {
  42642. _this.isCompleted = true;
  42643. if (_this.onSuccess) {
  42644. _this.onSuccess(_this);
  42645. }
  42646. onSuccess();
  42647. };
  42648. var onerror = function () {
  42649. if (_this.onError) {
  42650. _this.onError(_this);
  42651. }
  42652. onError();
  42653. };
  42654. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  42655. };
  42656. return CubeTextureAssetTask;
  42657. }());
  42658. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  42659. var AssetsManager = (function () {
  42660. function AssetsManager(scene) {
  42661. this.tasks = new Array();
  42662. this.waitingTasksCount = 0;
  42663. this.useDefaultLoadingScreen = true;
  42664. this._scene = scene;
  42665. }
  42666. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  42667. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  42668. this.tasks.push(task);
  42669. return task;
  42670. };
  42671. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  42672. var task = new TextFileAssetTask(taskName, url);
  42673. this.tasks.push(task);
  42674. return task;
  42675. };
  42676. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  42677. var task = new BinaryFileAssetTask(taskName, url);
  42678. this.tasks.push(task);
  42679. return task;
  42680. };
  42681. AssetsManager.prototype.addImageTask = function (taskName, url) {
  42682. var task = new ImageAssetTask(taskName, url);
  42683. this.tasks.push(task);
  42684. return task;
  42685. };
  42686. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  42687. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42688. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  42689. this.tasks.push(task);
  42690. return task;
  42691. };
  42692. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  42693. this.waitingTasksCount--;
  42694. if (this.waitingTasksCount === 0) {
  42695. if (this.onFinish) {
  42696. this.onFinish(this.tasks);
  42697. }
  42698. this._scene.getEngine().hideLoadingUI();
  42699. }
  42700. };
  42701. AssetsManager.prototype._runTask = function (task) {
  42702. var _this = this;
  42703. task.run(this._scene, function () {
  42704. if (_this.onTaskSuccess) {
  42705. _this.onTaskSuccess(task);
  42706. }
  42707. _this._decreaseWaitingTasksCount();
  42708. }, function () {
  42709. if (_this.onTaskError) {
  42710. _this.onTaskError(task);
  42711. }
  42712. _this._decreaseWaitingTasksCount();
  42713. });
  42714. };
  42715. AssetsManager.prototype.reset = function () {
  42716. this.tasks = new Array();
  42717. return this;
  42718. };
  42719. AssetsManager.prototype.load = function () {
  42720. this.waitingTasksCount = this.tasks.length;
  42721. if (this.waitingTasksCount === 0) {
  42722. if (this.onFinish) {
  42723. this.onFinish(this.tasks);
  42724. }
  42725. return this;
  42726. }
  42727. if (this.useDefaultLoadingScreen) {
  42728. this._scene.getEngine().displayLoadingUI();
  42729. }
  42730. for (var index = 0; index < this.tasks.length; index++) {
  42731. var task = this.tasks[index];
  42732. this._runTask(task);
  42733. }
  42734. return this;
  42735. };
  42736. return AssetsManager;
  42737. }());
  42738. BABYLON.AssetsManager = AssetsManager;
  42739. })(BABYLON || (BABYLON = {}));
  42740. var BABYLON;
  42741. (function (BABYLON) {
  42742. var VRCameraMetrics = (function () {
  42743. function VRCameraMetrics() {
  42744. this.compensateDistortion = true;
  42745. }
  42746. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  42747. get: function () {
  42748. return this.hResolution / (2 * this.vResolution);
  42749. },
  42750. enumerable: true,
  42751. configurable: true
  42752. });
  42753. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  42754. get: function () {
  42755. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  42756. },
  42757. enumerable: true,
  42758. configurable: true
  42759. });
  42760. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  42761. get: function () {
  42762. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  42763. var h = (4 * meters) / this.hScreenSize;
  42764. return BABYLON.Matrix.Translation(h, 0, 0);
  42765. },
  42766. enumerable: true,
  42767. configurable: true
  42768. });
  42769. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  42770. get: function () {
  42771. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  42772. var h = (4 * meters) / this.hScreenSize;
  42773. return BABYLON.Matrix.Translation(-h, 0, 0);
  42774. },
  42775. enumerable: true,
  42776. configurable: true
  42777. });
  42778. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  42779. get: function () {
  42780. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  42781. },
  42782. enumerable: true,
  42783. configurable: true
  42784. });
  42785. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  42786. get: function () {
  42787. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  42788. },
  42789. enumerable: true,
  42790. configurable: true
  42791. });
  42792. VRCameraMetrics.GetDefault = function () {
  42793. var result = new VRCameraMetrics();
  42794. result.hResolution = 1280;
  42795. result.vResolution = 800;
  42796. result.hScreenSize = 0.149759993;
  42797. result.vScreenSize = 0.0935999975;
  42798. result.vScreenCenter = 0.0467999987,
  42799. result.eyeToScreenDistance = 0.0410000011;
  42800. result.lensSeparationDistance = 0.0635000020;
  42801. result.interpupillaryDistance = 0.0640000030;
  42802. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  42803. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  42804. result.postProcessScaleFactor = 1.714605507808412;
  42805. result.lensCenterOffset = 0.151976421;
  42806. return result;
  42807. };
  42808. return VRCameraMetrics;
  42809. }());
  42810. BABYLON.VRCameraMetrics = VRCameraMetrics;
  42811. })(BABYLON || (BABYLON = {}));
  42812. var BABYLON;
  42813. (function (BABYLON) {
  42814. var WebVRFreeCamera = (function (_super) {
  42815. __extends(WebVRFreeCamera, _super);
  42816. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  42817. var _this = this;
  42818. if (compensateDistortion === void 0) { compensateDistortion = false; }
  42819. if (webVROptions === void 0) { webVROptions = {}; }
  42820. _super.call(this, name, position, scene);
  42821. this.webVROptions = webVROptions;
  42822. this._vrDevice = null;
  42823. this._cacheState = null;
  42824. this._vrEnabled = false;
  42825. //enable VR
  42826. this.getEngine().initWebVR();
  42827. if (!this.getEngine().vrDisplaysPromise) {
  42828. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  42829. }
  42830. else {
  42831. //TODO get the metrics updated using the device's eye parameters!
  42832. //TODO also check that the device has the right capabilities!
  42833. this.getEngine().vrDisplaysPromise.then(function (devices) {
  42834. if (devices.length > 0) {
  42835. _this._vrEnabled = true;
  42836. if (_this.webVROptions.displayName) {
  42837. var found = devices.some(function (device) {
  42838. if (device.displayName === _this.webVROptions.displayName) {
  42839. _this._vrDevice = device;
  42840. return true;
  42841. }
  42842. else {
  42843. return false;
  42844. }
  42845. });
  42846. if (!found) {
  42847. _this._vrDevice = devices[0];
  42848. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  42849. }
  42850. }
  42851. else {
  42852. //choose the first one
  42853. _this._vrDevice = devices[0];
  42854. }
  42855. //reset the rig parameters.
  42856. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice });
  42857. }
  42858. else {
  42859. BABYLON.Tools.Error("No WebVR devices found!");
  42860. }
  42861. });
  42862. }
  42863. this.rotationQuaternion = new BABYLON.Quaternion();
  42864. this._quaternionCache = new BABYLON.Quaternion();
  42865. }
  42866. WebVRFreeCamera.prototype._checkInputs = function () {
  42867. if (this._vrEnabled) {
  42868. var currentPost = this._vrDevice.getPose();
  42869. //make sure we have data
  42870. if (currentPost && currentPost.orientation) {
  42871. this._cacheState = currentPost;
  42872. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], this._cacheState.orientation[2], this._cacheState.orientation[3]);
  42873. if (this.webVROptions.trackPosition && this._cacheState.position) {
  42874. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  42875. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  42876. }
  42877. //Flip in XY plane
  42878. this.rotationQuaternion.z *= -1;
  42879. this.rotationQuaternion.w *= -1;
  42880. }
  42881. }
  42882. _super.prototype._checkInputs.call(this);
  42883. };
  42884. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  42885. _super.prototype.attachControl.call(this, element, noPreventDefault);
  42886. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42887. if (this._vrEnabled) {
  42888. this.getEngine().enableVR(this._vrDevice);
  42889. }
  42890. };
  42891. WebVRFreeCamera.prototype.detachControl = function (element) {
  42892. _super.prototype.detachControl.call(this, element);
  42893. this._vrEnabled = false;
  42894. this.getEngine().disableVR();
  42895. };
  42896. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  42897. //Backwards comp.
  42898. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  42899. //this.getEngine().switchFullscreen(requestPointerlock);
  42900. };
  42901. WebVRFreeCamera.prototype.getTypeName = function () {
  42902. return "WebVRFreeCamera";
  42903. };
  42904. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  42905. //uses the vrDisplay's "resetPose()".
  42906. //pitch and roll won't be affected.
  42907. this._vrDevice.resetPose();
  42908. };
  42909. return WebVRFreeCamera;
  42910. }(BABYLON.FreeCamera));
  42911. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  42912. })(BABYLON || (BABYLON = {}));
  42913. var BABYLON;
  42914. (function (BABYLON) {
  42915. // Standard optimizations
  42916. var SceneOptimization = (function () {
  42917. function SceneOptimization(priority) {
  42918. if (priority === void 0) { priority = 0; }
  42919. this.priority = priority;
  42920. this.apply = function (scene) {
  42921. return true; // Return true if everything that can be done was applied
  42922. };
  42923. }
  42924. return SceneOptimization;
  42925. }());
  42926. BABYLON.SceneOptimization = SceneOptimization;
  42927. var TextureOptimization = (function (_super) {
  42928. __extends(TextureOptimization, _super);
  42929. function TextureOptimization(priority, maximumSize) {
  42930. var _this = this;
  42931. if (priority === void 0) { priority = 0; }
  42932. if (maximumSize === void 0) { maximumSize = 1024; }
  42933. _super.call(this, priority);
  42934. this.priority = priority;
  42935. this.maximumSize = maximumSize;
  42936. this.apply = function (scene) {
  42937. var allDone = true;
  42938. for (var index = 0; index < scene.textures.length; index++) {
  42939. var texture = scene.textures[index];
  42940. if (!texture.canRescale) {
  42941. continue;
  42942. }
  42943. var currentSize = texture.getSize();
  42944. var maxDimension = Math.max(currentSize.width, currentSize.height);
  42945. if (maxDimension > _this.maximumSize) {
  42946. texture.scale(0.5);
  42947. allDone = false;
  42948. }
  42949. }
  42950. return allDone;
  42951. };
  42952. }
  42953. return TextureOptimization;
  42954. }(SceneOptimization));
  42955. BABYLON.TextureOptimization = TextureOptimization;
  42956. var HardwareScalingOptimization = (function (_super) {
  42957. __extends(HardwareScalingOptimization, _super);
  42958. function HardwareScalingOptimization(priority, maximumScale) {
  42959. var _this = this;
  42960. if (priority === void 0) { priority = 0; }
  42961. if (maximumScale === void 0) { maximumScale = 2; }
  42962. _super.call(this, priority);
  42963. this.priority = priority;
  42964. this.maximumScale = maximumScale;
  42965. this._currentScale = 1;
  42966. this.apply = function (scene) {
  42967. _this._currentScale++;
  42968. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  42969. return _this._currentScale >= _this.maximumScale;
  42970. };
  42971. }
  42972. return HardwareScalingOptimization;
  42973. }(SceneOptimization));
  42974. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  42975. var ShadowsOptimization = (function (_super) {
  42976. __extends(ShadowsOptimization, _super);
  42977. function ShadowsOptimization() {
  42978. _super.apply(this, arguments);
  42979. this.apply = function (scene) {
  42980. scene.shadowsEnabled = false;
  42981. return true;
  42982. };
  42983. }
  42984. return ShadowsOptimization;
  42985. }(SceneOptimization));
  42986. BABYLON.ShadowsOptimization = ShadowsOptimization;
  42987. var PostProcessesOptimization = (function (_super) {
  42988. __extends(PostProcessesOptimization, _super);
  42989. function PostProcessesOptimization() {
  42990. _super.apply(this, arguments);
  42991. this.apply = function (scene) {
  42992. scene.postProcessesEnabled = false;
  42993. return true;
  42994. };
  42995. }
  42996. return PostProcessesOptimization;
  42997. }(SceneOptimization));
  42998. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  42999. var LensFlaresOptimization = (function (_super) {
  43000. __extends(LensFlaresOptimization, _super);
  43001. function LensFlaresOptimization() {
  43002. _super.apply(this, arguments);
  43003. this.apply = function (scene) {
  43004. scene.lensFlaresEnabled = false;
  43005. return true;
  43006. };
  43007. }
  43008. return LensFlaresOptimization;
  43009. }(SceneOptimization));
  43010. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  43011. var ParticlesOptimization = (function (_super) {
  43012. __extends(ParticlesOptimization, _super);
  43013. function ParticlesOptimization() {
  43014. _super.apply(this, arguments);
  43015. this.apply = function (scene) {
  43016. scene.particlesEnabled = false;
  43017. return true;
  43018. };
  43019. }
  43020. return ParticlesOptimization;
  43021. }(SceneOptimization));
  43022. BABYLON.ParticlesOptimization = ParticlesOptimization;
  43023. var RenderTargetsOptimization = (function (_super) {
  43024. __extends(RenderTargetsOptimization, _super);
  43025. function RenderTargetsOptimization() {
  43026. _super.apply(this, arguments);
  43027. this.apply = function (scene) {
  43028. scene.renderTargetsEnabled = false;
  43029. return true;
  43030. };
  43031. }
  43032. return RenderTargetsOptimization;
  43033. }(SceneOptimization));
  43034. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  43035. var MergeMeshesOptimization = (function (_super) {
  43036. __extends(MergeMeshesOptimization, _super);
  43037. function MergeMeshesOptimization() {
  43038. var _this = this;
  43039. _super.apply(this, arguments);
  43040. this._canBeMerged = function (abstractMesh) {
  43041. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  43042. return false;
  43043. }
  43044. var mesh = abstractMesh;
  43045. if (!mesh.isVisible || !mesh.isEnabled()) {
  43046. return false;
  43047. }
  43048. if (mesh.instances.length > 0) {
  43049. return false;
  43050. }
  43051. if (mesh.skeleton || mesh.hasLODLevels) {
  43052. return false;
  43053. }
  43054. if (mesh.parent) {
  43055. return false;
  43056. }
  43057. return true;
  43058. };
  43059. this.apply = function (scene, updateSelectionTree) {
  43060. var globalPool = scene.meshes.slice(0);
  43061. var globalLength = globalPool.length;
  43062. for (var index = 0; index < globalLength; index++) {
  43063. var currentPool = new Array();
  43064. var current = globalPool[index];
  43065. // Checks
  43066. if (!_this._canBeMerged(current)) {
  43067. continue;
  43068. }
  43069. currentPool.push(current);
  43070. // Find compatible meshes
  43071. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  43072. var otherMesh = globalPool[subIndex];
  43073. if (!_this._canBeMerged(otherMesh)) {
  43074. continue;
  43075. }
  43076. if (otherMesh.material !== current.material) {
  43077. continue;
  43078. }
  43079. if (otherMesh.checkCollisions !== current.checkCollisions) {
  43080. continue;
  43081. }
  43082. currentPool.push(otherMesh);
  43083. globalLength--;
  43084. globalPool.splice(subIndex, 1);
  43085. subIndex--;
  43086. }
  43087. if (currentPool.length < 2) {
  43088. continue;
  43089. }
  43090. // Merge meshes
  43091. BABYLON.Mesh.MergeMeshes(currentPool);
  43092. }
  43093. if (updateSelectionTree != undefined) {
  43094. if (updateSelectionTree) {
  43095. scene.createOrUpdateSelectionOctree();
  43096. }
  43097. }
  43098. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  43099. scene.createOrUpdateSelectionOctree();
  43100. }
  43101. return true;
  43102. };
  43103. }
  43104. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  43105. get: function () {
  43106. return MergeMeshesOptimization._UpdateSelectionTree;
  43107. },
  43108. set: function (value) {
  43109. MergeMeshesOptimization._UpdateSelectionTree = value;
  43110. },
  43111. enumerable: true,
  43112. configurable: true
  43113. });
  43114. MergeMeshesOptimization._UpdateSelectionTree = false;
  43115. return MergeMeshesOptimization;
  43116. }(SceneOptimization));
  43117. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  43118. // Options
  43119. var SceneOptimizerOptions = (function () {
  43120. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  43121. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  43122. if (trackerDuration === void 0) { trackerDuration = 2000; }
  43123. this.targetFrameRate = targetFrameRate;
  43124. this.trackerDuration = trackerDuration;
  43125. this.optimizations = new Array();
  43126. }
  43127. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  43128. var result = new SceneOptimizerOptions(targetFrameRate);
  43129. var priority = 0;
  43130. result.optimizations.push(new MergeMeshesOptimization(priority));
  43131. result.optimizations.push(new ShadowsOptimization(priority));
  43132. result.optimizations.push(new LensFlaresOptimization(priority));
  43133. // Next priority
  43134. priority++;
  43135. result.optimizations.push(new PostProcessesOptimization(priority));
  43136. result.optimizations.push(new ParticlesOptimization(priority));
  43137. // Next priority
  43138. priority++;
  43139. result.optimizations.push(new TextureOptimization(priority, 1024));
  43140. return result;
  43141. };
  43142. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  43143. var result = new SceneOptimizerOptions(targetFrameRate);
  43144. var priority = 0;
  43145. result.optimizations.push(new MergeMeshesOptimization(priority));
  43146. result.optimizations.push(new ShadowsOptimization(priority));
  43147. result.optimizations.push(new LensFlaresOptimization(priority));
  43148. // Next priority
  43149. priority++;
  43150. result.optimizations.push(new PostProcessesOptimization(priority));
  43151. result.optimizations.push(new ParticlesOptimization(priority));
  43152. // Next priority
  43153. priority++;
  43154. result.optimizations.push(new TextureOptimization(priority, 512));
  43155. // Next priority
  43156. priority++;
  43157. result.optimizations.push(new RenderTargetsOptimization(priority));
  43158. // Next priority
  43159. priority++;
  43160. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  43161. return result;
  43162. };
  43163. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  43164. var result = new SceneOptimizerOptions(targetFrameRate);
  43165. var priority = 0;
  43166. result.optimizations.push(new MergeMeshesOptimization(priority));
  43167. result.optimizations.push(new ShadowsOptimization(priority));
  43168. result.optimizations.push(new LensFlaresOptimization(priority));
  43169. // Next priority
  43170. priority++;
  43171. result.optimizations.push(new PostProcessesOptimization(priority));
  43172. result.optimizations.push(new ParticlesOptimization(priority));
  43173. // Next priority
  43174. priority++;
  43175. result.optimizations.push(new TextureOptimization(priority, 256));
  43176. // Next priority
  43177. priority++;
  43178. result.optimizations.push(new RenderTargetsOptimization(priority));
  43179. // Next priority
  43180. priority++;
  43181. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  43182. return result;
  43183. };
  43184. return SceneOptimizerOptions;
  43185. }());
  43186. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  43187. // Scene optimizer tool
  43188. var SceneOptimizer = (function () {
  43189. function SceneOptimizer() {
  43190. }
  43191. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  43192. // TODO: add an epsilon
  43193. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  43194. if (onSuccess) {
  43195. onSuccess();
  43196. }
  43197. return;
  43198. }
  43199. // Apply current level of optimizations
  43200. var allDone = true;
  43201. var noOptimizationApplied = true;
  43202. for (var index = 0; index < options.optimizations.length; index++) {
  43203. var optimization = options.optimizations[index];
  43204. if (optimization.priority === currentPriorityLevel) {
  43205. noOptimizationApplied = false;
  43206. allDone = allDone && optimization.apply(scene);
  43207. }
  43208. }
  43209. // If no optimization was applied, this is a failure :(
  43210. if (noOptimizationApplied) {
  43211. if (onFailure) {
  43212. onFailure();
  43213. }
  43214. return;
  43215. }
  43216. // If all optimizations were done, move to next level
  43217. if (allDone) {
  43218. currentPriorityLevel++;
  43219. }
  43220. // Let's the system running for a specific amount of time before checking FPS
  43221. scene.executeWhenReady(function () {
  43222. setTimeout(function () {
  43223. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  43224. }, options.trackerDuration);
  43225. });
  43226. };
  43227. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  43228. if (!options) {
  43229. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  43230. }
  43231. // Let's the system running for a specific amount of time before checking FPS
  43232. scene.executeWhenReady(function () {
  43233. setTimeout(function () {
  43234. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  43235. }, options.trackerDuration);
  43236. });
  43237. };
  43238. return SceneOptimizer;
  43239. }());
  43240. BABYLON.SceneOptimizer = SceneOptimizer;
  43241. })(BABYLON || (BABYLON = {}));
  43242. var BABYLON;
  43243. (function (BABYLON) {
  43244. var Internals;
  43245. (function (Internals) {
  43246. var MeshLODLevel = (function () {
  43247. function MeshLODLevel(distance, mesh) {
  43248. this.distance = distance;
  43249. this.mesh = mesh;
  43250. }
  43251. return MeshLODLevel;
  43252. }());
  43253. Internals.MeshLODLevel = MeshLODLevel;
  43254. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43255. })(BABYLON || (BABYLON = {}));
  43256. var BABYLON;
  43257. (function (BABYLON) {
  43258. var RawTexture = (function (_super) {
  43259. __extends(RawTexture, _super);
  43260. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  43261. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43262. if (invertY === void 0) { invertY = false; }
  43263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43264. _super.call(this, null, scene, !generateMipMaps, invertY);
  43265. this.format = format;
  43266. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  43267. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43268. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43269. }
  43270. RawTexture.prototype.update = function (data) {
  43271. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  43272. };
  43273. // Statics
  43274. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43275. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43276. if (invertY === void 0) { invertY = false; }
  43277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43278. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  43279. };
  43280. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43281. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43282. if (invertY === void 0) { invertY = false; }
  43283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43284. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43285. };
  43286. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43287. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43288. if (invertY === void 0) { invertY = false; }
  43289. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43290. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43291. };
  43292. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43293. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43294. if (invertY === void 0) { invertY = false; }
  43295. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43296. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  43297. };
  43298. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43299. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43300. if (invertY === void 0) { invertY = false; }
  43301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43302. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  43303. };
  43304. return RawTexture;
  43305. }(BABYLON.Texture));
  43306. BABYLON.RawTexture = RawTexture;
  43307. })(BABYLON || (BABYLON = {}));
  43308. var BABYLON;
  43309. (function (BABYLON) {
  43310. var IndexedVector2 = (function (_super) {
  43311. __extends(IndexedVector2, _super);
  43312. function IndexedVector2(original, index) {
  43313. _super.call(this, original.x, original.y);
  43314. this.index = index;
  43315. }
  43316. return IndexedVector2;
  43317. }(BABYLON.Vector2));
  43318. var PolygonPoints = (function () {
  43319. function PolygonPoints() {
  43320. this.elements = new Array();
  43321. }
  43322. PolygonPoints.prototype.add = function (originalPoints) {
  43323. var _this = this;
  43324. var result = new Array();
  43325. originalPoints.forEach(function (point) {
  43326. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  43327. var newPoint = new IndexedVector2(point, _this.elements.length);
  43328. result.push(newPoint);
  43329. _this.elements.push(newPoint);
  43330. }
  43331. });
  43332. return result;
  43333. };
  43334. PolygonPoints.prototype.computeBounds = function () {
  43335. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  43336. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  43337. this.elements.forEach(function (point) {
  43338. // x
  43339. if (point.x < lmin.x) {
  43340. lmin.x = point.x;
  43341. }
  43342. else if (point.x > lmax.x) {
  43343. lmax.x = point.x;
  43344. }
  43345. // y
  43346. if (point.y < lmin.y) {
  43347. lmin.y = point.y;
  43348. }
  43349. else if (point.y > lmax.y) {
  43350. lmax.y = point.y;
  43351. }
  43352. });
  43353. return {
  43354. min: lmin,
  43355. max: lmax,
  43356. width: lmax.x - lmin.x,
  43357. height: lmax.y - lmin.y
  43358. };
  43359. };
  43360. return PolygonPoints;
  43361. }());
  43362. var Polygon = (function () {
  43363. function Polygon() {
  43364. }
  43365. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  43366. return [
  43367. new BABYLON.Vector2(xmin, ymin),
  43368. new BABYLON.Vector2(xmax, ymin),
  43369. new BABYLON.Vector2(xmax, ymax),
  43370. new BABYLON.Vector2(xmin, ymax)
  43371. ];
  43372. };
  43373. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  43374. if (cx === void 0) { cx = 0; }
  43375. if (cy === void 0) { cy = 0; }
  43376. if (numberOfSides === void 0) { numberOfSides = 32; }
  43377. var result = new Array();
  43378. var angle = 0;
  43379. var increment = (Math.PI * 2) / numberOfSides;
  43380. for (var i = 0; i < numberOfSides; i++) {
  43381. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  43382. angle -= increment;
  43383. }
  43384. return result;
  43385. };
  43386. Polygon.Parse = function (input) {
  43387. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  43388. var i, result = [];
  43389. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  43390. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  43391. }
  43392. return result;
  43393. };
  43394. Polygon.StartingAt = function (x, y) {
  43395. return BABYLON.Path2.StartingAt(x, y);
  43396. };
  43397. return Polygon;
  43398. }());
  43399. BABYLON.Polygon = Polygon;
  43400. var PolygonMeshBuilder = (function () {
  43401. function PolygonMeshBuilder(name, contours, scene) {
  43402. this._points = new PolygonPoints();
  43403. this._outlinepoints = new PolygonPoints();
  43404. this._holes = [];
  43405. this._epoints = new Array();
  43406. this._eholes = new Array();
  43407. this._name = name;
  43408. this._scene = scene;
  43409. var points;
  43410. if (contours instanceof BABYLON.Path2) {
  43411. points = contours.getPoints();
  43412. }
  43413. else {
  43414. points = contours;
  43415. }
  43416. this._addToepoint(points);
  43417. this._points.add(points);
  43418. this._outlinepoints.add(points);
  43419. }
  43420. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  43421. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  43422. var p = points_1[_i];
  43423. this._epoints.push(p.x, p.y);
  43424. }
  43425. };
  43426. PolygonMeshBuilder.prototype.addHole = function (hole) {
  43427. this._points.add(hole);
  43428. var holepoints = new PolygonPoints();
  43429. holepoints.add(hole);
  43430. this._holes.push(holepoints);
  43431. this._eholes.push(this._epoints.length / 2);
  43432. this._addToepoint(hole);
  43433. return this;
  43434. };
  43435. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  43436. var _this = this;
  43437. if (updatable === void 0) { updatable = false; }
  43438. var result = new BABYLON.Mesh(this._name, this._scene);
  43439. var normals = [];
  43440. var positions = [];
  43441. var uvs = [];
  43442. var bounds = this._points.computeBounds();
  43443. this._points.elements.forEach(function (p) {
  43444. normals.push(0, 1.0, 0);
  43445. positions.push(p.x, 0, p.y);
  43446. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  43447. });
  43448. var indices = [];
  43449. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  43450. for (var i = 0; i < res.length; i++) {
  43451. indices.push(res[i]);
  43452. }
  43453. if (depth > 0) {
  43454. var positionscount = (positions.length / 3); //get the current pointcount
  43455. this._points.elements.forEach(function (p) {
  43456. normals.push(0, -1.0, 0);
  43457. positions.push(p.x, -depth, p.y);
  43458. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  43459. });
  43460. var totalCount = indices.length;
  43461. for (var i = 0; i < totalCount; i += 3) {
  43462. var i0 = indices[i + 0];
  43463. var i1 = indices[i + 1];
  43464. var i2 = indices[i + 2];
  43465. indices.push(i2 + positionscount);
  43466. indices.push(i1 + positionscount);
  43467. indices.push(i0 + positionscount);
  43468. }
  43469. //Add the sides
  43470. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  43471. this._holes.forEach(function (hole) {
  43472. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  43473. });
  43474. }
  43475. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  43476. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  43477. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  43478. result.setIndices(indices);
  43479. return result;
  43480. };
  43481. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  43482. var StartIndex = positions.length / 3;
  43483. var ulength = 0;
  43484. for (var i = 0; i < points.elements.length; i++) {
  43485. var p = points.elements[i];
  43486. var p1;
  43487. if ((i + 1) > points.elements.length - 1) {
  43488. p1 = points.elements[0];
  43489. }
  43490. else {
  43491. p1 = points.elements[i + 1];
  43492. }
  43493. positions.push(p.x, 0, p.y);
  43494. positions.push(p.x, -depth, p.y);
  43495. positions.push(p1.x, 0, p1.y);
  43496. positions.push(p1.x, -depth, p1.y);
  43497. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  43498. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  43499. var v3 = v2.subtract(v1);
  43500. var v4 = new BABYLON.Vector3(0, 1, 0);
  43501. var vn = BABYLON.Vector3.Cross(v3, v4);
  43502. vn = vn.normalize();
  43503. uvs.push(ulength / bounds.width, 0);
  43504. uvs.push(ulength / bounds.width, 1);
  43505. ulength += v3.length();
  43506. uvs.push((ulength / bounds.width), 0);
  43507. uvs.push((ulength / bounds.width), 1);
  43508. if (!flip) {
  43509. normals.push(-vn.x, -vn.y, -vn.z);
  43510. normals.push(-vn.x, -vn.y, -vn.z);
  43511. normals.push(-vn.x, -vn.y, -vn.z);
  43512. normals.push(-vn.x, -vn.y, -vn.z);
  43513. indices.push(StartIndex);
  43514. indices.push(StartIndex + 1);
  43515. indices.push(StartIndex + 2);
  43516. indices.push(StartIndex + 1);
  43517. indices.push(StartIndex + 3);
  43518. indices.push(StartIndex + 2);
  43519. }
  43520. else {
  43521. normals.push(vn.x, vn.y, vn.z);
  43522. normals.push(vn.x, vn.y, vn.z);
  43523. normals.push(vn.x, vn.y, vn.z);
  43524. normals.push(vn.x, vn.y, vn.z);
  43525. indices.push(StartIndex);
  43526. indices.push(StartIndex + 2);
  43527. indices.push(StartIndex + 1);
  43528. indices.push(StartIndex + 1);
  43529. indices.push(StartIndex + 2);
  43530. indices.push(StartIndex + 3);
  43531. }
  43532. StartIndex += 4;
  43533. }
  43534. ;
  43535. };
  43536. return PolygonMeshBuilder;
  43537. }());
  43538. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  43539. })(BABYLON || (BABYLON = {}));
  43540. var BABYLON;
  43541. (function (BABYLON) {
  43542. var Octree = (function () {
  43543. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  43544. if (maxDepth === void 0) { maxDepth = 2; }
  43545. this.maxDepth = maxDepth;
  43546. this.dynamicContent = new Array();
  43547. this._maxBlockCapacity = maxBlockCapacity || 64;
  43548. this._selectionContent = new BABYLON.SmartArray(1024);
  43549. this._creationFunc = creationFunc;
  43550. }
  43551. // Methods
  43552. Octree.prototype.update = function (worldMin, worldMax, entries) {
  43553. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  43554. };
  43555. Octree.prototype.addMesh = function (entry) {
  43556. for (var index = 0; index < this.blocks.length; index++) {
  43557. var block = this.blocks[index];
  43558. block.addEntry(entry);
  43559. }
  43560. };
  43561. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  43562. this._selectionContent.reset();
  43563. for (var index = 0; index < this.blocks.length; index++) {
  43564. var block = this.blocks[index];
  43565. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  43566. }
  43567. if (allowDuplicate) {
  43568. this._selectionContent.concat(this.dynamicContent);
  43569. }
  43570. else {
  43571. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  43572. }
  43573. return this._selectionContent;
  43574. };
  43575. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  43576. this._selectionContent.reset();
  43577. for (var index = 0; index < this.blocks.length; index++) {
  43578. var block = this.blocks[index];
  43579. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  43580. }
  43581. if (allowDuplicate) {
  43582. this._selectionContent.concat(this.dynamicContent);
  43583. }
  43584. else {
  43585. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  43586. }
  43587. return this._selectionContent;
  43588. };
  43589. Octree.prototype.intersectsRay = function (ray) {
  43590. this._selectionContent.reset();
  43591. for (var index = 0; index < this.blocks.length; index++) {
  43592. var block = this.blocks[index];
  43593. block.intersectsRay(ray, this._selectionContent);
  43594. }
  43595. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  43596. return this._selectionContent;
  43597. };
  43598. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  43599. target.blocks = new Array();
  43600. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  43601. // Segmenting space
  43602. for (var x = 0; x < 2; x++) {
  43603. for (var y = 0; y < 2; y++) {
  43604. for (var z = 0; z < 2; z++) {
  43605. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  43606. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  43607. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  43608. block.addEntries(entries);
  43609. target.blocks.push(block);
  43610. }
  43611. }
  43612. }
  43613. };
  43614. Octree.CreationFuncForMeshes = function (entry, block) {
  43615. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  43616. block.entries.push(entry);
  43617. }
  43618. };
  43619. Octree.CreationFuncForSubMeshes = function (entry, block) {
  43620. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  43621. block.entries.push(entry);
  43622. }
  43623. };
  43624. return Octree;
  43625. }());
  43626. BABYLON.Octree = Octree;
  43627. })(BABYLON || (BABYLON = {}));
  43628. var BABYLON;
  43629. (function (BABYLON) {
  43630. var OctreeBlock = (function () {
  43631. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  43632. this.entries = new Array();
  43633. this._boundingVectors = new Array();
  43634. this._capacity = capacity;
  43635. this._depth = depth;
  43636. this._maxDepth = maxDepth;
  43637. this._creationFunc = creationFunc;
  43638. this._minPoint = minPoint;
  43639. this._maxPoint = maxPoint;
  43640. this._boundingVectors.push(minPoint.clone());
  43641. this._boundingVectors.push(maxPoint.clone());
  43642. this._boundingVectors.push(minPoint.clone());
  43643. this._boundingVectors[2].x = maxPoint.x;
  43644. this._boundingVectors.push(minPoint.clone());
  43645. this._boundingVectors[3].y = maxPoint.y;
  43646. this._boundingVectors.push(minPoint.clone());
  43647. this._boundingVectors[4].z = maxPoint.z;
  43648. this._boundingVectors.push(maxPoint.clone());
  43649. this._boundingVectors[5].z = minPoint.z;
  43650. this._boundingVectors.push(maxPoint.clone());
  43651. this._boundingVectors[6].x = minPoint.x;
  43652. this._boundingVectors.push(maxPoint.clone());
  43653. this._boundingVectors[7].y = minPoint.y;
  43654. }
  43655. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  43656. // Property
  43657. get: function () {
  43658. return this._capacity;
  43659. },
  43660. enumerable: true,
  43661. configurable: true
  43662. });
  43663. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  43664. get: function () {
  43665. return this._minPoint;
  43666. },
  43667. enumerable: true,
  43668. configurable: true
  43669. });
  43670. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  43671. get: function () {
  43672. return this._maxPoint;
  43673. },
  43674. enumerable: true,
  43675. configurable: true
  43676. });
  43677. // Methods
  43678. OctreeBlock.prototype.addEntry = function (entry) {
  43679. if (this.blocks) {
  43680. for (var index = 0; index < this.blocks.length; index++) {
  43681. var block = this.blocks[index];
  43682. block.addEntry(entry);
  43683. }
  43684. return;
  43685. }
  43686. this._creationFunc(entry, this);
  43687. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  43688. this.createInnerBlocks();
  43689. }
  43690. };
  43691. OctreeBlock.prototype.addEntries = function (entries) {
  43692. for (var index = 0; index < entries.length; index++) {
  43693. var mesh = entries[index];
  43694. this.addEntry(mesh);
  43695. }
  43696. };
  43697. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  43698. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  43699. if (this.blocks) {
  43700. for (var index = 0; index < this.blocks.length; index++) {
  43701. var block = this.blocks[index];
  43702. block.select(frustumPlanes, selection, allowDuplicate);
  43703. }
  43704. return;
  43705. }
  43706. if (allowDuplicate) {
  43707. selection.concat(this.entries);
  43708. }
  43709. else {
  43710. selection.concatWithNoDuplicate(this.entries);
  43711. }
  43712. }
  43713. };
  43714. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  43715. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  43716. if (this.blocks) {
  43717. for (var index = 0; index < this.blocks.length; index++) {
  43718. var block = this.blocks[index];
  43719. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  43720. }
  43721. return;
  43722. }
  43723. if (allowDuplicate) {
  43724. selection.concat(this.entries);
  43725. }
  43726. else {
  43727. selection.concatWithNoDuplicate(this.entries);
  43728. }
  43729. }
  43730. };
  43731. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  43732. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  43733. if (this.blocks) {
  43734. for (var index = 0; index < this.blocks.length; index++) {
  43735. var block = this.blocks[index];
  43736. block.intersectsRay(ray, selection);
  43737. }
  43738. return;
  43739. }
  43740. selection.concatWithNoDuplicate(this.entries);
  43741. }
  43742. };
  43743. OctreeBlock.prototype.createInnerBlocks = function () {
  43744. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  43745. };
  43746. return OctreeBlock;
  43747. }());
  43748. BABYLON.OctreeBlock = OctreeBlock;
  43749. })(BABYLON || (BABYLON = {}));
  43750. var BABYLON;
  43751. (function (BABYLON) {
  43752. var BlurPostProcess = (function (_super) {
  43753. __extends(BlurPostProcess, _super);
  43754. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  43755. var _this = this;
  43756. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43757. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  43758. this.direction = direction;
  43759. this.blurWidth = blurWidth;
  43760. this.onApplyObservable.add(function (effect) {
  43761. effect.setFloat2("screenSize", _this.width, _this.height);
  43762. effect.setVector2("direction", _this.direction);
  43763. effect.setFloat("blurWidth", _this.blurWidth);
  43764. });
  43765. }
  43766. return BlurPostProcess;
  43767. }(BABYLON.PostProcess));
  43768. BABYLON.BlurPostProcess = BlurPostProcess;
  43769. })(BABYLON || (BABYLON = {}));
  43770. var BABYLON;
  43771. (function (BABYLON) {
  43772. var RefractionPostProcess = (function (_super) {
  43773. __extends(RefractionPostProcess, _super);
  43774. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  43775. var _this = this;
  43776. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  43777. this.color = color;
  43778. this.depth = depth;
  43779. this.colorLevel = colorLevel;
  43780. this.onActivateObservable.add(function (cam) {
  43781. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  43782. });
  43783. this.onApplyObservable.add(function (effect) {
  43784. effect.setColor3("baseColor", _this.color);
  43785. effect.setFloat("depth", _this.depth);
  43786. effect.setFloat("colorLevel", _this.colorLevel);
  43787. effect.setTexture("refractionSampler", _this._refRexture);
  43788. });
  43789. }
  43790. // Methods
  43791. RefractionPostProcess.prototype.dispose = function (camera) {
  43792. if (this._refRexture) {
  43793. this._refRexture.dispose();
  43794. }
  43795. _super.prototype.dispose.call(this, camera);
  43796. };
  43797. return RefractionPostProcess;
  43798. }(BABYLON.PostProcess));
  43799. BABYLON.RefractionPostProcess = RefractionPostProcess;
  43800. })(BABYLON || (BABYLON = {}));
  43801. var BABYLON;
  43802. (function (BABYLON) {
  43803. var BlackAndWhitePostProcess = (function (_super) {
  43804. __extends(BlackAndWhitePostProcess, _super);
  43805. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  43806. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  43807. }
  43808. return BlackAndWhitePostProcess;
  43809. }(BABYLON.PostProcess));
  43810. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  43811. })(BABYLON || (BABYLON = {}));
  43812. var BABYLON;
  43813. (function (BABYLON) {
  43814. var ConvolutionPostProcess = (function (_super) {
  43815. __extends(ConvolutionPostProcess, _super);
  43816. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  43817. var _this = this;
  43818. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  43819. this.kernel = kernel;
  43820. this.onApply = function (effect) {
  43821. effect.setFloat2("screenSize", _this.width, _this.height);
  43822. effect.setArray("kernel", _this.kernel);
  43823. };
  43824. }
  43825. // Statics
  43826. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  43827. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  43828. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  43829. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  43830. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  43831. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  43832. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  43833. return ConvolutionPostProcess;
  43834. }(BABYLON.PostProcess));
  43835. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  43836. })(BABYLON || (BABYLON = {}));
  43837. var BABYLON;
  43838. (function (BABYLON) {
  43839. var FilterPostProcess = (function (_super) {
  43840. __extends(FilterPostProcess, _super);
  43841. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  43842. var _this = this;
  43843. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  43844. this.kernelMatrix = kernelMatrix;
  43845. this.onApply = function (effect) {
  43846. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  43847. };
  43848. }
  43849. return FilterPostProcess;
  43850. }(BABYLON.PostProcess));
  43851. BABYLON.FilterPostProcess = FilterPostProcess;
  43852. })(BABYLON || (BABYLON = {}));
  43853. var BABYLON;
  43854. (function (BABYLON) {
  43855. var FxaaPostProcess = (function (_super) {
  43856. __extends(FxaaPostProcess, _super);
  43857. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  43858. var _this = this;
  43859. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  43860. this.onSizeChangedObservable.add(function () {
  43861. _this.texelWidth = 1.0 / _this.width;
  43862. _this.texelHeight = 1.0 / _this.height;
  43863. });
  43864. this.onApplyObservable.add(function (effect) {
  43865. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  43866. });
  43867. }
  43868. return FxaaPostProcess;
  43869. }(BABYLON.PostProcess));
  43870. BABYLON.FxaaPostProcess = FxaaPostProcess;
  43871. })(BABYLON || (BABYLON = {}));
  43872. var BABYLON;
  43873. (function (BABYLON) {
  43874. var StereoscopicInterlacePostProcess = (function (_super) {
  43875. __extends(StereoscopicInterlacePostProcess, _super);
  43876. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  43877. var _this = this;
  43878. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  43879. this._passedProcess = rigCameras[0]._rigPostProcess;
  43880. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  43881. this.onSizeChangedObservable.add(function () {
  43882. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  43883. });
  43884. this.onApplyObservable.add(function (effect) {
  43885. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  43886. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  43887. });
  43888. }
  43889. return StereoscopicInterlacePostProcess;
  43890. }(BABYLON.PostProcess));
  43891. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  43892. })(BABYLON || (BABYLON = {}));
  43893. var BABYLON;
  43894. (function (BABYLON) {
  43895. var LensFlare = (function () {
  43896. function LensFlare(size, position, color, imgUrl, system) {
  43897. this.size = size;
  43898. this.position = position;
  43899. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  43900. this.dispose = function () {
  43901. if (this.texture) {
  43902. this.texture.dispose();
  43903. }
  43904. // Remove from scene
  43905. var index = this._system.lensFlares.indexOf(this);
  43906. this._system.lensFlares.splice(index, 1);
  43907. };
  43908. this.color = color || new BABYLON.Color3(1, 1, 1);
  43909. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  43910. this._system = system;
  43911. system.lensFlares.push(this);
  43912. }
  43913. return LensFlare;
  43914. }());
  43915. BABYLON.LensFlare = LensFlare;
  43916. })(BABYLON || (BABYLON = {}));
  43917. var BABYLON;
  43918. (function (BABYLON) {
  43919. var LensFlareSystem = (function () {
  43920. function LensFlareSystem(name, emitter, scene) {
  43921. this.name = name;
  43922. this.lensFlares = new Array();
  43923. this.borderLimit = 300;
  43924. this.viewportBorder = 0;
  43925. this.layerMask = 0x0FFFFFFF;
  43926. this._vertexBuffers = {};
  43927. this._isEnabled = true;
  43928. this._scene = scene;
  43929. this._emitter = emitter;
  43930. this.id = name;
  43931. scene.lensFlareSystems.push(this);
  43932. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  43933. var engine = scene.getEngine();
  43934. // VBO
  43935. var vertices = [];
  43936. vertices.push(1, 1);
  43937. vertices.push(-1, 1);
  43938. vertices.push(-1, -1);
  43939. vertices.push(1, -1);
  43940. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  43941. // Indices
  43942. var indices = [];
  43943. indices.push(0);
  43944. indices.push(1);
  43945. indices.push(2);
  43946. indices.push(0);
  43947. indices.push(2);
  43948. indices.push(3);
  43949. this._indexBuffer = engine.createIndexBuffer(indices);
  43950. // Effects
  43951. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  43952. }
  43953. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  43954. get: function () {
  43955. return this._isEnabled;
  43956. },
  43957. set: function (value) {
  43958. this._isEnabled = value;
  43959. },
  43960. enumerable: true,
  43961. configurable: true
  43962. });
  43963. LensFlareSystem.prototype.getScene = function () {
  43964. return this._scene;
  43965. };
  43966. LensFlareSystem.prototype.getEmitter = function () {
  43967. return this._emitter;
  43968. };
  43969. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  43970. this._emitter = newEmitter;
  43971. };
  43972. LensFlareSystem.prototype.getEmitterPosition = function () {
  43973. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  43974. };
  43975. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  43976. var position = this.getEmitterPosition();
  43977. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  43978. this._positionX = position.x;
  43979. this._positionY = position.y;
  43980. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  43981. if (this.viewportBorder > 0) {
  43982. globalViewport.x -= this.viewportBorder;
  43983. globalViewport.y -= this.viewportBorder;
  43984. globalViewport.width += this.viewportBorder * 2;
  43985. globalViewport.height += this.viewportBorder * 2;
  43986. position.x += this.viewportBorder;
  43987. position.y += this.viewportBorder;
  43988. this._positionX += this.viewportBorder;
  43989. this._positionY += this.viewportBorder;
  43990. }
  43991. if (position.z > 0) {
  43992. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  43993. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  43994. return true;
  43995. }
  43996. return true;
  43997. }
  43998. return false;
  43999. };
  44000. LensFlareSystem.prototype._isVisible = function () {
  44001. if (!this._isEnabled) {
  44002. return false;
  44003. }
  44004. var emitterPosition = this.getEmitterPosition();
  44005. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  44006. var distance = direction.length();
  44007. direction.normalize();
  44008. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  44009. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  44010. return !pickInfo.hit || pickInfo.distance > distance;
  44011. };
  44012. LensFlareSystem.prototype.render = function () {
  44013. if (!this._effect.isReady())
  44014. return false;
  44015. var engine = this._scene.getEngine();
  44016. var viewport = this._scene.activeCamera.viewport;
  44017. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  44018. // Position
  44019. if (!this.computeEffectivePosition(globalViewport)) {
  44020. return false;
  44021. }
  44022. // Visibility
  44023. if (!this._isVisible()) {
  44024. return false;
  44025. }
  44026. // Intensity
  44027. var awayX;
  44028. var awayY;
  44029. if (this._positionX < this.borderLimit + globalViewport.x) {
  44030. awayX = this.borderLimit + globalViewport.x - this._positionX;
  44031. }
  44032. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  44033. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  44034. }
  44035. else {
  44036. awayX = 0;
  44037. }
  44038. if (this._positionY < this.borderLimit + globalViewport.y) {
  44039. awayY = this.borderLimit + globalViewport.y - this._positionY;
  44040. }
  44041. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  44042. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  44043. }
  44044. else {
  44045. awayY = 0;
  44046. }
  44047. var away = (awayX > awayY) ? awayX : awayY;
  44048. away -= this.viewportBorder;
  44049. if (away > this.borderLimit) {
  44050. away = this.borderLimit;
  44051. }
  44052. var intensity = 1.0 - (away / this.borderLimit);
  44053. if (intensity < 0) {
  44054. return false;
  44055. }
  44056. if (intensity > 1.0) {
  44057. intensity = 1.0;
  44058. }
  44059. if (this.viewportBorder > 0) {
  44060. globalViewport.x += this.viewportBorder;
  44061. globalViewport.y += this.viewportBorder;
  44062. globalViewport.width -= this.viewportBorder * 2;
  44063. globalViewport.height -= this.viewportBorder * 2;
  44064. this._positionX -= this.viewportBorder;
  44065. this._positionY -= this.viewportBorder;
  44066. }
  44067. // Position
  44068. var centerX = globalViewport.x + globalViewport.width / 2;
  44069. var centerY = globalViewport.y + globalViewport.height / 2;
  44070. var distX = centerX - this._positionX;
  44071. var distY = centerY - this._positionY;
  44072. // Effects
  44073. engine.enableEffect(this._effect);
  44074. engine.setState(false);
  44075. engine.setDepthBuffer(false);
  44076. // VBOs
  44077. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44078. // Flares
  44079. for (var index = 0; index < this.lensFlares.length; index++) {
  44080. var flare = this.lensFlares[index];
  44081. engine.setAlphaMode(flare.alphaMode);
  44082. var x = centerX - (distX * flare.position);
  44083. var y = centerY - (distY * flare.position);
  44084. var cw = flare.size;
  44085. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  44086. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  44087. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  44088. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  44089. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  44090. // Texture
  44091. this._effect.setTexture("textureSampler", flare.texture);
  44092. // Color
  44093. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  44094. // Draw order
  44095. engine.draw(true, 0, 6);
  44096. }
  44097. engine.setDepthBuffer(true);
  44098. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44099. return true;
  44100. };
  44101. LensFlareSystem.prototype.dispose = function () {
  44102. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  44103. if (vertexBuffer) {
  44104. vertexBuffer.dispose();
  44105. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  44106. }
  44107. if (this._indexBuffer) {
  44108. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44109. this._indexBuffer = null;
  44110. }
  44111. while (this.lensFlares.length) {
  44112. this.lensFlares[0].dispose();
  44113. }
  44114. // Remove from scene
  44115. var index = this._scene.lensFlareSystems.indexOf(this);
  44116. this._scene.lensFlareSystems.splice(index, 1);
  44117. };
  44118. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  44119. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  44120. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  44121. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  44122. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  44123. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  44124. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  44125. var parsedFlare = parsedLensFlareSystem.flares[index];
  44126. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  44127. }
  44128. return lensFlareSystem;
  44129. };
  44130. LensFlareSystem.prototype.serialize = function () {
  44131. var serializationObject = {};
  44132. serializationObject.id = this.id;
  44133. serializationObject.name = this.name;
  44134. serializationObject.emitterId = this.getEmitter().id;
  44135. serializationObject.borderLimit = this.borderLimit;
  44136. serializationObject.flares = [];
  44137. for (var index = 0; index < this.lensFlares.length; index++) {
  44138. var flare = this.lensFlares[index];
  44139. serializationObject.flares.push({
  44140. size: flare.size,
  44141. position: flare.position,
  44142. color: flare.color.asArray(),
  44143. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  44144. });
  44145. }
  44146. return serializationObject;
  44147. };
  44148. return LensFlareSystem;
  44149. }());
  44150. BABYLON.LensFlareSystem = LensFlareSystem;
  44151. })(BABYLON || (BABYLON = {}));
  44152. var BABYLON;
  44153. (function (BABYLON) {
  44154. // We're mainly based on the logic defined into the FreeCamera code
  44155. var DeviceOrientationCamera = (function (_super) {
  44156. __extends(DeviceOrientationCamera, _super);
  44157. function DeviceOrientationCamera(name, position, scene) {
  44158. _super.call(this, name, position, scene);
  44159. this._quaternionCache = new BABYLON.Quaternion();
  44160. this.inputs.addDeviceOrientation();
  44161. }
  44162. DeviceOrientationCamera.prototype.getTypeName = function () {
  44163. return "DeviceOrientationCamera";
  44164. };
  44165. DeviceOrientationCamera.prototype._checkInputs = function () {
  44166. _super.prototype._checkInputs.call(this);
  44167. this._quaternionCache.copyFrom(this.rotationQuaternion);
  44168. if (this._initialQuaternion) {
  44169. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  44170. }
  44171. };
  44172. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  44173. var _this = this;
  44174. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  44175. //can only work if this camera has a rotation quaternion already.
  44176. if (!this.rotationQuaternion)
  44177. return;
  44178. if (!this._initialQuaternion) {
  44179. this._initialQuaternion = new BABYLON.Quaternion();
  44180. }
  44181. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  44182. ['x', 'y', 'z'].forEach(function (axisName) {
  44183. if (!axis[axisName]) {
  44184. _this._initialQuaternion[axisName] = 0;
  44185. }
  44186. else {
  44187. _this._initialQuaternion[axisName] *= -1;
  44188. }
  44189. });
  44190. this._initialQuaternion.normalize();
  44191. //force rotation update
  44192. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  44193. };
  44194. return DeviceOrientationCamera;
  44195. }(BABYLON.FreeCamera));
  44196. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  44197. })(BABYLON || (BABYLON = {}));
  44198. var BABYLON;
  44199. (function (BABYLON) {
  44200. var VRDeviceOrientationFreeCamera = (function (_super) {
  44201. __extends(VRDeviceOrientationFreeCamera, _super);
  44202. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  44203. if (compensateDistortion === void 0) { compensateDistortion = true; }
  44204. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  44205. _super.call(this, name, position, scene);
  44206. vrCameraMetrics.compensateDistortion = compensateDistortion;
  44207. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  44208. }
  44209. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  44210. return "VRDeviceOrientationFreeCamera";
  44211. };
  44212. return VRDeviceOrientationFreeCamera;
  44213. }(BABYLON.DeviceOrientationCamera));
  44214. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  44215. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  44216. __extends(VRDeviceOrientationArcRotateCamera, _super);
  44217. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  44218. if (compensateDistortion === void 0) { compensateDistortion = true; }
  44219. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  44220. _super.call(this, name, alpha, beta, radius, target, scene);
  44221. vrCameraMetrics.compensateDistortion = compensateDistortion;
  44222. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  44223. this.inputs.addVRDeviceOrientation();
  44224. }
  44225. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  44226. return "VRDeviceOrientationArcRotateCamera";
  44227. };
  44228. return VRDeviceOrientationArcRotateCamera;
  44229. }(BABYLON.ArcRotateCamera));
  44230. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  44231. })(BABYLON || (BABYLON = {}));
  44232. var BABYLON;
  44233. (function (BABYLON) {
  44234. // We're mainly based on the logic defined into the FreeCamera code
  44235. var UniversalCamera = (function (_super) {
  44236. __extends(UniversalCamera, _super);
  44237. //-- end properties for backward compatibility for inputs
  44238. function UniversalCamera(name, position, scene) {
  44239. _super.call(this, name, position, scene);
  44240. this.inputs.addGamepad();
  44241. }
  44242. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  44243. //-- Begin properties for backward compatibility for inputs
  44244. get: function () {
  44245. var gamepad = this.inputs.attached["gamepad"];
  44246. if (gamepad)
  44247. return gamepad.gamepadAngularSensibility;
  44248. },
  44249. set: function (value) {
  44250. var gamepad = this.inputs.attached["gamepad"];
  44251. if (gamepad)
  44252. gamepad.gamepadAngularSensibility = value;
  44253. },
  44254. enumerable: true,
  44255. configurable: true
  44256. });
  44257. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  44258. get: function () {
  44259. var gamepad = this.inputs.attached["gamepad"];
  44260. if (gamepad)
  44261. return gamepad.gamepadMoveSensibility;
  44262. },
  44263. set: function (value) {
  44264. var gamepad = this.inputs.attached["gamepad"];
  44265. if (gamepad)
  44266. gamepad.gamepadMoveSensibility = value;
  44267. },
  44268. enumerable: true,
  44269. configurable: true
  44270. });
  44271. UniversalCamera.prototype.getTypeName = function () {
  44272. return "UniversalCamera";
  44273. };
  44274. return UniversalCamera;
  44275. }(BABYLON.TouchCamera));
  44276. BABYLON.UniversalCamera = UniversalCamera;
  44277. })(BABYLON || (BABYLON = {}));
  44278. var BABYLON;
  44279. (function (BABYLON) {
  44280. var Gamepads = (function () {
  44281. function Gamepads(ongamedpadconnected) {
  44282. var _this = this;
  44283. this.babylonGamepads = [];
  44284. this.oneGamepadConnected = false;
  44285. this.isMonitoring = false;
  44286. this.gamepadEventSupported = 'GamepadEvent' in window;
  44287. this.gamepadSupportAvailable = (navigator.getGamepads ||
  44288. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  44289. this._callbackGamepadConnected = ongamedpadconnected;
  44290. if (this.gamepadSupportAvailable) {
  44291. // Checking if the gamepad connected event is supported (like in Firefox)
  44292. if (this.gamepadEventSupported) {
  44293. this._onGamepadConnectedEvent = function (evt) {
  44294. _this._onGamepadConnected(evt);
  44295. };
  44296. this._onGamepadDisonnectedEvent = function (evt) {
  44297. _this._onGamepadDisconnected(evt);
  44298. };
  44299. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44300. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44301. }
  44302. else {
  44303. this._startMonitoringGamepads();
  44304. }
  44305. }
  44306. }
  44307. Gamepads.prototype.dispose = function () {
  44308. if (Gamepads.gamepadDOMInfo) {
  44309. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44310. }
  44311. if (this._onGamepadConnectedEvent) {
  44312. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44313. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44314. this._onGamepadConnectedEvent = null;
  44315. this._onGamepadDisonnectedEvent = null;
  44316. }
  44317. };
  44318. Gamepads.prototype._onGamepadConnected = function (evt) {
  44319. var newGamepad = this._addNewGamepad(evt.gamepad);
  44320. if (this._callbackGamepadConnected)
  44321. this._callbackGamepadConnected(newGamepad);
  44322. this._startMonitoringGamepads();
  44323. };
  44324. Gamepads.prototype._addNewGamepad = function (gamepad) {
  44325. if (!this.oneGamepadConnected) {
  44326. this.oneGamepadConnected = true;
  44327. if (Gamepads.gamepadDOMInfo) {
  44328. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44329. Gamepads.gamepadDOMInfo = null;
  44330. }
  44331. }
  44332. var newGamepad;
  44333. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  44334. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  44335. }
  44336. else {
  44337. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  44338. }
  44339. this.babylonGamepads.push(newGamepad);
  44340. return newGamepad;
  44341. };
  44342. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  44343. // Remove the gamepad from the list of gamepads to monitor.
  44344. for (var i in this.babylonGamepads) {
  44345. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  44346. this.babylonGamepads.splice(+i, 1);
  44347. break;
  44348. }
  44349. }
  44350. // If no gamepads are left, stop the polling loop.
  44351. if (this.babylonGamepads.length == 0) {
  44352. this._stopMonitoringGamepads();
  44353. }
  44354. };
  44355. Gamepads.prototype._startMonitoringGamepads = function () {
  44356. if (!this.isMonitoring) {
  44357. this.isMonitoring = true;
  44358. this._checkGamepadsStatus();
  44359. }
  44360. };
  44361. Gamepads.prototype._stopMonitoringGamepads = function () {
  44362. this.isMonitoring = false;
  44363. };
  44364. Gamepads.prototype._checkGamepadsStatus = function () {
  44365. var _this = this;
  44366. // updating gamepad objects
  44367. this._updateGamepadObjects();
  44368. for (var i in this.babylonGamepads) {
  44369. this.babylonGamepads[i].update();
  44370. }
  44371. if (this.isMonitoring) {
  44372. if (window.requestAnimationFrame) {
  44373. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44374. }
  44375. else if (window.mozRequestAnimationFrame) {
  44376. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44377. }
  44378. else if (window.webkitRequestAnimationFrame) {
  44379. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44380. }
  44381. }
  44382. };
  44383. // This function is called only on Chrome, which does not yet support
  44384. // connection/disconnection events, but requires you to monitor
  44385. // an array for changes.
  44386. Gamepads.prototype._updateGamepadObjects = function () {
  44387. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  44388. for (var i = 0; i < gamepads.length; i++) {
  44389. if (gamepads[i]) {
  44390. if (!(gamepads[i].index in this.babylonGamepads)) {
  44391. var newGamepad = this._addNewGamepad(gamepads[i]);
  44392. if (this._callbackGamepadConnected) {
  44393. this._callbackGamepadConnected(newGamepad);
  44394. }
  44395. }
  44396. else {
  44397. this.babylonGamepads[i].browserGamepad = gamepads[i];
  44398. }
  44399. }
  44400. }
  44401. };
  44402. return Gamepads;
  44403. }());
  44404. BABYLON.Gamepads = Gamepads;
  44405. var StickValues = (function () {
  44406. function StickValues(x, y) {
  44407. this.x = x;
  44408. this.y = y;
  44409. }
  44410. return StickValues;
  44411. }());
  44412. BABYLON.StickValues = StickValues;
  44413. var Gamepad = (function () {
  44414. function Gamepad(id, index, browserGamepad) {
  44415. this.id = id;
  44416. this.index = index;
  44417. this.browserGamepad = browserGamepad;
  44418. if (this.browserGamepad.axes.length >= 2) {
  44419. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  44420. }
  44421. if (this.browserGamepad.axes.length >= 4) {
  44422. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  44423. }
  44424. }
  44425. Gamepad.prototype.onleftstickchanged = function (callback) {
  44426. this._onleftstickchanged = callback;
  44427. };
  44428. Gamepad.prototype.onrightstickchanged = function (callback) {
  44429. this._onrightstickchanged = callback;
  44430. };
  44431. Object.defineProperty(Gamepad.prototype, "leftStick", {
  44432. get: function () {
  44433. return this._leftStick;
  44434. },
  44435. set: function (newValues) {
  44436. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  44437. this._onleftstickchanged(newValues);
  44438. }
  44439. this._leftStick = newValues;
  44440. },
  44441. enumerable: true,
  44442. configurable: true
  44443. });
  44444. Object.defineProperty(Gamepad.prototype, "rightStick", {
  44445. get: function () {
  44446. return this._rightStick;
  44447. },
  44448. set: function (newValues) {
  44449. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  44450. this._onrightstickchanged(newValues);
  44451. }
  44452. this._rightStick = newValues;
  44453. },
  44454. enumerable: true,
  44455. configurable: true
  44456. });
  44457. Gamepad.prototype.update = function () {
  44458. if (this._leftStick) {
  44459. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  44460. }
  44461. if (this._rightStick) {
  44462. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  44463. }
  44464. };
  44465. return Gamepad;
  44466. }());
  44467. BABYLON.Gamepad = Gamepad;
  44468. var GenericPad = (function (_super) {
  44469. __extends(GenericPad, _super);
  44470. function GenericPad(id, index, gamepad) {
  44471. _super.call(this, id, index, gamepad);
  44472. this.id = id;
  44473. this.index = index;
  44474. this.gamepad = gamepad;
  44475. this._buttons = new Array(gamepad.buttons.length);
  44476. }
  44477. GenericPad.prototype.onbuttondown = function (callback) {
  44478. this._onbuttondown = callback;
  44479. };
  44480. GenericPad.prototype.onbuttonup = function (callback) {
  44481. this._onbuttonup = callback;
  44482. };
  44483. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  44484. if (newValue !== currentValue) {
  44485. if (this._onbuttondown && newValue === 1) {
  44486. this._onbuttondown(buttonIndex);
  44487. }
  44488. if (this._onbuttonup && newValue === 0) {
  44489. this._onbuttonup(buttonIndex);
  44490. }
  44491. }
  44492. return newValue;
  44493. };
  44494. GenericPad.prototype.update = function () {
  44495. _super.prototype.update.call(this);
  44496. for (var index = 0; index < this._buttons.length; index++) {
  44497. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  44498. }
  44499. };
  44500. return GenericPad;
  44501. }(Gamepad));
  44502. BABYLON.GenericPad = GenericPad;
  44503. (function (Xbox360Button) {
  44504. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  44505. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  44506. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  44507. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  44508. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  44509. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  44510. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  44511. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  44512. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  44513. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  44514. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  44515. var Xbox360Button = BABYLON.Xbox360Button;
  44516. (function (Xbox360Dpad) {
  44517. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  44518. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  44519. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  44520. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  44521. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  44522. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  44523. var Xbox360Pad = (function (_super) {
  44524. __extends(Xbox360Pad, _super);
  44525. function Xbox360Pad() {
  44526. _super.apply(this, arguments);
  44527. this._leftTrigger = 0;
  44528. this._rightTrigger = 0;
  44529. this._buttonA = 0;
  44530. this._buttonB = 0;
  44531. this._buttonX = 0;
  44532. this._buttonY = 0;
  44533. this._buttonBack = 0;
  44534. this._buttonStart = 0;
  44535. this._buttonLB = 0;
  44536. this._buttonRB = 0;
  44537. this._buttonLeftStick = 0;
  44538. this._buttonRightStick = 0;
  44539. this._dPadUp = 0;
  44540. this._dPadDown = 0;
  44541. this._dPadLeft = 0;
  44542. this._dPadRight = 0;
  44543. }
  44544. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  44545. this._onlefttriggerchanged = callback;
  44546. };
  44547. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  44548. this._onrighttriggerchanged = callback;
  44549. };
  44550. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  44551. get: function () {
  44552. return this._leftTrigger;
  44553. },
  44554. set: function (newValue) {
  44555. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  44556. this._onlefttriggerchanged(newValue);
  44557. }
  44558. this._leftTrigger = newValue;
  44559. },
  44560. enumerable: true,
  44561. configurable: true
  44562. });
  44563. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  44564. get: function () {
  44565. return this._rightTrigger;
  44566. },
  44567. set: function (newValue) {
  44568. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  44569. this._onrighttriggerchanged(newValue);
  44570. }
  44571. this._rightTrigger = newValue;
  44572. },
  44573. enumerable: true,
  44574. configurable: true
  44575. });
  44576. Xbox360Pad.prototype.onbuttondown = function (callback) {
  44577. this._onbuttondown = callback;
  44578. };
  44579. Xbox360Pad.prototype.onbuttonup = function (callback) {
  44580. this._onbuttonup = callback;
  44581. };
  44582. Xbox360Pad.prototype.ondpaddown = function (callback) {
  44583. this._ondpaddown = callback;
  44584. };
  44585. Xbox360Pad.prototype.ondpadup = function (callback) {
  44586. this._ondpadup = callback;
  44587. };
  44588. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  44589. if (newValue !== currentValue) {
  44590. if (this._onbuttondown && newValue === 1) {
  44591. this._onbuttondown(buttonType);
  44592. }
  44593. if (this._onbuttonup && newValue === 0) {
  44594. this._onbuttonup(buttonType);
  44595. }
  44596. }
  44597. return newValue;
  44598. };
  44599. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  44600. if (newValue !== currentValue) {
  44601. if (this._ondpaddown && newValue === 1) {
  44602. this._ondpaddown(buttonType);
  44603. }
  44604. if (this._ondpadup && newValue === 0) {
  44605. this._ondpadup(buttonType);
  44606. }
  44607. }
  44608. return newValue;
  44609. };
  44610. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  44611. get: function () {
  44612. return this._buttonA;
  44613. },
  44614. set: function (value) {
  44615. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  44616. },
  44617. enumerable: true,
  44618. configurable: true
  44619. });
  44620. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  44621. get: function () {
  44622. return this._buttonB;
  44623. },
  44624. set: function (value) {
  44625. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  44626. },
  44627. enumerable: true,
  44628. configurable: true
  44629. });
  44630. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  44631. get: function () {
  44632. return this._buttonX;
  44633. },
  44634. set: function (value) {
  44635. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  44636. },
  44637. enumerable: true,
  44638. configurable: true
  44639. });
  44640. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  44641. get: function () {
  44642. return this._buttonY;
  44643. },
  44644. set: function (value) {
  44645. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  44646. },
  44647. enumerable: true,
  44648. configurable: true
  44649. });
  44650. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  44651. get: function () {
  44652. return this._buttonStart;
  44653. },
  44654. set: function (value) {
  44655. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  44656. },
  44657. enumerable: true,
  44658. configurable: true
  44659. });
  44660. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  44661. get: function () {
  44662. return this._buttonBack;
  44663. },
  44664. set: function (value) {
  44665. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  44666. },
  44667. enumerable: true,
  44668. configurable: true
  44669. });
  44670. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  44671. get: function () {
  44672. return this._buttonLB;
  44673. },
  44674. set: function (value) {
  44675. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  44676. },
  44677. enumerable: true,
  44678. configurable: true
  44679. });
  44680. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  44681. get: function () {
  44682. return this._buttonRB;
  44683. },
  44684. set: function (value) {
  44685. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  44686. },
  44687. enumerable: true,
  44688. configurable: true
  44689. });
  44690. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  44691. get: function () {
  44692. return this._buttonLeftStick;
  44693. },
  44694. set: function (value) {
  44695. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  44696. },
  44697. enumerable: true,
  44698. configurable: true
  44699. });
  44700. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  44701. get: function () {
  44702. return this._buttonRightStick;
  44703. },
  44704. set: function (value) {
  44705. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  44706. },
  44707. enumerable: true,
  44708. configurable: true
  44709. });
  44710. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  44711. get: function () {
  44712. return this._dPadUp;
  44713. },
  44714. set: function (value) {
  44715. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  44716. },
  44717. enumerable: true,
  44718. configurable: true
  44719. });
  44720. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  44721. get: function () {
  44722. return this._dPadDown;
  44723. },
  44724. set: function (value) {
  44725. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  44726. },
  44727. enumerable: true,
  44728. configurable: true
  44729. });
  44730. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  44731. get: function () {
  44732. return this._dPadLeft;
  44733. },
  44734. set: function (value) {
  44735. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  44736. },
  44737. enumerable: true,
  44738. configurable: true
  44739. });
  44740. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  44741. get: function () {
  44742. return this._dPadRight;
  44743. },
  44744. set: function (value) {
  44745. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  44746. },
  44747. enumerable: true,
  44748. configurable: true
  44749. });
  44750. Xbox360Pad.prototype.update = function () {
  44751. _super.prototype.update.call(this);
  44752. this.buttonA = this.browserGamepad.buttons[0].value;
  44753. this.buttonB = this.browserGamepad.buttons[1].value;
  44754. this.buttonX = this.browserGamepad.buttons[2].value;
  44755. this.buttonY = this.browserGamepad.buttons[3].value;
  44756. this.buttonLB = this.browserGamepad.buttons[4].value;
  44757. this.buttonRB = this.browserGamepad.buttons[5].value;
  44758. this.leftTrigger = this.browserGamepad.buttons[6].value;
  44759. this.rightTrigger = this.browserGamepad.buttons[7].value;
  44760. this.buttonBack = this.browserGamepad.buttons[8].value;
  44761. this.buttonStart = this.browserGamepad.buttons[9].value;
  44762. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  44763. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  44764. this.dPadUp = this.browserGamepad.buttons[12].value;
  44765. this.dPadDown = this.browserGamepad.buttons[13].value;
  44766. this.dPadLeft = this.browserGamepad.buttons[14].value;
  44767. this.dPadRight = this.browserGamepad.buttons[15].value;
  44768. };
  44769. return Xbox360Pad;
  44770. }(Gamepad));
  44771. BABYLON.Xbox360Pad = Xbox360Pad;
  44772. })(BABYLON || (BABYLON = {}));
  44773. var BABYLON;
  44774. (function (BABYLON) {
  44775. // We're mainly based on the logic defined into the FreeCamera code
  44776. var GamepadCamera = (function (_super) {
  44777. __extends(GamepadCamera, _super);
  44778. //-- end properties for backward compatibility for inputs
  44779. function GamepadCamera(name, position, scene) {
  44780. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  44781. _super.call(this, name, position, scene);
  44782. }
  44783. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  44784. //-- Begin properties for backward compatibility for inputs
  44785. get: function () {
  44786. var gamepad = this.inputs.attached["gamepad"];
  44787. if (gamepad)
  44788. return gamepad.gamepadAngularSensibility;
  44789. },
  44790. set: function (value) {
  44791. var gamepad = this.inputs.attached["gamepad"];
  44792. if (gamepad)
  44793. gamepad.gamepadAngularSensibility = value;
  44794. },
  44795. enumerable: true,
  44796. configurable: true
  44797. });
  44798. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  44799. get: function () {
  44800. var gamepad = this.inputs.attached["gamepad"];
  44801. if (gamepad)
  44802. return gamepad.gamepadMoveSensibility;
  44803. },
  44804. set: function (value) {
  44805. var gamepad = this.inputs.attached["gamepad"];
  44806. if (gamepad)
  44807. gamepad.gamepadMoveSensibility = value;
  44808. },
  44809. enumerable: true,
  44810. configurable: true
  44811. });
  44812. GamepadCamera.prototype.getTypeName = function () {
  44813. return "GamepadCamera";
  44814. };
  44815. return GamepadCamera;
  44816. }(BABYLON.UniversalCamera));
  44817. BABYLON.GamepadCamera = GamepadCamera;
  44818. })(BABYLON || (BABYLON = {}));
  44819. var BABYLON;
  44820. (function (BABYLON) {
  44821. var Analyser = (function () {
  44822. function Analyser(scene) {
  44823. this.SMOOTHING = 0.75;
  44824. this.FFT_SIZE = 512;
  44825. this.BARGRAPHAMPLITUDE = 256;
  44826. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  44827. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  44828. this._scene = scene;
  44829. this._audioEngine = BABYLON.Engine.audioEngine;
  44830. if (this._audioEngine.canUseWebAudio) {
  44831. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  44832. this._webAudioAnalyser.minDecibels = -140;
  44833. this._webAudioAnalyser.maxDecibels = 0;
  44834. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44835. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44836. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  44837. }
  44838. }
  44839. Analyser.prototype.getFrequencyBinCount = function () {
  44840. if (this._audioEngine.canUseWebAudio) {
  44841. return this._webAudioAnalyser.frequencyBinCount;
  44842. }
  44843. else {
  44844. return 0;
  44845. }
  44846. };
  44847. Analyser.prototype.getByteFrequencyData = function () {
  44848. if (this._audioEngine.canUseWebAudio) {
  44849. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44850. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44851. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  44852. }
  44853. return this._byteFreqs;
  44854. };
  44855. Analyser.prototype.getByteTimeDomainData = function () {
  44856. if (this._audioEngine.canUseWebAudio) {
  44857. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44858. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44859. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  44860. }
  44861. return this._byteTime;
  44862. };
  44863. Analyser.prototype.getFloatFrequencyData = function () {
  44864. if (this._audioEngine.canUseWebAudio) {
  44865. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44866. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44867. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  44868. }
  44869. return this._floatFreqs;
  44870. };
  44871. Analyser.prototype.drawDebugCanvas = function () {
  44872. var _this = this;
  44873. if (this._audioEngine.canUseWebAudio) {
  44874. if (!this._debugCanvas) {
  44875. this._debugCanvas = document.createElement("canvas");
  44876. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  44877. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  44878. this._debugCanvas.style.position = "absolute";
  44879. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  44880. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  44881. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  44882. document.body.appendChild(this._debugCanvas);
  44883. this._registerFunc = function () {
  44884. _this.drawDebugCanvas();
  44885. };
  44886. this._scene.registerBeforeRender(this._registerFunc);
  44887. }
  44888. if (this._registerFunc) {
  44889. var workingArray = this.getByteFrequencyData();
  44890. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  44891. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  44892. // Draw the frequency domain chart.
  44893. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  44894. var value = workingArray[i];
  44895. var percent = value / this.BARGRAPHAMPLITUDE;
  44896. var height = this.DEBUGCANVASSIZE.height * percent;
  44897. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  44898. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  44899. var hue = i / this.getFrequencyBinCount() * 360;
  44900. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  44901. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  44902. }
  44903. }
  44904. }
  44905. };
  44906. Analyser.prototype.stopDebugCanvas = function () {
  44907. if (this._debugCanvas) {
  44908. this._scene.unregisterBeforeRender(this._registerFunc);
  44909. this._registerFunc = null;
  44910. document.body.removeChild(this._debugCanvas);
  44911. this._debugCanvas = null;
  44912. this._debugCanvasContext = null;
  44913. }
  44914. };
  44915. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  44916. if (this._audioEngine.canUseWebAudio) {
  44917. inputAudioNode.connect(this._webAudioAnalyser);
  44918. this._webAudioAnalyser.connect(outputAudioNode);
  44919. }
  44920. };
  44921. Analyser.prototype.dispose = function () {
  44922. if (this._audioEngine.canUseWebAudio) {
  44923. this._webAudioAnalyser.disconnect();
  44924. }
  44925. };
  44926. return Analyser;
  44927. }());
  44928. BABYLON.Analyser = Analyser;
  44929. })(BABYLON || (BABYLON = {}));
  44930. var BABYLON;
  44931. (function (BABYLON) {
  44932. var DepthRenderer = (function () {
  44933. function DepthRenderer(scene, type) {
  44934. var _this = this;
  44935. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  44936. this._viewMatrix = BABYLON.Matrix.Zero();
  44937. this._projectionMatrix = BABYLON.Matrix.Zero();
  44938. this._transformMatrix = BABYLON.Matrix.Zero();
  44939. this._worldViewProjection = BABYLON.Matrix.Zero();
  44940. this._scene = scene;
  44941. var engine = scene.getEngine();
  44942. // Render target
  44943. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  44944. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44945. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44946. this._depthMap.refreshRate = 1;
  44947. this._depthMap.renderParticles = false;
  44948. this._depthMap.renderList = null;
  44949. // set default depth value to 1.0 (far away)
  44950. this._depthMap.onClearObservable.add(function (engine) {
  44951. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  44952. });
  44953. // Custom render function
  44954. var renderSubMesh = function (subMesh) {
  44955. var mesh = subMesh.getRenderingMesh();
  44956. var scene = _this._scene;
  44957. var engine = scene.getEngine();
  44958. // Culling
  44959. engine.setState(subMesh.getMaterial().backFaceCulling);
  44960. // Managing instances
  44961. var batch = mesh._getInstancesRenderList(subMesh._id);
  44962. if (batch.mustReturn) {
  44963. return;
  44964. }
  44965. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  44966. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  44967. engine.enableEffect(_this._effect);
  44968. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  44969. var material = subMesh.getMaterial();
  44970. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44971. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  44972. // Alpha test
  44973. if (material && material.needAlphaTesting()) {
  44974. var alphaTexture = material.getAlphaTestTexture();
  44975. _this._effect.setTexture("diffuseSampler", alphaTexture);
  44976. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44977. }
  44978. // Bones
  44979. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44980. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44981. }
  44982. // Draw
  44983. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  44984. }
  44985. };
  44986. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  44987. var index;
  44988. for (index = 0; index < opaqueSubMeshes.length; index++) {
  44989. renderSubMesh(opaqueSubMeshes.data[index]);
  44990. }
  44991. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  44992. renderSubMesh(alphaTestSubMeshes.data[index]);
  44993. }
  44994. };
  44995. }
  44996. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  44997. var material = subMesh.getMaterial();
  44998. if (material.disableDepthWrite) {
  44999. return false;
  45000. }
  45001. var defines = [];
  45002. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45003. var mesh = subMesh.getMesh();
  45004. var scene = mesh.getScene();
  45005. // Alpha test
  45006. if (material && material.needAlphaTesting()) {
  45007. defines.push("#define ALPHATEST");
  45008. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45009. attribs.push(BABYLON.VertexBuffer.UVKind);
  45010. defines.push("#define UV1");
  45011. }
  45012. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45013. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45014. defines.push("#define UV2");
  45015. }
  45016. }
  45017. // Bones
  45018. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45019. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45020. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45021. if (mesh.numBoneInfluencers > 4) {
  45022. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45023. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45024. }
  45025. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45026. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45027. }
  45028. else {
  45029. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45030. }
  45031. // Instances
  45032. if (useInstances) {
  45033. defines.push("#define INSTANCES");
  45034. attribs.push("world0");
  45035. attribs.push("world1");
  45036. attribs.push("world2");
  45037. attribs.push("world3");
  45038. }
  45039. // Get correct effect
  45040. var join = defines.join("\n");
  45041. if (this._cachedDefines !== join) {
  45042. this._cachedDefines = join;
  45043. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  45044. }
  45045. return this._effect.isReady();
  45046. };
  45047. DepthRenderer.prototype.getDepthMap = function () {
  45048. return this._depthMap;
  45049. };
  45050. // Methods
  45051. DepthRenderer.prototype.dispose = function () {
  45052. this._depthMap.dispose();
  45053. };
  45054. return DepthRenderer;
  45055. }());
  45056. BABYLON.DepthRenderer = DepthRenderer;
  45057. })(BABYLON || (BABYLON = {}));
  45058. var BABYLON;
  45059. (function (BABYLON) {
  45060. var SSAORenderingPipeline = (function (_super) {
  45061. __extends(SSAORenderingPipeline, _super);
  45062. /**
  45063. * @constructor
  45064. * @param {string} name - The rendering pipeline name
  45065. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  45066. * @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 }
  45067. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  45068. */
  45069. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  45070. var _this = this;
  45071. _super.call(this, scene.getEngine(), name);
  45072. // Members
  45073. /**
  45074. * The PassPostProcess id in the pipeline that contains the original scene color
  45075. * @type {string}
  45076. */
  45077. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  45078. /**
  45079. * The SSAO PostProcess id in the pipeline
  45080. * @type {string}
  45081. */
  45082. this.SSAORenderEffect = "SSAORenderEffect";
  45083. /**
  45084. * The horizontal blur PostProcess id in the pipeline
  45085. * @type {string}
  45086. */
  45087. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  45088. /**
  45089. * The vertical blur PostProcess id in the pipeline
  45090. * @type {string}
  45091. */
  45092. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  45093. /**
  45094. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  45095. * @type {string}
  45096. */
  45097. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  45098. /**
  45099. * The output strength of the SSAO post-process. Default value is 1.0.
  45100. * @type {number}
  45101. */
  45102. this.totalStrength = 1.0;
  45103. /**
  45104. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  45105. * @type {number}
  45106. */
  45107. this.radius = 0.0001;
  45108. /**
  45109. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  45110. * Must not be equal to fallOff and superior to fallOff.
  45111. * Default value is 0.975
  45112. * @type {number}
  45113. */
  45114. this.area = 0.0075;
  45115. /**
  45116. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  45117. * Must not be equal to area and inferior to area.
  45118. * Default value is 0.0
  45119. * @type {number}
  45120. */
  45121. this.fallOff = 0.000001;
  45122. /**
  45123. * The base color of the SSAO post-process
  45124. * The final result is "base + ssao" between [0, 1]
  45125. * @type {number}
  45126. */
  45127. this.base = 0.5;
  45128. this._firstUpdate = true;
  45129. this._scene = scene;
  45130. // Set up assets
  45131. this._createRandomTexture();
  45132. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  45133. var ssaoRatio = ratio.ssaoRatio || ratio;
  45134. var combineRatio = ratio.combineRatio || ratio;
  45135. this._ratio = {
  45136. ssaoRatio: ssaoRatio,
  45137. combineRatio: combineRatio
  45138. };
  45139. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45140. this._createSSAOPostProcess(ssaoRatio);
  45141. this._createBlurPostProcess(ssaoRatio);
  45142. this._createSSAOCombinePostProcess(combineRatio);
  45143. // Set up pipeline
  45144. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  45145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  45146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  45147. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  45148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  45149. // Finish
  45150. scene.postProcessRenderPipelineManager.addPipeline(this);
  45151. if (cameras)
  45152. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  45153. }
  45154. // Public Methods
  45155. /**
  45156. * Returns the horizontal blur PostProcess
  45157. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  45158. */
  45159. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  45160. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  45161. return null;
  45162. };
  45163. /**
  45164. * Returns the vertical blur PostProcess
  45165. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  45166. */
  45167. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  45168. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  45169. return null;
  45170. };
  45171. /**
  45172. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  45173. */
  45174. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  45175. if (disableDepthRender === void 0) { disableDepthRender = false; }
  45176. for (var i = 0; i < this._scene.cameras.length; i++) {
  45177. var camera = this._scene.cameras[i];
  45178. this._originalColorPostProcess.dispose(camera);
  45179. this._ssaoPostProcess.dispose(camera);
  45180. this._blurHPostProcess.dispose(camera);
  45181. this._blurVPostProcess.dispose(camera);
  45182. this._ssaoCombinePostProcess.dispose(camera);
  45183. }
  45184. this._randomTexture.dispose();
  45185. if (disableDepthRender)
  45186. this._scene.disableDepthRenderer();
  45187. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  45188. };
  45189. // Private Methods
  45190. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  45191. var _this = this;
  45192. /*
  45193. var samplerOffsets = [
  45194. -8.0, -6.0, -4.0, -2.0,
  45195. 0.0,
  45196. 2.0, 4.0, 6.0, 8.0
  45197. ];
  45198. */
  45199. var samples = 16;
  45200. var samplerOffsets = [];
  45201. for (var i = -8; i < 8; i++) {
  45202. samplerOffsets.push(i * 2);
  45203. }
  45204. 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");
  45205. this._blurHPostProcess.onApply = function (effect) {
  45206. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  45207. effect.setTexture("depthSampler", _this._depthTexture);
  45208. if (_this._firstUpdate) {
  45209. effect.setArray("samplerOffsets", samplerOffsets);
  45210. }
  45211. };
  45212. 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");
  45213. this._blurVPostProcess.onApply = function (effect) {
  45214. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  45215. effect.setTexture("depthSampler", _this._depthTexture);
  45216. if (_this._firstUpdate) {
  45217. effect.setArray("samplerOffsets", samplerOffsets);
  45218. _this._firstUpdate = false;
  45219. }
  45220. };
  45221. };
  45222. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  45223. var _this = this;
  45224. var numSamples = 16;
  45225. var sampleSphere = [
  45226. 0.5381, 0.1856, -0.4319,
  45227. 0.1379, 0.2486, 0.4430,
  45228. 0.3371, 0.5679, -0.0057,
  45229. -0.6999, -0.0451, -0.0019,
  45230. 0.0689, -0.1598, -0.8547,
  45231. 0.0560, 0.0069, -0.1843,
  45232. -0.0146, 0.1402, 0.0762,
  45233. 0.0100, -0.1924, -0.0344,
  45234. -0.3577, -0.5301, -0.4358,
  45235. -0.3169, 0.1063, 0.0158,
  45236. 0.0103, -0.5869, 0.0046,
  45237. -0.0897, -0.4940, 0.3287,
  45238. 0.7119, -0.0154, -0.0918,
  45239. -0.0533, 0.0596, -0.5411,
  45240. 0.0352, -0.0631, 0.5460,
  45241. -0.4776, 0.2847, -0.0271
  45242. ];
  45243. var samplesFactor = 1.0 / numSamples;
  45244. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  45245. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  45246. "area", "fallOff", "base", "range", "viewport"
  45247. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  45248. var viewport = new BABYLON.Vector2(0, 0);
  45249. this._ssaoPostProcess.onApply = function (effect) {
  45250. if (_this._firstUpdate) {
  45251. effect.setArray3("sampleSphere", sampleSphere);
  45252. effect.setFloat("samplesFactor", samplesFactor);
  45253. effect.setFloat("randTextureTiles", 4.0);
  45254. }
  45255. effect.setFloat("totalStrength", _this.totalStrength);
  45256. effect.setFloat("radius", _this.radius);
  45257. effect.setFloat("area", _this.area);
  45258. effect.setFloat("fallOff", _this.fallOff);
  45259. effect.setFloat("base", _this.base);
  45260. effect.setTexture("textureSampler", _this._depthTexture);
  45261. effect.setTexture("randomSampler", _this._randomTexture);
  45262. };
  45263. };
  45264. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  45265. var _this = this;
  45266. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  45267. this._ssaoCombinePostProcess.onApply = function (effect) {
  45268. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  45269. };
  45270. };
  45271. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  45272. var size = 512;
  45273. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  45274. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  45275. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  45276. var context = this._randomTexture.getContext();
  45277. var rand = function (min, max) {
  45278. return Math.random() * (max - min) + min;
  45279. };
  45280. var randVector = BABYLON.Vector3.Zero();
  45281. for (var x = 0; x < size; x++) {
  45282. for (var y = 0; y < size; y++) {
  45283. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  45284. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  45285. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  45286. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  45287. context.fillRect(x, y, 1, 1);
  45288. }
  45289. }
  45290. this._randomTexture.update(false);
  45291. };
  45292. __decorate([
  45293. BABYLON.serialize()
  45294. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  45295. __decorate([
  45296. BABYLON.serialize()
  45297. ], SSAORenderingPipeline.prototype, "radius", void 0);
  45298. __decorate([
  45299. BABYLON.serialize()
  45300. ], SSAORenderingPipeline.prototype, "area", void 0);
  45301. __decorate([
  45302. BABYLON.serialize()
  45303. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  45304. __decorate([
  45305. BABYLON.serialize()
  45306. ], SSAORenderingPipeline.prototype, "base", void 0);
  45307. __decorate([
  45308. BABYLON.serialize()
  45309. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  45310. return SSAORenderingPipeline;
  45311. }(BABYLON.PostProcessRenderPipeline));
  45312. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  45313. })(BABYLON || (BABYLON = {}));
  45314. var BABYLON;
  45315. (function (BABYLON) {
  45316. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  45317. var VolumetricLightScatteringPostProcess = (function (_super) {
  45318. __extends(VolumetricLightScatteringPostProcess, _super);
  45319. /**
  45320. * @constructor
  45321. * @param {string} name - The post-process name
  45322. * @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)
  45323. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  45324. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  45325. * @param {number} samples - The post-process quality, default 100
  45326. * @param {number} samplingMode - The post-process filtering mode
  45327. * @param {BABYLON.Engine} engine - The babylon engine
  45328. * @param {boolean} reusable - If the post-process is reusable
  45329. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  45330. */
  45331. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  45332. var _this = this;
  45333. if (samples === void 0) { samples = 100; }
  45334. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45335. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  45336. this._screenCoordinates = BABYLON.Vector2.Zero();
  45337. /**
  45338. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  45339. * @type {Vector3}
  45340. */
  45341. this.customMeshPosition = BABYLON.Vector3.Zero();
  45342. /**
  45343. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  45344. * @type {boolean}
  45345. */
  45346. this.useCustomMeshPosition = false;
  45347. /**
  45348. * If the post-process should inverse the light scattering direction
  45349. * @type {boolean}
  45350. */
  45351. this.invert = true;
  45352. /**
  45353. * Array containing the excluded meshes not rendered in the internal pass
  45354. */
  45355. this.excludedMeshes = new Array();
  45356. /**
  45357. * Controls the overall intensity of the post-process
  45358. * @type {number}
  45359. */
  45360. this.exposure = 0.3;
  45361. /**
  45362. * Dissipates each sample's contribution in range [0, 1]
  45363. * @type {number}
  45364. */
  45365. this.decay = 0.96815;
  45366. /**
  45367. * Controls the overall intensity of each sample
  45368. * @type {number}
  45369. */
  45370. this.weight = 0.58767;
  45371. /**
  45372. * Controls the density of each sample
  45373. * @type {number}
  45374. */
  45375. this.density = 0.926;
  45376. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  45377. var engine = scene.getEngine();
  45378. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  45379. // Configure mesh
  45380. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  45381. // Configure
  45382. this._createPass(scene, ratio.passRatio || ratio);
  45383. this.onActivate = function (camera) {
  45384. if (!_this.isSupported) {
  45385. _this.dispose(camera);
  45386. }
  45387. _this.onActivate = null;
  45388. };
  45389. this.onApplyObservable.add(function (effect) {
  45390. _this._updateMeshScreenCoordinates(scene);
  45391. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  45392. effect.setFloat("exposure", _this.exposure);
  45393. effect.setFloat("decay", _this.decay);
  45394. effect.setFloat("weight", _this.weight);
  45395. effect.setFloat("density", _this.density);
  45396. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  45397. });
  45398. }
  45399. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  45400. get: function () {
  45401. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  45402. return false;
  45403. },
  45404. set: function (useDiffuseColor) {
  45405. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  45406. },
  45407. enumerable: true,
  45408. configurable: true
  45409. });
  45410. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  45411. var mesh = subMesh.getMesh();
  45412. // Render this.mesh as default
  45413. if (mesh === this.mesh) {
  45414. return mesh.material.isReady(mesh);
  45415. }
  45416. var defines = [];
  45417. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45418. var material = subMesh.getMaterial();
  45419. var needUV = false;
  45420. // Alpha test
  45421. if (material) {
  45422. if (material.needAlphaTesting()) {
  45423. defines.push("#define ALPHATEST");
  45424. }
  45425. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45426. attribs.push(BABYLON.VertexBuffer.UVKind);
  45427. defines.push("#define UV1");
  45428. }
  45429. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45430. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45431. defines.push("#define UV2");
  45432. }
  45433. }
  45434. // Bones
  45435. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45436. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45437. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45438. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45439. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45440. }
  45441. else {
  45442. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45443. }
  45444. // Instances
  45445. if (useInstances) {
  45446. defines.push("#define INSTANCES");
  45447. attribs.push("world0");
  45448. attribs.push("world1");
  45449. attribs.push("world2");
  45450. attribs.push("world3");
  45451. }
  45452. // Get correct effect
  45453. var join = defines.join("\n");
  45454. if (this._cachedDefines !== join) {
  45455. this._cachedDefines = join;
  45456. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  45457. }
  45458. return this._volumetricLightScatteringPass.isReady();
  45459. };
  45460. /**
  45461. * Sets the new light position for light scattering effect
  45462. * @param {BABYLON.Vector3} The new custom light position
  45463. */
  45464. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  45465. this.customMeshPosition = position;
  45466. };
  45467. /**
  45468. * Returns the light position for light scattering effect
  45469. * @return {BABYLON.Vector3} The custom light position
  45470. */
  45471. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  45472. return this.customMeshPosition;
  45473. };
  45474. /**
  45475. * Disposes the internal assets and detaches the post-process from the camera
  45476. */
  45477. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  45478. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  45479. if (rttIndex !== -1) {
  45480. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  45481. }
  45482. this._volumetricLightScatteringRTT.dispose();
  45483. _super.prototype.dispose.call(this, camera);
  45484. };
  45485. /**
  45486. * Returns the render target texture used by the post-process
  45487. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  45488. */
  45489. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  45490. return this._volumetricLightScatteringRTT;
  45491. };
  45492. // Private methods
  45493. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  45494. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  45495. return true;
  45496. }
  45497. return false;
  45498. };
  45499. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  45500. var _this = this;
  45501. var engine = scene.getEngine();
  45502. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  45503. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45504. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45505. this._volumetricLightScatteringRTT.renderList = null;
  45506. this._volumetricLightScatteringRTT.renderParticles = false;
  45507. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  45508. // Custom render function for submeshes
  45509. var renderSubMesh = function (subMesh) {
  45510. var mesh = subMesh.getRenderingMesh();
  45511. if (_this._meshExcluded(mesh)) {
  45512. return;
  45513. }
  45514. var scene = mesh.getScene();
  45515. var engine = scene.getEngine();
  45516. // Culling
  45517. engine.setState(subMesh.getMaterial().backFaceCulling);
  45518. // Managing instances
  45519. var batch = mesh._getInstancesRenderList(subMesh._id);
  45520. if (batch.mustReturn) {
  45521. return;
  45522. }
  45523. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  45524. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  45525. var effect = _this._volumetricLightScatteringPass;
  45526. if (mesh === _this.mesh) {
  45527. effect = subMesh.getMaterial().getEffect();
  45528. }
  45529. engine.enableEffect(effect);
  45530. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  45531. if (mesh === _this.mesh) {
  45532. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  45533. }
  45534. else {
  45535. var material = subMesh.getMaterial();
  45536. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  45537. // Alpha test
  45538. if (material && material.needAlphaTesting()) {
  45539. var alphaTexture = material.getAlphaTestTexture();
  45540. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  45541. if (alphaTexture) {
  45542. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45543. }
  45544. }
  45545. // Bones
  45546. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45547. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45548. }
  45549. }
  45550. // Draw
  45551. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  45552. }
  45553. };
  45554. // Render target texture callbacks
  45555. var savedSceneClearColor;
  45556. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  45557. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  45558. savedSceneClearColor = scene.clearColor;
  45559. scene.clearColor = sceneClearColor;
  45560. });
  45561. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  45562. scene.clearColor = savedSceneClearColor;
  45563. });
  45564. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  45565. var engine = scene.getEngine();
  45566. var index;
  45567. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45568. renderSubMesh(opaqueSubMeshes.data[index]);
  45569. }
  45570. engine.setAlphaTesting(true);
  45571. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45572. renderSubMesh(alphaTestSubMeshes.data[index]);
  45573. }
  45574. engine.setAlphaTesting(false);
  45575. if (transparentSubMeshes.length) {
  45576. // Sort sub meshes
  45577. for (index = 0; index < transparentSubMeshes.length; index++) {
  45578. var submesh = transparentSubMeshes.data[index];
  45579. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  45580. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  45581. }
  45582. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  45583. sortedArray.sort(function (a, b) {
  45584. // Alpha index first
  45585. if (a._alphaIndex > b._alphaIndex) {
  45586. return 1;
  45587. }
  45588. if (a._alphaIndex < b._alphaIndex) {
  45589. return -1;
  45590. }
  45591. // Then distance to camera
  45592. if (a._distanceToCamera < b._distanceToCamera) {
  45593. return 1;
  45594. }
  45595. if (a._distanceToCamera > b._distanceToCamera) {
  45596. return -1;
  45597. }
  45598. return 0;
  45599. });
  45600. // Render sub meshes
  45601. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45602. for (index = 0; index < sortedArray.length; index++) {
  45603. renderSubMesh(sortedArray[index]);
  45604. }
  45605. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45606. }
  45607. };
  45608. };
  45609. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  45610. var transform = scene.getTransformMatrix();
  45611. var meshPosition;
  45612. if (this.useCustomMeshPosition) {
  45613. meshPosition = this.customMeshPosition;
  45614. }
  45615. else if (this.attachedNode) {
  45616. meshPosition = this.attachedNode.position;
  45617. }
  45618. else {
  45619. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  45620. }
  45621. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  45622. this._screenCoordinates.x = pos.x / this._viewPort.width;
  45623. this._screenCoordinates.y = pos.y / this._viewPort.height;
  45624. if (this.invert)
  45625. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  45626. };
  45627. // Static methods
  45628. /**
  45629. * Creates a default mesh for the Volumeric Light Scattering post-process
  45630. * @param {string} The mesh name
  45631. * @param {BABYLON.Scene} The scene where to create the mesh
  45632. * @return {BABYLON.Mesh} the default mesh
  45633. */
  45634. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  45635. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  45636. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  45637. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  45638. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  45639. mesh.material = material;
  45640. return mesh;
  45641. };
  45642. __decorate([
  45643. BABYLON.serializeAsVector3()
  45644. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  45645. __decorate([
  45646. BABYLON.serialize()
  45647. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  45648. __decorate([
  45649. BABYLON.serialize()
  45650. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  45651. __decorate([
  45652. BABYLON.serializeAsMeshReference()
  45653. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  45654. __decorate([
  45655. BABYLON.serialize()
  45656. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  45657. __decorate([
  45658. BABYLON.serialize()
  45659. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  45660. __decorate([
  45661. BABYLON.serialize()
  45662. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  45663. __decorate([
  45664. BABYLON.serialize()
  45665. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  45666. __decorate([
  45667. BABYLON.serialize()
  45668. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  45669. return VolumetricLightScatteringPostProcess;
  45670. }(BABYLON.PostProcess));
  45671. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  45672. })(BABYLON || (BABYLON = {}));
  45673. // BABYLON.JS Chromatic Aberration GLSL Shader
  45674. // Author: Olivier Guyot
  45675. // Separates very slightly R, G and B colors on the edges of the screen
  45676. // Inspired by Francois Tarlier & Martins Upitis
  45677. var BABYLON;
  45678. (function (BABYLON) {
  45679. var LensRenderingPipeline = (function (_super) {
  45680. __extends(LensRenderingPipeline, _super);
  45681. /**
  45682. * @constructor
  45683. *
  45684. * Effect parameters are as follow:
  45685. * {
  45686. * chromatic_aberration: number; // from 0 to x (1 for realism)
  45687. * edge_blur: number; // from 0 to x (1 for realism)
  45688. * distortion: number; // from 0 to x (1 for realism)
  45689. * grain_amount: number; // from 0 to 1
  45690. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  45691. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  45692. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  45693. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  45694. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  45695. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  45696. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  45697. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  45698. * }
  45699. * Note: if an effect parameter is unset, effect is disabled
  45700. *
  45701. * @param {string} name - The rendering pipeline name
  45702. * @param {object} parameters - An object containing all parameters (see above)
  45703. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  45704. * @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)
  45705. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  45706. */
  45707. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  45708. var _this = this;
  45709. if (ratio === void 0) { ratio = 1.0; }
  45710. _super.call(this, scene.getEngine(), name);
  45711. // Lens effects can be of the following:
  45712. // - chromatic aberration (slight shift of RGB colors)
  45713. // - blur on the edge of the lens
  45714. // - lens distortion
  45715. // - depth-of-field blur & highlights enhancing
  45716. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  45717. // - grain effect (noise or custom texture)
  45718. // Two additional texture samplers are needed:
  45719. // - depth map (for depth-of-field)
  45720. // - grain texture
  45721. /**
  45722. * The chromatic aberration PostProcess id in the pipeline
  45723. * @type {string}
  45724. */
  45725. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  45726. /**
  45727. * The highlights enhancing PostProcess id in the pipeline
  45728. * @type {string}
  45729. */
  45730. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  45731. /**
  45732. * The depth-of-field PostProcess id in the pipeline
  45733. * @type {string}
  45734. */
  45735. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  45736. this._scene = scene;
  45737. // Fetch texture samplers
  45738. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  45739. if (parameters.grain_texture) {
  45740. this._grainTexture = parameters.grain_texture;
  45741. }
  45742. else {
  45743. this._createGrainTexture();
  45744. }
  45745. // save parameters
  45746. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  45747. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  45748. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  45749. this._distortion = parameters.distortion ? parameters.distortion : 0;
  45750. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  45751. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  45752. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  45753. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  45754. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  45755. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  45756. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  45757. // Create effects
  45758. this._createChromaticAberrationPostProcess(ratio);
  45759. this._createHighlightsPostProcess(ratio);
  45760. this._createDepthOfFieldPostProcess(ratio / 4);
  45761. // Set up pipeline
  45762. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  45763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  45764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  45765. if (this._highlightsGain === -1) {
  45766. this._disableEffect(this.HighlightsEnhancingEffect, null);
  45767. }
  45768. // Finish
  45769. scene.postProcessRenderPipelineManager.addPipeline(this);
  45770. if (cameras) {
  45771. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  45772. }
  45773. }
  45774. // public methods (self explanatory)
  45775. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  45776. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  45777. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  45778. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  45779. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  45780. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  45781. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  45782. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  45783. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  45784. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  45785. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  45786. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  45787. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  45788. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  45789. };
  45790. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  45791. this._highlightsPostProcess.updateEffect();
  45792. };
  45793. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  45794. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  45795. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  45796. this._highlightsGain = amount;
  45797. };
  45798. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  45799. if (this._highlightsGain === -1) {
  45800. this._highlightsGain = 1.0;
  45801. }
  45802. this._highlightsThreshold = amount;
  45803. };
  45804. LensRenderingPipeline.prototype.disableHighlights = function () {
  45805. this._highlightsGain = -1;
  45806. };
  45807. /**
  45808. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  45809. */
  45810. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  45811. if (disableDepthRender === void 0) { disableDepthRender = false; }
  45812. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  45813. this._chromaticAberrationPostProcess = undefined;
  45814. this._highlightsPostProcess = undefined;
  45815. this._depthOfFieldPostProcess = undefined;
  45816. this._grainTexture.dispose();
  45817. if (disableDepthRender)
  45818. this._scene.disableDepthRenderer();
  45819. };
  45820. // colors shifting and distortion
  45821. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  45822. var _this = this;
  45823. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  45824. [], // samplers
  45825. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  45826. this._chromaticAberrationPostProcess.onApply = function (effect) {
  45827. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  45828. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  45829. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  45830. };
  45831. };
  45832. // highlights enhancing
  45833. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  45834. var _this = this;
  45835. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  45836. [], // samplers
  45837. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  45838. this._highlightsPostProcess.onApply = function (effect) {
  45839. effect.setFloat('gain', _this._highlightsGain);
  45840. effect.setFloat('threshold', _this._highlightsThreshold);
  45841. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  45842. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  45843. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  45844. };
  45845. };
  45846. // colors shifting and distortion
  45847. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  45848. var _this = this;
  45849. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  45850. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  45851. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  45852. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  45853. this._depthOfFieldPostProcess.onApply = function (effect) {
  45854. effect.setTexture("depthSampler", _this._depthTexture);
  45855. effect.setTexture("grainSampler", _this._grainTexture);
  45856. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  45857. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  45858. effect.setFloat('grain_amount', _this._grainAmount);
  45859. effect.setBool('blur_noise', _this._blurNoise);
  45860. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  45861. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  45862. effect.setFloat('distortion', _this._distortion);
  45863. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  45864. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  45865. effect.setFloat('aperture', _this._dofAperture);
  45866. effect.setFloat('darken', _this._dofDarken);
  45867. effect.setFloat('edge_blur', _this._edgeBlur);
  45868. effect.setBool('highlights', (_this._highlightsGain !== -1));
  45869. effect.setFloat('near', _this._scene.activeCamera.minZ);
  45870. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  45871. };
  45872. };
  45873. // creates a black and white random noise texture, 512x512
  45874. LensRenderingPipeline.prototype._createGrainTexture = function () {
  45875. var size = 512;
  45876. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45877. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  45878. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  45879. var context = this._grainTexture.getContext();
  45880. var rand = function (min, max) {
  45881. return Math.random() * (max - min) + min;
  45882. };
  45883. var value;
  45884. for (var x = 0; x < size; x++) {
  45885. for (var y = 0; y < size; y++) {
  45886. value = Math.floor(rand(0.42, 0.58) * 255);
  45887. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  45888. context.fillRect(x, y, 1, 1);
  45889. }
  45890. }
  45891. this._grainTexture.update(false);
  45892. };
  45893. return LensRenderingPipeline;
  45894. }(BABYLON.PostProcessRenderPipeline));
  45895. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  45896. })(BABYLON || (BABYLON = {}));
  45897. //
  45898. // This post-process allows the modification of rendered colors by using
  45899. // a 'look-up table' (LUT). This effect is also called Color Grading.
  45900. //
  45901. // The object needs to be provided an url to a texture containing the color
  45902. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  45903. // Use an image editing software to tweak the LUT to match your needs.
  45904. //
  45905. // For an example of a color LUT, see here:
  45906. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  45907. // For explanations on color grading, see here:
  45908. // http://udn.epicgames.com/Three/ColorGrading.html
  45909. //
  45910. var BABYLON;
  45911. (function (BABYLON) {
  45912. var ColorCorrectionPostProcess = (function (_super) {
  45913. __extends(ColorCorrectionPostProcess, _super);
  45914. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  45915. var _this = this;
  45916. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  45917. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  45918. this._colorTableTexture.anisotropicFilteringLevel = 1;
  45919. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45920. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45921. this.onApply = function (effect) {
  45922. effect.setTexture("colorTable", _this._colorTableTexture);
  45923. };
  45924. }
  45925. return ColorCorrectionPostProcess;
  45926. }(BABYLON.PostProcess));
  45927. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  45928. })(BABYLON || (BABYLON = {}));
  45929. var BABYLON;
  45930. (function (BABYLON) {
  45931. var AnaglyphFreeCamera = (function (_super) {
  45932. __extends(AnaglyphFreeCamera, _super);
  45933. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  45934. _super.call(this, name, position, scene);
  45935. this.interaxialDistance = interaxialDistance;
  45936. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  45937. }
  45938. AnaglyphFreeCamera.prototype.getTypeName = function () {
  45939. return "AnaglyphFreeCamera";
  45940. };
  45941. return AnaglyphFreeCamera;
  45942. }(BABYLON.FreeCamera));
  45943. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  45944. var AnaglyphArcRotateCamera = (function (_super) {
  45945. __extends(AnaglyphArcRotateCamera, _super);
  45946. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  45947. _super.call(this, name, alpha, beta, radius, target, scene);
  45948. this.interaxialDistance = interaxialDistance;
  45949. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  45950. }
  45951. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  45952. return "AnaglyphArcRotateCamera";
  45953. };
  45954. return AnaglyphArcRotateCamera;
  45955. }(BABYLON.ArcRotateCamera));
  45956. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  45957. var AnaglyphGamepadCamera = (function (_super) {
  45958. __extends(AnaglyphGamepadCamera, _super);
  45959. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  45960. _super.call(this, name, position, scene);
  45961. this.interaxialDistance = interaxialDistance;
  45962. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  45963. }
  45964. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  45965. return "AnaglyphGamepadCamera";
  45966. };
  45967. return AnaglyphGamepadCamera;
  45968. }(BABYLON.GamepadCamera));
  45969. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  45970. var AnaglyphUniversalCamera = (function (_super) {
  45971. __extends(AnaglyphUniversalCamera, _super);
  45972. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  45973. _super.call(this, name, position, scene);
  45974. this.interaxialDistance = interaxialDistance;
  45975. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  45976. }
  45977. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  45978. return "AnaglyphUniversalCamera";
  45979. };
  45980. return AnaglyphUniversalCamera;
  45981. }(BABYLON.UniversalCamera));
  45982. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  45983. var StereoscopicFreeCamera = (function (_super) {
  45984. __extends(StereoscopicFreeCamera, _super);
  45985. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  45986. _super.call(this, name, position, scene);
  45987. this.interaxialDistance = interaxialDistance;
  45988. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  45989. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  45990. }
  45991. StereoscopicFreeCamera.prototype.getTypeName = function () {
  45992. return "StereoscopicFreeCamera";
  45993. };
  45994. return StereoscopicFreeCamera;
  45995. }(BABYLON.FreeCamera));
  45996. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  45997. var StereoscopicArcRotateCamera = (function (_super) {
  45998. __extends(StereoscopicArcRotateCamera, _super);
  45999. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  46000. _super.call(this, name, alpha, beta, radius, target, scene);
  46001. this.interaxialDistance = interaxialDistance;
  46002. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46003. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46004. }
  46005. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  46006. return "StereoscopicArcRotateCamera";
  46007. };
  46008. return StereoscopicArcRotateCamera;
  46009. }(BABYLON.ArcRotateCamera));
  46010. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  46011. var StereoscopicGamepadCamera = (function (_super) {
  46012. __extends(StereoscopicGamepadCamera, _super);
  46013. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46014. _super.call(this, name, position, scene);
  46015. this.interaxialDistance = interaxialDistance;
  46016. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46017. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46018. }
  46019. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  46020. return "StereoscopicGamepadCamera";
  46021. };
  46022. return StereoscopicGamepadCamera;
  46023. }(BABYLON.GamepadCamera));
  46024. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  46025. var StereoscopicUniversalCamera = (function (_super) {
  46026. __extends(StereoscopicUniversalCamera, _super);
  46027. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46028. _super.call(this, name, position, scene);
  46029. this.interaxialDistance = interaxialDistance;
  46030. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46031. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46032. }
  46033. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  46034. return "StereoscopicUniversalCamera";
  46035. };
  46036. return StereoscopicUniversalCamera;
  46037. }(BABYLON.UniversalCamera));
  46038. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  46039. })(BABYLON || (BABYLON = {}));
  46040. var BABYLON;
  46041. (function (BABYLON) {
  46042. var HDRRenderingPipeline = (function (_super) {
  46043. __extends(HDRRenderingPipeline, _super);
  46044. /**
  46045. * @constructor
  46046. * @param {string} name - The rendering pipeline name
  46047. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46048. * @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)
  46049. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  46050. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46051. */
  46052. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  46053. var _this = this;
  46054. if (originalPostProcess === void 0) { originalPostProcess = null; }
  46055. _super.call(this, scene.getEngine(), name);
  46056. /**
  46057. * Public members
  46058. */
  46059. // Gaussian Blur
  46060. /**
  46061. * Gaussian blur coefficient
  46062. * @type {number}
  46063. */
  46064. this.gaussCoeff = 0.3;
  46065. /**
  46066. * Gaussian blur mean
  46067. * @type {number}
  46068. */
  46069. this.gaussMean = 1.0;
  46070. /**
  46071. * Gaussian blur standard deviation
  46072. * @type {number}
  46073. */
  46074. this.gaussStandDev = 0.8;
  46075. /**
  46076. * Gaussian blur multiplier. Multiplies the blur effect
  46077. * @type {number}
  46078. */
  46079. this.gaussMultiplier = 4.0;
  46080. // HDR
  46081. /**
  46082. * Exposure, controls the overall intensity of the pipeline
  46083. * @type {number}
  46084. */
  46085. this.exposure = 1.0;
  46086. /**
  46087. * Minimum luminance that the post-process can output. Luminance is >= 0
  46088. * @type {number}
  46089. */
  46090. this.minimumLuminance = 1.0;
  46091. /**
  46092. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  46093. * @type {number}
  46094. */
  46095. this.maximumLuminance = 1e20;
  46096. /**
  46097. * Increase rate for luminance: eye adaptation speed to dark
  46098. * @type {number}
  46099. */
  46100. this.luminanceIncreaserate = 0.5;
  46101. /**
  46102. * Decrease rate for luminance: eye adaptation speed to bright
  46103. * @type {number}
  46104. */
  46105. this.luminanceDecreaseRate = 0.5;
  46106. // Bright pass
  46107. /**
  46108. * Minimum luminance needed to compute HDR
  46109. * @type {number}
  46110. */
  46111. this.brightThreshold = 0.8;
  46112. this._needUpdate = true;
  46113. this._scene = scene;
  46114. // Bright pass
  46115. this._createBrightPassPostProcess(scene, ratio);
  46116. // Down sample X4
  46117. this._createDownSampleX4PostProcess(scene, ratio);
  46118. // Create gaussian blur post-processes
  46119. this._createGaussianBlurPostProcess(scene, ratio);
  46120. // Texture adder
  46121. this._createTextureAdderPostProcess(scene, ratio);
  46122. // Luminance generator
  46123. this._createLuminanceGeneratorPostProcess(scene);
  46124. // HDR
  46125. this._createHDRPostProcess(scene, ratio);
  46126. // Pass postprocess
  46127. if (originalPostProcess === null) {
  46128. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46129. }
  46130. else {
  46131. this._originalPostProcess = originalPostProcess;
  46132. }
  46133. // Configure pipeline
  46134. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  46135. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  46136. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  46137. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  46138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  46139. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  46140. var addDownSamplerPostProcess = function (id) {
  46141. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  46142. };
  46143. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46144. addDownSamplerPostProcess(i);
  46145. }
  46146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  46147. // Finish
  46148. scene.postProcessRenderPipelineManager.addPipeline(this);
  46149. if (cameras !== null) {
  46150. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46151. }
  46152. this.update();
  46153. }
  46154. /**
  46155. * Tells the pipeline to update its post-processes
  46156. */
  46157. HDRRenderingPipeline.prototype.update = function () {
  46158. this._needUpdate = true;
  46159. };
  46160. /**
  46161. * Returns the current calculated luminance
  46162. */
  46163. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  46164. return this._hdrCurrentLuminance;
  46165. };
  46166. /**
  46167. * Returns the currently drawn luminance
  46168. */
  46169. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  46170. return this._hdrOutputLuminance;
  46171. };
  46172. /**
  46173. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  46174. */
  46175. HDRRenderingPipeline.prototype.dispose = function () {
  46176. this._originalPostProcess = undefined;
  46177. this._brightPassPostProcess = undefined;
  46178. this._downSampleX4PostProcess = undefined;
  46179. this._guassianBlurHPostProcess = undefined;
  46180. this._guassianBlurVPostProcess = undefined;
  46181. this._textureAdderPostProcess = undefined;
  46182. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46183. this._downSamplePostProcesses[i] = undefined;
  46184. }
  46185. this._hdrPostProcess = undefined;
  46186. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46187. };
  46188. /**
  46189. * Creates the HDR post-process and computes the luminance adaptation
  46190. */
  46191. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  46192. var _this = this;
  46193. var hdrLastLuminance = 0.0;
  46194. this._hdrOutputLuminance = -1.0;
  46195. this._hdrCurrentLuminance = 1.0;
  46196. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  46197. this._hdrPostProcess.onApply = function (effect) {
  46198. if (_this._hdrOutputLuminance < 0.0) {
  46199. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46200. }
  46201. else {
  46202. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  46203. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  46204. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  46205. }
  46206. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  46207. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  46208. }
  46209. else {
  46210. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46211. }
  46212. }
  46213. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  46214. hdrLastLuminance += scene.getEngine().getDeltaTime();
  46215. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46216. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46217. effect.setFloat("exposure", _this.exposure);
  46218. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  46219. _this._needUpdate = false;
  46220. };
  46221. };
  46222. /**
  46223. * Texture Adder post-process
  46224. */
  46225. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  46226. var _this = this;
  46227. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  46228. this._textureAdderPostProcess.onApply = function (effect) {
  46229. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46230. };
  46231. };
  46232. /**
  46233. * Down sample X4 post-process
  46234. */
  46235. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  46236. var _this = this;
  46237. var downSampleX4Offsets = new Array(32);
  46238. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  46239. this._downSampleX4PostProcess.onApply = function (effect) {
  46240. if (_this._needUpdate) {
  46241. var id = 0;
  46242. for (var i = -2; i < 2; i++) {
  46243. for (var j = -2; j < 2; j++) {
  46244. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  46245. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  46246. id += 2;
  46247. }
  46248. }
  46249. }
  46250. effect.setArray2("dsOffsets", downSampleX4Offsets);
  46251. };
  46252. };
  46253. /**
  46254. * Bright pass post-process
  46255. */
  46256. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  46257. var _this = this;
  46258. var brightOffsets = new Array(8);
  46259. var brightPassCallback = function (effect) {
  46260. if (_this._needUpdate) {
  46261. var sU = (1.0 / _this._brightPassPostProcess.width);
  46262. var sV = (1.0 / _this._brightPassPostProcess.height);
  46263. brightOffsets[0] = -0.5 * sU;
  46264. brightOffsets[1] = 0.5 * sV;
  46265. brightOffsets[2] = 0.5 * sU;
  46266. brightOffsets[3] = 0.5 * sV;
  46267. brightOffsets[4] = -0.5 * sU;
  46268. brightOffsets[5] = -0.5 * sV;
  46269. brightOffsets[6] = 0.5 * sU;
  46270. brightOffsets[7] = -0.5 * sV;
  46271. }
  46272. effect.setArray2("dsOffsets", brightOffsets);
  46273. effect.setFloat("brightThreshold", _this.brightThreshold);
  46274. };
  46275. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  46276. this._brightPassPostProcess.onApply = brightPassCallback;
  46277. };
  46278. /**
  46279. * Luminance generator. Creates the luminance post-process and down sample post-processes
  46280. */
  46281. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  46282. var _this = this;
  46283. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  46284. var luminanceOffsets = new Array(8);
  46285. var downSampleOffsets = new Array(18);
  46286. var halfDestPixelSize;
  46287. this._downSamplePostProcesses = new Array(lumSteps);
  46288. // Utils for luminance
  46289. var luminanceUpdateSourceOffsets = function (width, height) {
  46290. var sU = (1.0 / width);
  46291. var sV = (1.0 / height);
  46292. luminanceOffsets[0] = -0.5 * sU;
  46293. luminanceOffsets[1] = 0.5 * sV;
  46294. luminanceOffsets[2] = 0.5 * sU;
  46295. luminanceOffsets[3] = 0.5 * sV;
  46296. luminanceOffsets[4] = -0.5 * sU;
  46297. luminanceOffsets[5] = -0.5 * sV;
  46298. luminanceOffsets[6] = 0.5 * sU;
  46299. luminanceOffsets[7] = -0.5 * sV;
  46300. };
  46301. var luminanceUpdateDestOffsets = function (width, height) {
  46302. var id = 0;
  46303. for (var x = -1; x < 2; x++) {
  46304. for (var y = -1; y < 2; y++) {
  46305. downSampleOffsets[id] = (x) / width;
  46306. downSampleOffsets[id + 1] = (y) / height;
  46307. id += 2;
  46308. }
  46309. }
  46310. };
  46311. // Luminance callback
  46312. var luminanceCallback = function (effect) {
  46313. if (_this._needUpdate) {
  46314. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  46315. }
  46316. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46317. effect.setArray2("lumOffsets", luminanceOffsets);
  46318. };
  46319. // Down sample callbacks
  46320. var downSampleCallback = function (indice) {
  46321. var i = indice;
  46322. return function (effect) {
  46323. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46324. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46325. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  46326. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  46327. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  46328. effect.setArray2("dsOffsets", downSampleOffsets);
  46329. };
  46330. };
  46331. var downSampleAfterRenderCallback = function (effect) {
  46332. // Unpack result
  46333. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  46334. 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);
  46335. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  46336. };
  46337. // Create luminance post-process
  46338. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  46339. 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);
  46340. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  46341. // Create down sample post-processes
  46342. for (var i = lumSteps - 2; i >= 0; i--) {
  46343. var length = Math.pow(3, i);
  46344. ratio = { width: length, height: length };
  46345. var defines = "#define DOWN_SAMPLE\n";
  46346. if (i === 0) {
  46347. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  46348. }
  46349. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  46350. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  46351. if (i === 0) {
  46352. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  46353. }
  46354. }
  46355. };
  46356. /**
  46357. * Gaussian blur post-processes. Horizontal and Vertical
  46358. */
  46359. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  46360. var _this = this;
  46361. var blurOffsetsW = new Array(9);
  46362. var blurOffsetsH = new Array(9);
  46363. var blurWeights = new Array(9);
  46364. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  46365. // Utils for gaussian blur
  46366. var calculateBlurOffsets = function (height) {
  46367. var lastOutputDimensions = {
  46368. width: scene.getEngine().getRenderWidth(),
  46369. height: scene.getEngine().getRenderHeight()
  46370. };
  46371. for (var i = 0; i < 9; i++) {
  46372. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  46373. if (height) {
  46374. blurOffsetsH[i] = value;
  46375. }
  46376. else {
  46377. blurOffsetsW[i] = value;
  46378. }
  46379. }
  46380. };
  46381. var calculateWeights = function () {
  46382. var x = 0.0;
  46383. for (var i = 0; i < 9; i++) {
  46384. x = (i - 4.0) / 4.0;
  46385. 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));
  46386. }
  46387. };
  46388. // Callback
  46389. var gaussianBlurCallback = function (height) {
  46390. return function (effect) {
  46391. if (_this._needUpdate) {
  46392. calculateWeights();
  46393. calculateBlurOffsets(height);
  46394. }
  46395. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  46396. effect.setArray("blurWeights", blurWeights);
  46397. effect.setFloat("multiplier", _this.gaussMultiplier);
  46398. };
  46399. };
  46400. // Create horizontal gaussian blur post-processes
  46401. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  46402. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  46403. // Create vertical gaussian blur post-process
  46404. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  46405. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  46406. };
  46407. // Luminance generator
  46408. HDRRenderingPipeline.LUM_STEPS = 6;
  46409. return HDRRenderingPipeline;
  46410. }(BABYLON.PostProcessRenderPipeline));
  46411. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  46412. })(BABYLON || (BABYLON = {}));
  46413. var BABYLON;
  46414. (function (BABYLON) {
  46415. var FaceAdjacencies = (function () {
  46416. function FaceAdjacencies() {
  46417. this.edges = new Array();
  46418. this.edgesConnectedCount = 0;
  46419. }
  46420. return FaceAdjacencies;
  46421. }());
  46422. var EdgesRenderer = (function () {
  46423. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  46424. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  46425. if (epsilon === void 0) { epsilon = 0.95; }
  46426. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  46427. this.edgesWidthScalerForOrthographic = 1000.0;
  46428. this.edgesWidthScalerForPerspective = 50.0;
  46429. this._linesPositions = new Array();
  46430. this._linesNormals = new Array();
  46431. this._linesIndices = new Array();
  46432. this._buffers = {};
  46433. this._checkVerticesInsteadOfIndices = false;
  46434. this._source = source;
  46435. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  46436. this._epsilon = epsilon;
  46437. this._prepareRessources();
  46438. this._generateEdgesLines();
  46439. }
  46440. EdgesRenderer.prototype._prepareRessources = function () {
  46441. if (this._lineShader) {
  46442. return;
  46443. }
  46444. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  46445. attributes: ["position", "normal"],
  46446. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  46447. });
  46448. this._lineShader.disableDepthWrite = true;
  46449. this._lineShader.backFaceCulling = false;
  46450. };
  46451. EdgesRenderer.prototype.dispose = function () {
  46452. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  46453. if (buffer) {
  46454. buffer.dispose();
  46455. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  46456. }
  46457. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  46458. if (buffer) {
  46459. buffer.dispose();
  46460. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  46461. }
  46462. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  46463. this._lineShader.dispose();
  46464. };
  46465. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  46466. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  46467. return 0;
  46468. }
  46469. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  46470. return 1;
  46471. }
  46472. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  46473. return 2;
  46474. }
  46475. return -1;
  46476. };
  46477. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  46478. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  46479. return 0;
  46480. }
  46481. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  46482. return 1;
  46483. }
  46484. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  46485. return 2;
  46486. }
  46487. return -1;
  46488. };
  46489. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  46490. var needToCreateLine;
  46491. if (edge === undefined) {
  46492. needToCreateLine = true;
  46493. }
  46494. else {
  46495. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  46496. needToCreateLine = dotProduct < this._epsilon;
  46497. }
  46498. if (needToCreateLine) {
  46499. var offset = this._linesPositions.length / 3;
  46500. var normal = p0.subtract(p1);
  46501. normal.normalize();
  46502. // Positions
  46503. this._linesPositions.push(p0.x);
  46504. this._linesPositions.push(p0.y);
  46505. this._linesPositions.push(p0.z);
  46506. this._linesPositions.push(p0.x);
  46507. this._linesPositions.push(p0.y);
  46508. this._linesPositions.push(p0.z);
  46509. this._linesPositions.push(p1.x);
  46510. this._linesPositions.push(p1.y);
  46511. this._linesPositions.push(p1.z);
  46512. this._linesPositions.push(p1.x);
  46513. this._linesPositions.push(p1.y);
  46514. this._linesPositions.push(p1.z);
  46515. // Normals
  46516. this._linesNormals.push(p1.x);
  46517. this._linesNormals.push(p1.y);
  46518. this._linesNormals.push(p1.z);
  46519. this._linesNormals.push(-1);
  46520. this._linesNormals.push(p1.x);
  46521. this._linesNormals.push(p1.y);
  46522. this._linesNormals.push(p1.z);
  46523. this._linesNormals.push(1);
  46524. this._linesNormals.push(p0.x);
  46525. this._linesNormals.push(p0.y);
  46526. this._linesNormals.push(p0.z);
  46527. this._linesNormals.push(-1);
  46528. this._linesNormals.push(p0.x);
  46529. this._linesNormals.push(p0.y);
  46530. this._linesNormals.push(p0.z);
  46531. this._linesNormals.push(1);
  46532. // Indices
  46533. this._linesIndices.push(offset);
  46534. this._linesIndices.push(offset + 1);
  46535. this._linesIndices.push(offset + 2);
  46536. this._linesIndices.push(offset);
  46537. this._linesIndices.push(offset + 2);
  46538. this._linesIndices.push(offset + 3);
  46539. }
  46540. };
  46541. EdgesRenderer.prototype._generateEdgesLines = function () {
  46542. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46543. var indices = this._source.getIndices();
  46544. // First let's find adjacencies
  46545. var adjacencies = new Array();
  46546. var faceNormals = new Array();
  46547. var index;
  46548. var faceAdjacencies;
  46549. // Prepare faces
  46550. for (index = 0; index < indices.length; index += 3) {
  46551. faceAdjacencies = new FaceAdjacencies();
  46552. var p0Index = indices[index];
  46553. var p1Index = indices[index + 1];
  46554. var p2Index = indices[index + 2];
  46555. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  46556. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  46557. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  46558. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  46559. faceNormal.normalize();
  46560. faceNormals.push(faceNormal);
  46561. adjacencies.push(faceAdjacencies);
  46562. }
  46563. // Scan
  46564. for (index = 0; index < adjacencies.length; index++) {
  46565. faceAdjacencies = adjacencies[index];
  46566. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  46567. var otherFaceAdjacencies = adjacencies[otherIndex];
  46568. if (faceAdjacencies.edgesConnectedCount === 3) {
  46569. break;
  46570. }
  46571. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  46572. continue;
  46573. }
  46574. var otherP0 = indices[otherIndex * 3];
  46575. var otherP1 = indices[otherIndex * 3 + 1];
  46576. var otherP2 = indices[otherIndex * 3 + 2];
  46577. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  46578. var otherEdgeIndex;
  46579. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  46580. continue;
  46581. }
  46582. switch (edgeIndex) {
  46583. case 0:
  46584. if (this._checkVerticesInsteadOfIndices) {
  46585. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  46586. }
  46587. else {
  46588. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  46589. }
  46590. break;
  46591. case 1:
  46592. if (this._checkVerticesInsteadOfIndices) {
  46593. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  46594. }
  46595. else {
  46596. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  46597. }
  46598. break;
  46599. case 2:
  46600. if (this._checkVerticesInsteadOfIndices) {
  46601. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  46602. }
  46603. else {
  46604. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  46605. }
  46606. break;
  46607. }
  46608. if (otherEdgeIndex === -1) {
  46609. continue;
  46610. }
  46611. faceAdjacencies.edges[edgeIndex] = otherIndex;
  46612. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  46613. faceAdjacencies.edgesConnectedCount++;
  46614. otherFaceAdjacencies.edgesConnectedCount++;
  46615. if (faceAdjacencies.edgesConnectedCount === 3) {
  46616. break;
  46617. }
  46618. }
  46619. }
  46620. }
  46621. // Create lines
  46622. for (index = 0; index < adjacencies.length; index++) {
  46623. // 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
  46624. var current = adjacencies[index];
  46625. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  46626. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  46627. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  46628. }
  46629. // Merge into a single mesh
  46630. var engine = this._source.getScene().getEngine();
  46631. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  46632. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  46633. this._ib = engine.createIndexBuffer(this._linesIndices);
  46634. this._indicesCount = this._linesIndices.length;
  46635. };
  46636. EdgesRenderer.prototype.render = function () {
  46637. if (!this._lineShader.isReady()) {
  46638. return;
  46639. }
  46640. var scene = this._source.getScene();
  46641. var engine = scene.getEngine();
  46642. this._lineShader._preBind();
  46643. // VBOs
  46644. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  46645. scene.resetCachedMaterial();
  46646. this._lineShader.setColor4("color", this._source.edgesColor);
  46647. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  46648. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  46649. }
  46650. else {
  46651. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  46652. }
  46653. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  46654. this._lineShader.bind(this._source.getWorldMatrix());
  46655. // Draw order
  46656. engine.draw(true, 0, this._indicesCount);
  46657. this._lineShader.unbind();
  46658. engine.setDepthWrite(true);
  46659. };
  46660. return EdgesRenderer;
  46661. }());
  46662. BABYLON.EdgesRenderer = EdgesRenderer;
  46663. })(BABYLON || (BABYLON = {}));
  46664. var BABYLON;
  46665. (function (BABYLON) {
  46666. (function (TonemappingOperator) {
  46667. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  46668. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  46669. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  46670. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  46671. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  46672. var TonemappingOperator = BABYLON.TonemappingOperator;
  46673. ;
  46674. var TonemapPostProcess = (function (_super) {
  46675. __extends(TonemapPostProcess, _super);
  46676. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  46677. var _this = this;
  46678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46679. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46680. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  46681. this._operator = _operator;
  46682. this.exposureAdjustment = exposureAdjustment;
  46683. var defines = "#define ";
  46684. if (this._operator === TonemappingOperator.Hable)
  46685. defines += "HABLE_TONEMAPPING";
  46686. else if (this._operator === TonemappingOperator.Reinhard)
  46687. defines += "REINHARD_TONEMAPPING";
  46688. else if (this._operator === TonemappingOperator.HejiDawson)
  46689. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  46690. else if (this._operator === TonemappingOperator.Photographic)
  46691. defines += "PHOTOGRAPHIC_TONEMAPPING";
  46692. //sadly a second call to create the effect.
  46693. this.updateEffect(defines);
  46694. this.onApply = function (effect) {
  46695. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  46696. };
  46697. }
  46698. return TonemapPostProcess;
  46699. }(BABYLON.PostProcess));
  46700. BABYLON.TonemapPostProcess = TonemapPostProcess;
  46701. })(BABYLON || (BABYLON = {}));
  46702. var BABYLON;
  46703. (function (BABYLON) {
  46704. var ReflectionProbe = (function () {
  46705. function ReflectionProbe(name, size, scene, generateMipMaps) {
  46706. var _this = this;
  46707. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46708. this.name = name;
  46709. this._viewMatrix = BABYLON.Matrix.Identity();
  46710. this._target = BABYLON.Vector3.Zero();
  46711. this._add = BABYLON.Vector3.Zero();
  46712. this.invertYAxis = false;
  46713. this.position = BABYLON.Vector3.Zero();
  46714. this._scene = scene;
  46715. this._scene.reflectionProbes.push(this);
  46716. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  46717. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  46718. switch (faceIndex) {
  46719. case 0:
  46720. _this._add.copyFromFloats(1, 0, 0);
  46721. break;
  46722. case 1:
  46723. _this._add.copyFromFloats(-1, 0, 0);
  46724. break;
  46725. case 2:
  46726. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  46727. break;
  46728. case 3:
  46729. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  46730. break;
  46731. case 4:
  46732. _this._add.copyFromFloats(0, 0, 1);
  46733. break;
  46734. case 5:
  46735. _this._add.copyFromFloats(0, 0, -1);
  46736. break;
  46737. }
  46738. if (_this._attachedMesh) {
  46739. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  46740. }
  46741. _this.position.addToRef(_this._add, _this._target);
  46742. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  46743. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  46744. });
  46745. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  46746. scene.updateTransformMatrix(true);
  46747. });
  46748. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  46749. }
  46750. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  46751. get: function () {
  46752. return this._renderTargetTexture.refreshRate;
  46753. },
  46754. set: function (value) {
  46755. this._renderTargetTexture.refreshRate = value;
  46756. },
  46757. enumerable: true,
  46758. configurable: true
  46759. });
  46760. ReflectionProbe.prototype.getScene = function () {
  46761. return this._scene;
  46762. };
  46763. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  46764. get: function () {
  46765. return this._renderTargetTexture;
  46766. },
  46767. enumerable: true,
  46768. configurable: true
  46769. });
  46770. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  46771. get: function () {
  46772. return this._renderTargetTexture.renderList;
  46773. },
  46774. enumerable: true,
  46775. configurable: true
  46776. });
  46777. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  46778. this._attachedMesh = mesh;
  46779. };
  46780. ReflectionProbe.prototype.dispose = function () {
  46781. var index = this._scene.reflectionProbes.indexOf(this);
  46782. if (index !== -1) {
  46783. // Remove from the scene if found
  46784. this._scene.reflectionProbes.splice(index, 1);
  46785. }
  46786. if (this._renderTargetTexture) {
  46787. this._renderTargetTexture.dispose();
  46788. this._renderTargetTexture = null;
  46789. }
  46790. };
  46791. return ReflectionProbe;
  46792. }());
  46793. BABYLON.ReflectionProbe = ReflectionProbe;
  46794. })(BABYLON || (BABYLON = {}));
  46795. var BABYLON;
  46796. (function (BABYLON) {
  46797. var SolidParticle = (function () {
  46798. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, modelBoundingInfo) {
  46799. this.idx = 0; // particle global index
  46800. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  46801. this.position = BABYLON.Vector3.Zero(); // position
  46802. this.rotation = BABYLON.Vector3.Zero(); // rotation
  46803. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  46804. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  46805. this.velocity = BABYLON.Vector3.Zero(); // velocity
  46806. this.alive = true; // alive
  46807. this.isVisible = true; // visibility
  46808. this._pos = 0; // index of this particle in the global "positions" array
  46809. this.shapeId = 0; // model shape id
  46810. this.idxInShape = 0; // index of the particle in its shape id
  46811. this.idx = particleIndex;
  46812. this._pos = positionIndex;
  46813. this._model = model;
  46814. this.shapeId = shapeId;
  46815. this.idxInShape = idxInShape;
  46816. if (modelBoundingInfo) {
  46817. this._modelBoundingInfo = modelBoundingInfo;
  46818. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  46819. }
  46820. }
  46821. Object.defineProperty(SolidParticle.prototype, "scale", {
  46822. //legacy support, changed scale to scaling
  46823. get: function () {
  46824. return this.scaling;
  46825. },
  46826. set: function (scale) {
  46827. this.scaling = scale;
  46828. },
  46829. enumerable: true,
  46830. configurable: true
  46831. });
  46832. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  46833. //legacy support, changed quaternion to rotationQuaternion
  46834. get: function () {
  46835. return this.rotationQuaternion;
  46836. },
  46837. set: function (q) {
  46838. this.rotationQuaternion = q;
  46839. },
  46840. enumerable: true,
  46841. configurable: true
  46842. });
  46843. SolidParticle.prototype.intersectsMesh = function (target) {
  46844. if (!this._boundingInfo || !target._boundingInfo) {
  46845. return false;
  46846. }
  46847. return this._boundingInfo.intersects(target._boundingInfo, false);
  46848. };
  46849. return SolidParticle;
  46850. }());
  46851. BABYLON.SolidParticle = SolidParticle;
  46852. var ModelShape = (function () {
  46853. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  46854. this.shapeID = id;
  46855. this._shape = shape;
  46856. this._shapeUV = shapeUV;
  46857. this._positionFunction = posFunction;
  46858. this._vertexFunction = vtxFunction;
  46859. }
  46860. return ModelShape;
  46861. }());
  46862. BABYLON.ModelShape = ModelShape;
  46863. })(BABYLON || (BABYLON = {}));
  46864. var BABYLON;
  46865. (function (BABYLON) {
  46866. /**
  46867. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  46868. */
  46869. var SolidParticleSystem = (function () {
  46870. /**
  46871. * Creates a SPS (Solid Particle System) object.
  46872. * `name` (String) is the SPS name, this will be the underlying mesh name.
  46873. * `scene` (Scene) is the scene in which the SPS is added.
  46874. * `updatable` (default true) : if the SPS must be updatable or immutable.
  46875. * `isPickable` (default false) : if the solid particles must be pickable.
  46876. * `particleIntersection` (default false) : if the solid particle intersections must be computed
  46877. */
  46878. function SolidParticleSystem(name, scene, options) {
  46879. // public members
  46880. /**
  46881. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  46882. * Example : var p = SPS.particles[i];
  46883. */
  46884. this.particles = new Array();
  46885. /**
  46886. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  46887. */
  46888. this.nbParticles = 0;
  46889. /**
  46890. * If the particles must ever face the camera (default false). Useful for planar particles.
  46891. */
  46892. this.billboard = false;
  46893. /**
  46894. * Recompute normals when adding a shape
  46895. */
  46896. this.recomputeNormals = true;
  46897. /**
  46898. * This a counter ofr your own usage. It's not set by any SPS functions.
  46899. */
  46900. this.counter = 0;
  46901. /**
  46902. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  46903. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  46904. */
  46905. this.vars = {};
  46906. this._positions = new Array();
  46907. this._indices = new Array();
  46908. this._normals = new Array();
  46909. this._colors = new Array();
  46910. this._uvs = new Array();
  46911. this._index = 0; // indices index
  46912. this._updatable = true;
  46913. this._pickable = false;
  46914. this._isVisibilityBoxLocked = false;
  46915. this._alwaysVisible = false;
  46916. this._shapeCounter = 0;
  46917. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  46918. this._color = new BABYLON.Color4(0, 0, 0, 0);
  46919. this._computeParticleColor = true;
  46920. this._computeParticleTexture = true;
  46921. this._computeParticleRotation = true;
  46922. this._computeParticleVertex = false;
  46923. this._computeBoundingBox = false;
  46924. this._cam_axisZ = BABYLON.Vector3.Zero();
  46925. this._cam_axisY = BABYLON.Vector3.Zero();
  46926. this._cam_axisX = BABYLON.Vector3.Zero();
  46927. this._axisX = BABYLON.Axis.X;
  46928. this._axisY = BABYLON.Axis.Y;
  46929. this._axisZ = BABYLON.Axis.Z;
  46930. this._camDir = BABYLON.Vector3.Zero();
  46931. this._rotMatrix = new BABYLON.Matrix();
  46932. this._invertMatrix = new BABYLON.Matrix();
  46933. this._rotated = BABYLON.Vector3.Zero();
  46934. this._quaternion = new BABYLON.Quaternion();
  46935. this._vertex = BABYLON.Vector3.Zero();
  46936. this._normal = BABYLON.Vector3.Zero();
  46937. this._yaw = 0.0;
  46938. this._pitch = 0.0;
  46939. this._roll = 0.0;
  46940. this._halfroll = 0.0;
  46941. this._halfpitch = 0.0;
  46942. this._halfyaw = 0.0;
  46943. this._sinRoll = 0.0;
  46944. this._cosRoll = 0.0;
  46945. this._sinPitch = 0.0;
  46946. this._cosPitch = 0.0;
  46947. this._sinYaw = 0.0;
  46948. this._cosYaw = 0.0;
  46949. this._w = 0.0;
  46950. this._minimum = BABYLON.Tmp.Vector3[0];
  46951. this._maximum = BABYLON.Tmp.Vector3[1];
  46952. this._scale = BABYLON.Tmp.Vector3[2];
  46953. this._translation = BABYLON.Tmp.Vector3[3];
  46954. this._particlesIntersect = false;
  46955. this.name = name;
  46956. this._scene = scene;
  46957. this._camera = scene.activeCamera;
  46958. this._pickable = options ? options.isPickable : false;
  46959. this._particlesIntersect = options ? options.particleIntersection : false;
  46960. if (options && options.updatable) {
  46961. this._updatable = options.updatable;
  46962. }
  46963. else {
  46964. this._updatable = true;
  46965. }
  46966. if (this._pickable) {
  46967. this.pickedParticles = [];
  46968. }
  46969. }
  46970. /**
  46971. * Builds the SPS underlying mesh. Returns a standard Mesh.
  46972. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  46973. */
  46974. SolidParticleSystem.prototype.buildMesh = function () {
  46975. if (this.nbParticles === 0) {
  46976. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  46977. this.addShape(triangle, 1);
  46978. triangle.dispose();
  46979. }
  46980. this._positions32 = new Float32Array(this._positions);
  46981. this._uvs32 = new Float32Array(this._uvs);
  46982. this._colors32 = new Float32Array(this._colors);
  46983. if (this.recomputeNormals) {
  46984. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  46985. }
  46986. this._normals32 = new Float32Array(this._normals);
  46987. this._fixedNormal32 = new Float32Array(this._normals);
  46988. var vertexData = new BABYLON.VertexData();
  46989. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  46990. vertexData.indices = this._indices;
  46991. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  46992. if (this._uvs32) {
  46993. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  46994. ;
  46995. }
  46996. if (this._colors32) {
  46997. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  46998. }
  46999. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47000. vertexData.applyToMesh(mesh, this._updatable);
  47001. this.mesh = mesh;
  47002. this.mesh.isPickable = this._pickable;
  47003. // free memory
  47004. this._positions = null;
  47005. this._normals = null;
  47006. this._uvs = null;
  47007. this._colors = null;
  47008. if (!this._updatable) {
  47009. this.particles.length = 0;
  47010. }
  47011. return mesh;
  47012. };
  47013. /**
  47014. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47015. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47016. * Thus the particles generated from `digest()` have their property `position` set yet.
  47017. * `mesh` ( Mesh ) is the mesh to be digested
  47018. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47019. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47020. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47021. */
  47022. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47023. var size = (options && options.facetNb) || 1;
  47024. var number = (options && options.number);
  47025. var delta = (options && options.delta) || 0;
  47026. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47027. var meshInd = mesh.getIndices();
  47028. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47029. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47030. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47031. var f = 0; // facet counter
  47032. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47033. // compute size from number
  47034. if (number) {
  47035. number = (number > totalFacets) ? totalFacets : number;
  47036. size = Math.round(totalFacets / number);
  47037. delta = 0;
  47038. }
  47039. else {
  47040. size = (size > totalFacets) ? totalFacets : size;
  47041. }
  47042. var facetPos = []; // submesh positions
  47043. var facetInd = []; // submesh indices
  47044. var facetUV = []; // submesh UV
  47045. var facetCol = []; // submesh colors
  47046. var barycenter = BABYLON.Tmp.Vector3[0];
  47047. var rand;
  47048. var sizeO = size;
  47049. while (f < totalFacets) {
  47050. size = sizeO + Math.floor((1 + delta) * Math.random());
  47051. if (f > totalFacets - size) {
  47052. size = totalFacets - f;
  47053. }
  47054. // reset temp arrays
  47055. facetPos.length = 0;
  47056. facetInd.length = 0;
  47057. facetUV.length = 0;
  47058. facetCol.length = 0;
  47059. // iterate over "size" facets
  47060. var fi = 0;
  47061. for (var j = f * 3; j < (f + size) * 3; j++) {
  47062. facetInd.push(fi);
  47063. var i = meshInd[j];
  47064. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47065. if (meshUV) {
  47066. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47067. }
  47068. if (meshCol) {
  47069. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47070. }
  47071. fi++;
  47072. }
  47073. // create a model shape for each single particle
  47074. var idx = this.nbParticles;
  47075. var shape = this._posToShape(facetPos);
  47076. var shapeUV = this._uvsToShapeUV(facetUV);
  47077. // compute the barycenter of the shape
  47078. var v;
  47079. for (v = 0; v < shape.length; v++) {
  47080. barycenter.addInPlace(shape[v]);
  47081. }
  47082. barycenter.scaleInPlace(1 / shape.length);
  47083. // shift the shape from its barycenter to the origin
  47084. for (v = 0; v < shape.length; v++) {
  47085. shape[v].subtractInPlace(barycenter);
  47086. }
  47087. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  47088. // add the particle in the SPS
  47089. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47090. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  47091. // initialize the particle position
  47092. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47093. this._index += shape.length;
  47094. idx++;
  47095. this.nbParticles++;
  47096. this._shapeCounter++;
  47097. f += size;
  47098. }
  47099. return this;
  47100. };
  47101. //reset copy
  47102. SolidParticleSystem.prototype._resetCopy = function () {
  47103. this._copy.position.x = 0;
  47104. this._copy.position.y = 0;
  47105. this._copy.position.z = 0;
  47106. this._copy.rotation.x = 0;
  47107. this._copy.rotation.y = 0;
  47108. this._copy.rotation.z = 0;
  47109. this._copy.rotationQuaternion = null;
  47110. this._copy.scaling.x = 1;
  47111. this._copy.scaling.y = 1;
  47112. this._copy.scaling.z = 1;
  47113. this._copy.uvs.x = 0;
  47114. this._copy.uvs.y = 0;
  47115. this._copy.uvs.z = 1;
  47116. this._copy.uvs.w = 1;
  47117. this._copy.color = null;
  47118. };
  47119. // _meshBuilder : inserts the shape model in the global SPS mesh
  47120. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47121. var i;
  47122. var u = 0;
  47123. var c = 0;
  47124. var n = 0;
  47125. this._resetCopy();
  47126. if (options && options.positionFunction) {
  47127. options.positionFunction(this._copy, idx, idxInShape);
  47128. }
  47129. if (this._copy.rotationQuaternion) {
  47130. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47131. }
  47132. else {
  47133. this._yaw = this._copy.rotation.y;
  47134. this._pitch = this._copy.rotation.x;
  47135. this._roll = this._copy.rotation.z;
  47136. this._quaternionRotationYPR();
  47137. }
  47138. this._quaternionToRotationMatrix();
  47139. for (i = 0; i < shape.length; i++) {
  47140. this._vertex.x = shape[i].x;
  47141. this._vertex.y = shape[i].y;
  47142. this._vertex.z = shape[i].z;
  47143. if (options && options.vertexFunction) {
  47144. options.vertexFunction(this._copy, this._vertex, i);
  47145. }
  47146. this._vertex.x *= this._copy.scaling.x;
  47147. this._vertex.y *= this._copy.scaling.y;
  47148. this._vertex.z *= this._copy.scaling.z;
  47149. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47150. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47151. if (meshUV) {
  47152. 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);
  47153. u += 2;
  47154. }
  47155. if (this._copy.color) {
  47156. this._color = this._copy.color;
  47157. }
  47158. else if (meshCol && meshCol[c] !== undefined) {
  47159. this._color.r = meshCol[c];
  47160. this._color.g = meshCol[c + 1];
  47161. this._color.b = meshCol[c + 2];
  47162. this._color.a = meshCol[c + 3];
  47163. }
  47164. else {
  47165. this._color.r = 1;
  47166. this._color.g = 1;
  47167. this._color.b = 1;
  47168. this._color.a = 1;
  47169. }
  47170. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47171. c += 4;
  47172. if (!this.recomputeNormals && meshNor) {
  47173. this._normal.x = meshNor[n];
  47174. this._normal.y = meshNor[n + 1];
  47175. this._normal.z = meshNor[n + 2];
  47176. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  47177. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47178. n += 3;
  47179. }
  47180. }
  47181. for (i = 0; i < meshInd.length; i++) {
  47182. indices.push(p + meshInd[i]);
  47183. }
  47184. if (this._pickable) {
  47185. var nbfaces = meshInd.length / 3;
  47186. for (i = 0; i < nbfaces; i++) {
  47187. this.pickedParticles.push({ idx: idx, faceId: i });
  47188. }
  47189. }
  47190. };
  47191. // returns a shape array from positions array
  47192. SolidParticleSystem.prototype._posToShape = function (positions) {
  47193. var shape = [];
  47194. for (var i = 0; i < positions.length; i += 3) {
  47195. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47196. }
  47197. return shape;
  47198. };
  47199. // returns a shapeUV array from a Vector4 uvs
  47200. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47201. var shapeUV = [];
  47202. if (uvs) {
  47203. for (var i = 0; i < uvs.length; i++)
  47204. shapeUV.push(uvs[i]);
  47205. }
  47206. return shapeUV;
  47207. };
  47208. // adds a new particle object in the particles array
  47209. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bbInfo) {
  47210. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, bbInfo));
  47211. };
  47212. /**
  47213. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47214. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47215. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47216. * `nb` (positive integer) the number of particles to be created from this model
  47217. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47218. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47219. */
  47220. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47221. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47222. var meshInd = mesh.getIndices();
  47223. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47224. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47225. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47226. var bbInfo;
  47227. if (this._particlesIntersect) {
  47228. bbInfo = mesh.getBoundingInfo();
  47229. }
  47230. var shape = this._posToShape(meshPos);
  47231. var shapeUV = this._uvsToShapeUV(meshUV);
  47232. var posfunc = options ? options.positionFunction : null;
  47233. var vtxfunc = options ? options.vertexFunction : null;
  47234. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  47235. // particles
  47236. var idx = this.nbParticles;
  47237. for (var i = 0; i < nb; i++) {
  47238. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47239. if (this._updatable) {
  47240. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  47241. }
  47242. this._index += shape.length;
  47243. idx++;
  47244. }
  47245. this.nbParticles += nb;
  47246. this._shapeCounter++;
  47247. return this._shapeCounter - 1;
  47248. };
  47249. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47250. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47251. this._resetCopy();
  47252. if (particle._model._positionFunction) {
  47253. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47254. }
  47255. if (this._copy.rotationQuaternion) {
  47256. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47257. }
  47258. else {
  47259. this._yaw = this._copy.rotation.y;
  47260. this._pitch = this._copy.rotation.x;
  47261. this._roll = this._copy.rotation.z;
  47262. this._quaternionRotationYPR();
  47263. }
  47264. this._quaternionToRotationMatrix();
  47265. this._shape = particle._model._shape;
  47266. for (var pt = 0; pt < this._shape.length; pt++) {
  47267. this._vertex.x = this._shape[pt].x;
  47268. this._vertex.y = this._shape[pt].y;
  47269. this._vertex.z = this._shape[pt].z;
  47270. if (particle._model._vertexFunction) {
  47271. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47272. }
  47273. this._vertex.x *= this._copy.scaling.x;
  47274. this._vertex.y *= this._copy.scaling.y;
  47275. this._vertex.z *= this._copy.scaling.z;
  47276. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47277. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47278. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47279. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47280. }
  47281. particle.position.x = 0.0;
  47282. particle.position.y = 0.0;
  47283. particle.position.z = 0.0;
  47284. particle.rotation.x = 0.0;
  47285. particle.rotation.y = 0.0;
  47286. particle.rotation.z = 0.0;
  47287. particle.rotationQuaternion = null;
  47288. particle.scaling.x = 1.0;
  47289. particle.scaling.y = 1.0;
  47290. particle.scaling.z = 1.0;
  47291. };
  47292. /**
  47293. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47294. */
  47295. SolidParticleSystem.prototype.rebuildMesh = function () {
  47296. for (var p = 0; p < this.particles.length; p++) {
  47297. this._rebuildParticle(this.particles[p]);
  47298. }
  47299. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47300. };
  47301. /**
  47302. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47303. * This method calls `updateParticle()` for each particle of the SPS.
  47304. * For an animated SPS, it is usually called within the render loop.
  47305. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47306. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47307. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47308. */
  47309. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47310. if (start === void 0) { start = 0; }
  47311. if (end === void 0) { end = this.nbParticles - 1; }
  47312. if (update === void 0) { update = true; }
  47313. if (!this._updatable) {
  47314. return;
  47315. }
  47316. // custom beforeUpdate
  47317. this.beforeUpdateParticles(start, end, update);
  47318. this._cam_axisX.x = 1.0;
  47319. this._cam_axisX.y = 0.0;
  47320. this._cam_axisX.z = 0.0;
  47321. this._cam_axisY.x = 0.0;
  47322. this._cam_axisY.y = 1.0;
  47323. this._cam_axisY.z = 0.0;
  47324. this._cam_axisZ.x = 0.0;
  47325. this._cam_axisZ.y = 0.0;
  47326. this._cam_axisZ.z = 1.0;
  47327. // if the particles will always face the camera
  47328. if (this.billboard) {
  47329. // compute the camera position and un-rotate it by the current mesh rotation
  47330. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  47331. this._quaternionToRotationMatrix();
  47332. this._rotMatrix.invertToRef(this._invertMatrix);
  47333. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  47334. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  47335. this._cam_axisZ.normalize();
  47336. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  47337. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  47338. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  47339. this._cam_axisY.normalize();
  47340. this._cam_axisX.normalize();
  47341. }
  47342. }
  47343. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47344. var idx = 0;
  47345. var index = 0;
  47346. var colidx = 0;
  47347. var colorIndex = 0;
  47348. var uvidx = 0;
  47349. var uvIndex = 0;
  47350. var pt = 0;
  47351. if (this._computeBoundingBox) {
  47352. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47353. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47354. }
  47355. // particle loop
  47356. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  47357. for (var p = start; p <= end; p++) {
  47358. this._particle = this.particles[p];
  47359. this._shape = this._particle._model._shape;
  47360. this._shapeUV = this._particle._model._shapeUV;
  47361. // call to custom user function to update the particle properties
  47362. this.updateParticle(this._particle);
  47363. if (this._particle.isVisible) {
  47364. // particle rotation matrix
  47365. if (this.billboard) {
  47366. this._particle.rotation.x = 0.0;
  47367. this._particle.rotation.y = 0.0;
  47368. }
  47369. if (this._computeParticleRotation || this.billboard) {
  47370. if (this._particle.rotationQuaternion) {
  47371. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47372. }
  47373. else {
  47374. this._yaw = this._particle.rotation.y;
  47375. this._pitch = this._particle.rotation.x;
  47376. this._roll = this._particle.rotation.z;
  47377. this._quaternionRotationYPR();
  47378. }
  47379. this._quaternionToRotationMatrix();
  47380. }
  47381. // particle vertex loop
  47382. for (pt = 0; pt < this._shape.length; pt++) {
  47383. idx = index + pt * 3;
  47384. colidx = colorIndex + pt * 4;
  47385. uvidx = uvIndex + pt * 2;
  47386. this._vertex.x = this._shape[pt].x;
  47387. this._vertex.y = this._shape[pt].y;
  47388. this._vertex.z = this._shape[pt].z;
  47389. if (this._computeParticleVertex) {
  47390. this.updateParticleVertex(this._particle, this._vertex, pt);
  47391. }
  47392. // positions
  47393. this._vertex.x *= this._particle.scaling.x;
  47394. this._vertex.y *= this._particle.scaling.y;
  47395. this._vertex.z *= this._particle.scaling.z;
  47396. 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];
  47397. 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;
  47398. 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;
  47399. 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;
  47400. 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;
  47401. 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;
  47402. 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;
  47403. if (this._computeBoundingBox) {
  47404. if (this._positions32[idx] < this._minimum.x) {
  47405. this._minimum.x = this._positions32[idx];
  47406. }
  47407. if (this._positions32[idx] > this._maximum.x) {
  47408. this._maximum.x = this._positions32[idx];
  47409. }
  47410. if (this._positions32[idx + 1] < this._minimum.y) {
  47411. this._minimum.y = this._positions32[idx + 1];
  47412. }
  47413. if (this._positions32[idx + 1] > this._maximum.y) {
  47414. this._maximum.y = this._positions32[idx + 1];
  47415. }
  47416. if (this._positions32[idx + 2] < this._minimum.z) {
  47417. this._minimum.z = this._positions32[idx + 2];
  47418. }
  47419. if (this._positions32[idx + 2] > this._maximum.z) {
  47420. this._maximum.z = this._positions32[idx + 2];
  47421. }
  47422. }
  47423. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  47424. if (!this._computeParticleVertex) {
  47425. this._normal.x = this._fixedNormal32[idx];
  47426. this._normal.y = this._fixedNormal32[idx + 1];
  47427. this._normal.z = this._fixedNormal32[idx + 2];
  47428. 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];
  47429. 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;
  47430. 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;
  47431. 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;
  47432. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47433. 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;
  47434. 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;
  47435. }
  47436. if (this._computeParticleColor) {
  47437. this._colors32[colidx] = this._particle.color.r;
  47438. this._colors32[colidx + 1] = this._particle.color.g;
  47439. this._colors32[colidx + 2] = this._particle.color.b;
  47440. this._colors32[colidx + 3] = this._particle.color.a;
  47441. }
  47442. if (this._computeParticleTexture) {
  47443. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47444. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47445. }
  47446. }
  47447. }
  47448. else {
  47449. for (pt = 0; pt < this._shape.length; pt++) {
  47450. idx = index + pt * 3;
  47451. colidx = colorIndex + pt * 4;
  47452. uvidx = uvIndex + pt * 2;
  47453. this._positions32[idx] = this._camera.position.x;
  47454. this._positions32[idx + 1] = this._camera.position.y;
  47455. this._positions32[idx + 2] = this._camera.position.z;
  47456. this._normals32[idx] = 0.0;
  47457. this._normals32[idx + 1] = 0.0;
  47458. this._normals32[idx + 2] = 0.0;
  47459. if (this._computeParticleColor) {
  47460. this._colors32[colidx] = this._particle.color.r;
  47461. this._colors32[colidx + 1] = this._particle.color.g;
  47462. this._colors32[colidx + 2] = this._particle.color.b;
  47463. this._colors32[colidx + 3] = this._particle.color.a;
  47464. }
  47465. if (this._computeParticleTexture) {
  47466. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47467. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47468. }
  47469. }
  47470. }
  47471. // if the particle intersections must be computed : update the bbInfo
  47472. if (this._particlesIntersect) {
  47473. var bInfo = this._particle._boundingInfo;
  47474. var bBox = bInfo.boundingBox;
  47475. var bSphere = bInfo.boundingSphere;
  47476. // place, scale and rotate the particle bbox within the SPS local system
  47477. for (var b = 0; b < bBox.vectors.length; b++) {
  47478. if (this._particle.isVisible) {
  47479. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  47480. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  47481. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  47482. 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];
  47483. 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;
  47484. 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;
  47485. 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;
  47486. 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;
  47487. 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;
  47488. 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;
  47489. }
  47490. else {
  47491. bBox.vectors[b].x = this._camera.position.x;
  47492. bBox.vectors[b].y = this._camera.position.y;
  47493. bBox.vectors[b].z = this._camera.position.z;
  47494. }
  47495. }
  47496. // place and scale the particle bouding sphere in the SPS local system
  47497. if (this._particle.isVisible) {
  47498. this._minimum.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  47499. this._minimum.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  47500. this._minimum.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  47501. this._maximum.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  47502. this._maximum.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  47503. this._maximum.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  47504. bSphere.center.x = this._particle.position.x + (this._minimum.x + this._maximum.x) * 0.5;
  47505. bSphere.center.y = this._particle.position.y + (this._minimum.y + this._maximum.y) * 0.5;
  47506. bSphere.center.z = this._particle.position.z + (this._minimum.z + this._maximum.z) * 0.5;
  47507. bSphere.radius = BABYLON.Vector3.Distance(this._minimum, this._maximum) * 0.5;
  47508. }
  47509. else {
  47510. bSphere.center.x = this._camera.position.x;
  47511. bSphere.center.y = this._camera.position.x;
  47512. bSphere.center.z = this._camera.position.x;
  47513. bSphere.radius = 0.0;
  47514. }
  47515. // then update the bbox and the bsphere into the world system
  47516. bBox._update(this.mesh.getWorldMatrix());
  47517. bSphere._update(this.mesh.getWorldMatrix());
  47518. }
  47519. // increment indexes for the next particle
  47520. index = idx + 3;
  47521. colorIndex = colidx + 4;
  47522. uvIndex = uvidx + 2;
  47523. }
  47524. // if the VBO must be updated
  47525. if (update) {
  47526. if (this._computeParticleColor) {
  47527. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47528. }
  47529. if (this._computeParticleTexture) {
  47530. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47531. }
  47532. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47533. if (!this.mesh.areNormalsFrozen) {
  47534. if (this._computeParticleVertex) {
  47535. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  47536. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  47537. for (var i = 0; i < this._normals32.length; i++) {
  47538. this._fixedNormal32[i] = this._normals32[i];
  47539. }
  47540. }
  47541. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47542. }
  47543. }
  47544. if (this._computeBoundingBox) {
  47545. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  47546. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  47547. }
  47548. this.afterUpdateParticles(start, end, update);
  47549. };
  47550. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  47551. this._halfroll = this._roll * 0.5;
  47552. this._halfpitch = this._pitch * 0.5;
  47553. this._halfyaw = this._yaw * 0.5;
  47554. this._sinRoll = Math.sin(this._halfroll);
  47555. this._cosRoll = Math.cos(this._halfroll);
  47556. this._sinPitch = Math.sin(this._halfpitch);
  47557. this._cosPitch = Math.cos(this._halfpitch);
  47558. this._sinYaw = Math.sin(this._halfyaw);
  47559. this._cosYaw = Math.cos(this._halfyaw);
  47560. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  47561. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  47562. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  47563. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  47564. };
  47565. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  47566. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  47567. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  47568. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  47569. this._rotMatrix.m[3] = 0;
  47570. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  47571. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  47572. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  47573. this._rotMatrix.m[7] = 0;
  47574. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  47575. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  47576. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  47577. this._rotMatrix.m[11] = 0;
  47578. this._rotMatrix.m[12] = 0;
  47579. this._rotMatrix.m[13] = 0;
  47580. this._rotMatrix.m[14] = 0;
  47581. this._rotMatrix.m[15] = 1.0;
  47582. };
  47583. /**
  47584. * Disposes the SPS
  47585. */
  47586. SolidParticleSystem.prototype.dispose = function () {
  47587. this.mesh.dispose();
  47588. this.vars = null;
  47589. // drop references to internal big arrays for the GC
  47590. this._positions = null;
  47591. this._indices = null;
  47592. this._normals = null;
  47593. this._uvs = null;
  47594. this._colors = null;
  47595. this._positions32 = null;
  47596. this._normals32 = null;
  47597. this._fixedNormal32 = null;
  47598. this._uvs32 = null;
  47599. this._colors32 = null;
  47600. this.pickedParticles = null;
  47601. };
  47602. /**
  47603. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  47604. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47605. */
  47606. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  47607. if (!this._isVisibilityBoxLocked) {
  47608. this.mesh.refreshBoundingInfo();
  47609. }
  47610. };
  47611. /**
  47612. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  47613. * @param size the size (float) of the visibility box
  47614. * note : this doesn't lock the SPS mesh bounding box.
  47615. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47616. */
  47617. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  47618. var vis = size / 2;
  47619. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  47620. };
  47621. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  47622. // getter and setter
  47623. get: function () {
  47624. return this._alwaysVisible;
  47625. },
  47626. /**
  47627. * Sets the SPS as always visible or not
  47628. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47629. */
  47630. set: function (val) {
  47631. this._alwaysVisible = val;
  47632. this.mesh.alwaysSelectAsActiveMesh = val;
  47633. },
  47634. enumerable: true,
  47635. configurable: true
  47636. });
  47637. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  47638. get: function () {
  47639. return this._isVisibilityBoxLocked;
  47640. },
  47641. /**
  47642. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  47643. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47644. */
  47645. set: function (val) {
  47646. this._isVisibilityBoxLocked = val;
  47647. this.mesh.getBoundingInfo().isLocked = val;
  47648. },
  47649. enumerable: true,
  47650. configurable: true
  47651. });
  47652. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  47653. // getters
  47654. get: function () {
  47655. return this._computeParticleRotation;
  47656. },
  47657. // Optimizer setters
  47658. /**
  47659. * Tells to `setParticles()` to compute the particle rotations or not.
  47660. * Default value : true. The SPS is faster when it's set to false.
  47661. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  47662. */
  47663. set: function (val) {
  47664. this._computeParticleRotation = val;
  47665. },
  47666. enumerable: true,
  47667. configurable: true
  47668. });
  47669. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47670. get: function () {
  47671. return this._computeParticleColor;
  47672. },
  47673. /**
  47674. * Tells to `setParticles()` to compute the particle colors or not.
  47675. * Default value : true. The SPS is faster when it's set to false.
  47676. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47677. */
  47678. set: function (val) {
  47679. this._computeParticleColor = val;
  47680. },
  47681. enumerable: true,
  47682. configurable: true
  47683. });
  47684. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  47685. get: function () {
  47686. return this._computeParticleTexture;
  47687. },
  47688. /**
  47689. * Tells to `setParticles()` to compute the particle textures or not.
  47690. * Default value : true. The SPS is faster when it's set to false.
  47691. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  47692. */
  47693. set: function (val) {
  47694. this._computeParticleTexture = val;
  47695. },
  47696. enumerable: true,
  47697. configurable: true
  47698. });
  47699. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  47700. get: function () {
  47701. return this._computeParticleVertex;
  47702. },
  47703. /**
  47704. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  47705. * Default value : false. The SPS is faster when it's set to false.
  47706. * Note : the particle custom vertex positions aren't stored values.
  47707. */
  47708. set: function (val) {
  47709. this._computeParticleVertex = val;
  47710. },
  47711. enumerable: true,
  47712. configurable: true
  47713. });
  47714. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  47715. get: function () {
  47716. return this._computeBoundingBox;
  47717. },
  47718. /**
  47719. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  47720. */
  47721. set: function (val) {
  47722. this._computeBoundingBox = val;
  47723. },
  47724. enumerable: true,
  47725. configurable: true
  47726. });
  47727. // =======================================================================
  47728. // Particle behavior logic
  47729. // these following methods may be overwritten by the user to fit his needs
  47730. /**
  47731. * This function does nothing. It may be overwritten to set all the particle first values.
  47732. * The SPS doesn't call this function, you may have to call it by your own.
  47733. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47734. */
  47735. SolidParticleSystem.prototype.initParticles = function () {
  47736. };
  47737. /**
  47738. * This function does nothing. It may be overwritten to recycle a particle.
  47739. * The SPS doesn't call this function, you may have to call it by your own.
  47740. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47741. */
  47742. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  47743. return particle;
  47744. };
  47745. /**
  47746. * Updates a particle : this function should be overwritten by the user.
  47747. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  47748. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47749. * ex : just set a particle position or velocity and recycle conditions
  47750. */
  47751. SolidParticleSystem.prototype.updateParticle = function (particle) {
  47752. return particle;
  47753. };
  47754. /**
  47755. * Updates a vertex of a particle : it can be overwritten by the user.
  47756. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  47757. * @param particle the current particle
  47758. * @param vertex the current index of the current particle
  47759. * @param pt the index of the current vertex in the particle shape
  47760. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  47761. * ex : just set a vertex particle position
  47762. */
  47763. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  47764. return vertex;
  47765. };
  47766. /**
  47767. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  47768. * This does nothing and may be overwritten by the user.
  47769. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47770. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47771. * @param update the boolean update value actually passed to setParticles()
  47772. */
  47773. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  47774. };
  47775. /**
  47776. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  47777. * This will be passed three parameters.
  47778. * This does nothing and may be overwritten by the user.
  47779. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47780. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47781. * @param update the boolean update value actually passed to setParticles()
  47782. */
  47783. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  47784. };
  47785. return SolidParticleSystem;
  47786. }());
  47787. BABYLON.SolidParticleSystem = SolidParticleSystem;
  47788. })(BABYLON || (BABYLON = {}));
  47789. var BABYLON;
  47790. (function (BABYLON) {
  47791. var Internals;
  47792. (function (Internals) {
  47793. var FileFaceOrientation = (function () {
  47794. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  47795. this.name = name;
  47796. this.worldAxisForNormal = worldAxisForNormal;
  47797. this.worldAxisForFileX = worldAxisForFileX;
  47798. this.worldAxisForFileY = worldAxisForFileY;
  47799. }
  47800. return FileFaceOrientation;
  47801. }());
  47802. ;
  47803. /**
  47804. * Helper class dealing with the extraction of spherical polynomial dataArray
  47805. * from a cube map.
  47806. */
  47807. var CubeMapToSphericalPolynomialTools = (function () {
  47808. function CubeMapToSphericalPolynomialTools() {
  47809. }
  47810. /**
  47811. * Converts a cubemap to the according Spherical Polynomial data.
  47812. * This extracts the first 3 orders only as they are the only one used in the lighting.
  47813. *
  47814. * @param cubeInfo The Cube map to extract the information from.
  47815. * @return The Spherical Polynomial data.
  47816. */
  47817. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  47818. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  47819. var totalSolidAngle = 0.0;
  47820. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  47821. var du = 2.0 / cubeInfo.size;
  47822. var dv = du;
  47823. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  47824. var minUV = du * 0.5 - 1.0;
  47825. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  47826. var fileFace = this.FileFaces[faceIndex];
  47827. var dataArray = cubeInfo[fileFace.name];
  47828. var v = minUV;
  47829. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  47830. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  47831. // Because SP is still linear, so summation is fine in that basis.
  47832. for (var y = 0; y < cubeInfo.size; y++) {
  47833. var u = minUV;
  47834. for (var x = 0; x < cubeInfo.size; x++) {
  47835. // World direction (not normalised)
  47836. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  47837. worldDirection.normalize();
  47838. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  47839. if (1) {
  47840. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  47841. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  47842. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  47843. var color = new BABYLON.Color3(r, g, b);
  47844. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  47845. }
  47846. else {
  47847. if (faceIndex == 0) {
  47848. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  47849. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  47850. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  47851. }
  47852. else if (faceIndex == 1) {
  47853. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  47854. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  47855. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  47856. }
  47857. else if (faceIndex == 2) {
  47858. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  47859. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  47860. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  47861. }
  47862. else if (faceIndex == 3) {
  47863. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  47864. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  47865. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  47866. }
  47867. else if (faceIndex == 4) {
  47868. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  47869. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  47870. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  47871. }
  47872. else if (faceIndex == 5) {
  47873. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  47874. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  47875. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  47876. }
  47877. 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]);
  47878. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  47879. }
  47880. totalSolidAngle += deltaSolidAngle;
  47881. u += du;
  47882. }
  47883. v += dv;
  47884. }
  47885. }
  47886. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  47887. var correction = correctSolidAngle / totalSolidAngle;
  47888. sphericalHarmonics.scale(correction);
  47889. // Additionally scale by pi -- audit needed
  47890. sphericalHarmonics.scale(1.0 / Math.PI);
  47891. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  47892. };
  47893. CubeMapToSphericalPolynomialTools.FileFaces = [
  47894. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  47895. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  47896. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  47897. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  47898. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  47899. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  47900. ];
  47901. return CubeMapToSphericalPolynomialTools;
  47902. }());
  47903. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  47904. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47905. })(BABYLON || (BABYLON = {}));
  47906. var BABYLON;
  47907. (function (BABYLON) {
  47908. var Internals;
  47909. (function (Internals) {
  47910. /**
  47911. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  47912. */
  47913. var PanoramaToCubeMapTools = (function () {
  47914. function PanoramaToCubeMapTools() {
  47915. }
  47916. /**
  47917. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  47918. *
  47919. * @param float32Array The source data.
  47920. * @param inputWidth The width of the input panorama.
  47921. * @param inputhHeight The height of the input panorama.
  47922. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  47923. * @return The cubemap data
  47924. */
  47925. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  47926. if (!float32Array) {
  47927. throw "ConvertPanoramaToCubemap: input cannot be null";
  47928. }
  47929. if (float32Array.length != inputWidth * inputHeight * 3) {
  47930. throw "ConvertPanoramaToCubemap: input size is wrong";
  47931. }
  47932. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  47933. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  47934. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  47935. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  47936. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  47937. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  47938. return {
  47939. front: textureFront,
  47940. back: textureBack,
  47941. left: textureLeft,
  47942. right: textureRight,
  47943. up: textureUp,
  47944. down: textureDown,
  47945. size: size
  47946. };
  47947. };
  47948. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  47949. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  47950. var textureArray = new Float32Array(buffer);
  47951. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  47952. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  47953. var dy = 1 / texSize;
  47954. var fy = 0;
  47955. for (var y = 0; y < texSize; y++) {
  47956. var xv1 = faceData[0];
  47957. var xv2 = faceData[2];
  47958. for (var x = 0; x < texSize; x++) {
  47959. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  47960. v.normalize();
  47961. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  47962. // 3 channels per pixels
  47963. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  47964. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  47965. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  47966. xv1 = xv1.add(rotDX1);
  47967. xv2 = xv2.add(rotDX2);
  47968. }
  47969. fy += dy;
  47970. }
  47971. return textureArray;
  47972. };
  47973. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  47974. var theta = Math.atan2(vDir.z, vDir.x);
  47975. var phi = Math.acos(vDir.y);
  47976. while (theta < -Math.PI)
  47977. theta += 2 * Math.PI;
  47978. while (theta > Math.PI)
  47979. theta -= 2 * Math.PI;
  47980. var dx = theta / Math.PI;
  47981. var dy = phi / Math.PI;
  47982. // recenter.
  47983. dx = dx * 0.5 + 0.5;
  47984. var px = Math.round(dx * inputWidth);
  47985. if (px < 0)
  47986. px = 0;
  47987. else if (px >= inputWidth)
  47988. px = inputWidth - 1;
  47989. var py = Math.round(dy * inputHeight);
  47990. if (py < 0)
  47991. py = 0;
  47992. else if (py >= inputHeight)
  47993. py = inputHeight - 1;
  47994. var inputY = (inputHeight - py - 1);
  47995. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  47996. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  47997. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  47998. return {
  47999. r: r,
  48000. g: g,
  48001. b: b
  48002. };
  48003. };
  48004. PanoramaToCubeMapTools.FACE_FRONT = [
  48005. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48006. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48007. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48008. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48009. ];
  48010. PanoramaToCubeMapTools.FACE_BACK = [
  48011. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48012. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48013. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48014. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48015. ];
  48016. PanoramaToCubeMapTools.FACE_RIGHT = [
  48017. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48018. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48019. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48020. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48021. ];
  48022. PanoramaToCubeMapTools.FACE_LEFT = [
  48023. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48024. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48025. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48026. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48027. ];
  48028. PanoramaToCubeMapTools.FACE_DOWN = [
  48029. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48030. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48031. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48032. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48033. ];
  48034. PanoramaToCubeMapTools.FACE_UP = [
  48035. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48036. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48037. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48038. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48039. ];
  48040. return PanoramaToCubeMapTools;
  48041. }());
  48042. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48043. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48044. })(BABYLON || (BABYLON = {}));
  48045. var BABYLON;
  48046. (function (BABYLON) {
  48047. var Internals;
  48048. (function (Internals) {
  48049. ;
  48050. /**
  48051. * This groups tools to convert HDR texture to native colors array.
  48052. */
  48053. var HDRTools = (function () {
  48054. function HDRTools() {
  48055. }
  48056. HDRTools.Ldexp = function (mantissa, exponent) {
  48057. if (exponent > 1023) {
  48058. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48059. }
  48060. if (exponent < -1074) {
  48061. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48062. }
  48063. return mantissa * Math.pow(2, exponent);
  48064. };
  48065. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48066. if (exponent > 0) {
  48067. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48068. float32array[index + 0] = red * exponent;
  48069. float32array[index + 1] = green * exponent;
  48070. float32array[index + 2] = blue * exponent;
  48071. }
  48072. else {
  48073. float32array[index + 0] = 0;
  48074. float32array[index + 1] = 0;
  48075. float32array[index + 2] = 0;
  48076. }
  48077. };
  48078. HDRTools.readStringLine = function (uint8array, startIndex) {
  48079. var line = "";
  48080. var character = "";
  48081. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48082. character = String.fromCharCode(uint8array[i]);
  48083. if (character == "\n") {
  48084. break;
  48085. }
  48086. line += character;
  48087. }
  48088. return line;
  48089. };
  48090. /**
  48091. * Reads header information from an RGBE texture stored in a native array.
  48092. * More information on this format are available here:
  48093. * https://en.wikipedia.org/wiki/RGBE_image_format
  48094. *
  48095. * @param uint8array The binary file stored in native array.
  48096. * @return The header information.
  48097. */
  48098. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48099. var height = 0;
  48100. var width = 0;
  48101. var line = this.readStringLine(uint8array, 0);
  48102. if (line[0] != '#' || line[1] != '?') {
  48103. throw "Bad HDR Format.";
  48104. }
  48105. var endOfHeader = false;
  48106. var findFormat = false;
  48107. var lineIndex = 0;
  48108. do {
  48109. lineIndex += (line.length + 1);
  48110. line = this.readStringLine(uint8array, lineIndex);
  48111. if (line == "FORMAT=32-bit_rle_rgbe") {
  48112. findFormat = true;
  48113. }
  48114. else if (line.length == 0) {
  48115. endOfHeader = true;
  48116. }
  48117. } while (!endOfHeader);
  48118. if (!findFormat) {
  48119. throw "HDR Bad header format, unsupported FORMAT";
  48120. }
  48121. lineIndex += (line.length + 1);
  48122. line = this.readStringLine(uint8array, lineIndex);
  48123. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48124. var match = sizeRegexp.exec(line);
  48125. // TODO. Support +Y and -X if needed.
  48126. if (match.length < 3) {
  48127. throw "HDR Bad header format, no size";
  48128. }
  48129. width = parseInt(match[2]);
  48130. height = parseInt(match[1]);
  48131. if (width < 8 || width > 0x7fff) {
  48132. throw "HDR Bad header format, unsupported size";
  48133. }
  48134. lineIndex += (line.length + 1);
  48135. return {
  48136. height: height,
  48137. width: width,
  48138. dataPosition: lineIndex
  48139. };
  48140. };
  48141. /**
  48142. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48143. * This RGBE texture needs to store the information as a panorama.
  48144. *
  48145. * More information on this format are available here:
  48146. * https://en.wikipedia.org/wiki/RGBE_image_format
  48147. *
  48148. * @param buffer The binary file stored in an array buffer.
  48149. * @param size The expected size of the extracted cubemap.
  48150. * @return The Cube Map information.
  48151. */
  48152. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48153. var uint8array = new Uint8Array(buffer);
  48154. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48155. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48156. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48157. return cubeMapData;
  48158. };
  48159. /**
  48160. * Returns the pixels data extracted from an RGBE texture.
  48161. * This pixels will be stored left to right up to down in the R G B order in one array.
  48162. *
  48163. * More information on this format are available here:
  48164. * https://en.wikipedia.org/wiki/RGBE_image_format
  48165. *
  48166. * @param uint8array The binary file stored in an array buffer.
  48167. * @param hdrInfo The header information of the file.
  48168. * @return The pixels data in RGB right to left up to down order.
  48169. */
  48170. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48171. // Keep for multi format supports.
  48172. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48173. };
  48174. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48175. var num_scanlines = hdrInfo.height;
  48176. var scanline_width = hdrInfo.width;
  48177. var a, b, c, d, count;
  48178. var dataIndex = hdrInfo.dataPosition;
  48179. var index = 0, endIndex = 0, i = 0;
  48180. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48181. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48182. // 3 channels of 4 bytes per pixel in float.
  48183. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48184. var resultArray = new Float32Array(resultBuffer);
  48185. // read in each successive scanline
  48186. while (num_scanlines > 0) {
  48187. a = uint8array[dataIndex++];
  48188. b = uint8array[dataIndex++];
  48189. c = uint8array[dataIndex++];
  48190. d = uint8array[dataIndex++];
  48191. if (a != 2 || b != 2 || (c & 0x80)) {
  48192. // this file is not run length encoded
  48193. throw "HDR Bad header format, not RLE";
  48194. }
  48195. if (((c << 8) | d) != scanline_width) {
  48196. throw "HDR Bad header format, wrong scan line width";
  48197. }
  48198. index = 0;
  48199. // read each of the four channels for the scanline into the buffer
  48200. for (i = 0; i < 4; i++) {
  48201. endIndex = (i + 1) * scanline_width;
  48202. while (index < endIndex) {
  48203. a = uint8array[dataIndex++];
  48204. b = uint8array[dataIndex++];
  48205. if (a > 128) {
  48206. // a run of the same value
  48207. count = a - 128;
  48208. if ((count == 0) || (count > endIndex - index)) {
  48209. throw "HDR Bad Format, bad scanline data (run)";
  48210. }
  48211. while (count-- > 0) {
  48212. scanLineArray[index++] = b;
  48213. }
  48214. }
  48215. else {
  48216. // a non-run
  48217. count = a;
  48218. if ((count == 0) || (count > endIndex - index)) {
  48219. throw "HDR Bad Format, bad scanline data (non-run)";
  48220. }
  48221. scanLineArray[index++] = b;
  48222. if (--count > 0) {
  48223. for (var j = 0; j < count; j++) {
  48224. scanLineArray[index++] = uint8array[dataIndex++];
  48225. }
  48226. }
  48227. }
  48228. }
  48229. }
  48230. // now convert data from buffer into floats
  48231. for (i = 0; i < scanline_width; i++) {
  48232. a = scanLineArray[i];
  48233. b = scanLineArray[i + scanline_width];
  48234. c = scanLineArray[i + 2 * scanline_width];
  48235. d = scanLineArray[i + 3 * scanline_width];
  48236. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48237. }
  48238. num_scanlines--;
  48239. }
  48240. return resultArray;
  48241. };
  48242. return HDRTools;
  48243. }());
  48244. Internals.HDRTools = HDRTools;
  48245. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48246. })(BABYLON || (BABYLON = {}));
  48247. //_______________________________________________________________
  48248. // Extracted from CubeMapGen:
  48249. // https://code.google.com/archive/p/cubemapgen/
  48250. //
  48251. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  48252. //_______________________________________________________________
  48253. var BABYLON;
  48254. (function (BABYLON) {
  48255. var Internals;
  48256. (function (Internals) {
  48257. /**
  48258. * The bounding box information used during the conversion process.
  48259. */
  48260. var CMGBoundinBox = (function () {
  48261. function CMGBoundinBox() {
  48262. this.min = new BABYLON.Vector3(0, 0, 0);
  48263. this.max = new BABYLON.Vector3(0, 0, 0);
  48264. this.clear();
  48265. }
  48266. CMGBoundinBox.prototype.clear = function () {
  48267. this.min.x = CMGBoundinBox.MAX;
  48268. this.min.y = CMGBoundinBox.MAX;
  48269. this.min.z = CMGBoundinBox.MAX;
  48270. this.max.x = CMGBoundinBox.MIN;
  48271. this.max.y = CMGBoundinBox.MIN;
  48272. this.max.z = CMGBoundinBox.MIN;
  48273. };
  48274. CMGBoundinBox.prototype.augment = function (x, y, z) {
  48275. this.min.x = Math.min(this.min.x, x);
  48276. this.min.y = Math.min(this.min.y, y);
  48277. this.min.z = Math.min(this.min.z, z);
  48278. this.max.x = Math.max(this.max.x, x);
  48279. this.max.y = Math.max(this.max.y, y);
  48280. this.max.z = Math.max(this.max.z, z);
  48281. };
  48282. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  48283. this.min.x = Math.max(this.min.x, x);
  48284. this.min.y = Math.max(this.min.y, y);
  48285. this.min.z = Math.max(this.min.z, z);
  48286. };
  48287. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  48288. this.max.x = Math.min(this.max.x, x);
  48289. this.max.y = Math.min(this.max.y, y);
  48290. this.max.z = Math.min(this.max.z, z);
  48291. };
  48292. CMGBoundinBox.prototype.empty = function () {
  48293. if ((this.min.x > this.max.y) ||
  48294. (this.min.y > this.max.y) ||
  48295. (this.min.z > this.max.y)) {
  48296. return true;
  48297. }
  48298. else {
  48299. return false;
  48300. }
  48301. };
  48302. CMGBoundinBox.MAX = Number.MAX_VALUE;
  48303. CMGBoundinBox.MIN = Number.MIN_VALUE;
  48304. return CMGBoundinBox;
  48305. }());
  48306. /**
  48307. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  48308. * required by the glossinees of a material.
  48309. *
  48310. * This only supports the cosine drop power as well as Warp fixup generation method.
  48311. *
  48312. * This is using the process from CubeMapGen described here:
  48313. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  48314. */
  48315. var PMREMGenerator = (function () {
  48316. /**
  48317. * Constructor of the generator.
  48318. *
  48319. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  48320. * @param inputSize The size of the cubemap faces
  48321. * @param outputSize The size of the output cubemap faces
  48322. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  48323. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  48324. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  48325. * @param specularPower The max specular level of the desired cubemap
  48326. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  48327. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  48328. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  48329. */
  48330. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  48331. this.input = input;
  48332. this.inputSize = inputSize;
  48333. this.outputSize = outputSize;
  48334. this.maxNumMipLevels = maxNumMipLevels;
  48335. this.numChannels = numChannels;
  48336. this.isFloat = isFloat;
  48337. this.specularPower = specularPower;
  48338. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  48339. this.excludeBase = excludeBase;
  48340. this.fixup = fixup;
  48341. this._outputSurface = [];
  48342. this._numMipLevels = 0;
  48343. }
  48344. /**
  48345. * Launches the filter process and return the result.
  48346. *
  48347. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  48348. */
  48349. PMREMGenerator.prototype.filterCubeMap = function () {
  48350. // Init cubemap processor
  48351. this.init();
  48352. // Filters the cubemap
  48353. this.filterCubeMapMipChain();
  48354. // Returns the filtered mips.
  48355. return this._outputSurface;
  48356. };
  48357. PMREMGenerator.prototype.init = function () {
  48358. var i;
  48359. var j;
  48360. var mipLevelSize;
  48361. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  48362. if (this.maxNumMipLevels == 0) {
  48363. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  48364. }
  48365. //first miplevel size
  48366. mipLevelSize = this.outputSize;
  48367. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  48368. for (j = 0; j < this.maxNumMipLevels; j++) {
  48369. this._outputSurface.length++;
  48370. this._outputSurface[j] = [];
  48371. //Iterate over faces for output images
  48372. for (i = 0; i < 6; i++) {
  48373. this._outputSurface[j].length++;
  48374. // Initializes a new array for the output.
  48375. if (this.isFloat) {
  48376. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  48377. }
  48378. else {
  48379. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  48380. }
  48381. }
  48382. //next mip level is half size
  48383. mipLevelSize >>= 1;
  48384. this._numMipLevels++;
  48385. //terminate if mip chain becomes too small
  48386. if (mipLevelSize == 0) {
  48387. this.maxNumMipLevels = j;
  48388. return;
  48389. }
  48390. }
  48391. };
  48392. //--------------------------------------------------------------------------------------
  48393. //Cube map filtering and mip chain generation.
  48394. // the cube map filtereing is specified using a number of parameters:
  48395. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  48396. // indicates the region of the hemisphere to filter over for each tap.
  48397. //
  48398. // Note that the top mip level is also a filtered version of the original input images
  48399. // as well in order to create mip chains for diffuse environment illumination.
  48400. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  48401. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  48402. //
  48403. // Then the mip angle used to genreate the next level of the mip chain from the first level
  48404. // is a_InitialMipAngle
  48405. //
  48406. // The angle for the subsequent levels of the mip chain are specified by their parents
  48407. // filtering angle and a per-level scale and bias
  48408. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  48409. //
  48410. //--------------------------------------------------------------------------------------
  48411. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  48412. // First, take count of the lighting model to modify SpecularPower
  48413. // 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;
  48414. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  48415. //Cone angle start (for generating subsequent mip levels)
  48416. var currentSpecularPower = this.specularPower;
  48417. //Build filter lookup tables based on the source miplevel size
  48418. this.precomputeFilterLookupTables(this.inputSize);
  48419. // Note that we need to filter the first level before generating mipmap
  48420. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  48421. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  48422. // TODO : Write a function to copy and scale the base mipmap in output
  48423. // I am just lazy here and just put a high specular power value, and do some if.
  48424. if (this.excludeBase && (levelIndex == 0)) {
  48425. // 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).
  48426. currentSpecularPower = 100000.0;
  48427. }
  48428. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  48429. var srcCubeImage = this.input;
  48430. var dstCubeImage = this._outputSurface[levelIndex];
  48431. var dstSize = this.outputSize >> levelIndex;
  48432. // Compute required angle.
  48433. var angle = this.getBaseFilterAngle(currentSpecularPower);
  48434. // filter cube surfaces
  48435. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  48436. // fix seams
  48437. if (this.fixup) {
  48438. this.fixupCubeEdges(dstCubeImage, dstSize);
  48439. }
  48440. // Decrease the specular power to generate the mipmap chain
  48441. // TODO : Use another method for Exclude (see first comment at start of the function
  48442. if (this.excludeBase && (levelIndex == 0)) {
  48443. currentSpecularPower = this.specularPower;
  48444. }
  48445. currentSpecularPower *= this.cosinePowerDropPerMip;
  48446. }
  48447. };
  48448. //--------------------------------------------------------------------------------------
  48449. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  48450. // It allow to optimize the texel to access base on the specular power.
  48451. //--------------------------------------------------------------------------------------
  48452. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  48453. // We want to find the alpha such that:
  48454. // cos(alpha)^cosinePower = epsilon
  48455. // That's: acos(epsilon^(1/cosinePower))
  48456. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  48457. var angle = 180.0;
  48458. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  48459. angle *= 180.0 / Math.PI; // Convert to degree
  48460. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  48461. return angle;
  48462. };
  48463. //--------------------------------------------------------------------------------------
  48464. //Builds the following lookup tables prior to filtering:
  48465. // -normalizer cube map
  48466. // -tap weight lookup table
  48467. //
  48468. //--------------------------------------------------------------------------------------
  48469. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  48470. var srcTexelAngle;
  48471. var iCubeFace;
  48472. //clear pre-existing normalizer cube map
  48473. this._normCubeMap = [];
  48474. //Normalized vectors per cubeface and per-texel solid angle
  48475. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  48476. };
  48477. //--------------------------------------------------------------------------------------
  48478. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  48479. //
  48480. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  48481. //
  48482. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  48483. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  48484. // below
  48485. //--------------------------------------------------------------------------------------
  48486. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  48487. var iCubeFace;
  48488. var u;
  48489. var v;
  48490. //iterate over cube faces
  48491. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  48492. //First three channels for norm cube, and last channel for solid angle
  48493. this._normCubeMap.push(new Float32Array(size * size * 4));
  48494. //fast texture walk, build normalizer cube map
  48495. var facesData = this.input[iCubeFace];
  48496. for (v = 0; v < size; v++) {
  48497. for (u = 0; u < size; u++) {
  48498. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  48499. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  48500. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  48501. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  48502. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  48503. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  48504. }
  48505. }
  48506. }
  48507. };
  48508. //--------------------------------------------------------------------------------------
  48509. // Convert cubemap face texel coordinates and face idx to 3D vector
  48510. // note the U and V coords are integer coords and range from 0 to size-1
  48511. // this routine can be used to generate a normalizer cube map
  48512. //--------------------------------------------------------------------------------------
  48513. // SL BEGIN
  48514. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  48515. var nvcU;
  48516. var nvcV;
  48517. var tempVec;
  48518. // Change from original AMD code
  48519. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  48520. // + 0.5f is for texel center addressing
  48521. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  48522. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  48523. // warp fixup
  48524. if (fixup && size > 1) {
  48525. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  48526. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  48527. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  48528. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  48529. }
  48530. // Get current vector
  48531. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  48532. // U contribution
  48533. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  48534. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  48535. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  48536. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  48537. // V contribution and Sum
  48538. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  48539. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  48540. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  48541. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  48542. //add face axis
  48543. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  48544. PMREMGenerator._vectorTemp.x += faceAxis[0];
  48545. PMREMGenerator._vectorTemp.y += faceAxis[1];
  48546. PMREMGenerator._vectorTemp.z += faceAxis[2];
  48547. //normalize vector
  48548. PMREMGenerator._vectorTemp.normalize();
  48549. return PMREMGenerator._vectorTemp;
  48550. };
  48551. //--------------------------------------------------------------------------------------
  48552. // Convert 3D vector to cubemap face texel coordinates and face idx
  48553. // note the U and V coords are integer coords and range from 0 to size-1
  48554. // this routine can be used to generate a normalizer cube map
  48555. //
  48556. // returns face IDX and texel coords
  48557. //--------------------------------------------------------------------------------------
  48558. // SL BEGIN
  48559. /*
  48560. Mapping Texture Coordinates to Cube Map Faces
  48561. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  48562. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  48563. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  48564. map arrangement in Pixar's RenderMan package.
  48565. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  48566. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  48567. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  48568. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  48569. the major axis direction). The target column in the table below explains how the major axis direction
  48570. maps to the 2D image of a particular cube map target.
  48571. major axis
  48572. direction target sc tc ma
  48573. ---------- --------------------------------- --- --- ---
  48574. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  48575. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  48576. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  48577. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  48578. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  48579. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  48580. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  48581. an updated (s,t) is calculated as follows
  48582. s = ( sc/|ma| + 1 ) / 2
  48583. t = ( tc/|ma| + 1 ) / 2
  48584. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  48585. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  48586. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  48587. */
  48588. // Note this method return U and V in range from 0 to size-1
  48589. // SL END
  48590. // Store the information in vector3 for convenience (faceindex, u, v)
  48591. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  48592. var maxCoord;
  48593. var faceIdx;
  48594. //absolute value 3
  48595. var absX = Math.abs(x);
  48596. var absY = Math.abs(y);
  48597. var absZ = Math.abs(z);
  48598. if (absX >= absY && absX >= absZ) {
  48599. maxCoord = absX;
  48600. if (x >= 0) {
  48601. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  48602. }
  48603. else {
  48604. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  48605. }
  48606. }
  48607. else if (absY >= absX && absY >= absZ) {
  48608. maxCoord = absY;
  48609. if (y >= 0) {
  48610. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  48611. }
  48612. else {
  48613. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  48614. }
  48615. }
  48616. else {
  48617. maxCoord = absZ;
  48618. if (z >= 0) {
  48619. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  48620. }
  48621. else {
  48622. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  48623. }
  48624. }
  48625. //divide through by max coord so face vector lies on cube face
  48626. var scale = 1 / maxCoord;
  48627. x *= scale;
  48628. y *= scale;
  48629. z *= scale;
  48630. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  48631. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  48632. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  48633. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  48634. // Modify original AMD code to return value from 0 to Size - 1
  48635. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  48636. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  48637. PMREMGenerator._vectorTemp.x = faceIdx;
  48638. PMREMGenerator._vectorTemp.y = u;
  48639. PMREMGenerator._vectorTemp.z = v;
  48640. return PMREMGenerator._vectorTemp;
  48641. };
  48642. //--------------------------------------------------------------------------------------
  48643. //Original code from Ignacio CastaÒo
  48644. // This formula is from Manne ÷hrstrˆm's thesis.
  48645. // Take two coordiantes in the range [-1, 1] that define a portion of a
  48646. // cube face and return the area of the projection of that portion on the
  48647. // surface of the sphere.
  48648. //--------------------------------------------------------------------------------------
  48649. PMREMGenerator.prototype.areaElement = function (x, y) {
  48650. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  48651. };
  48652. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  48653. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  48654. // (+ 0.5f is for texel center addressing)
  48655. u = (2.0 * (u + 0.5) / size) - 1.0;
  48656. v = (2.0 * (v + 0.5) / size) - 1.0;
  48657. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  48658. var invResolution = 1.0 / size;
  48659. // U and V are the -1..1 texture coordinate on the current face.
  48660. // Get projected area for this texel
  48661. var x0 = u - invResolution;
  48662. var y0 = v - invResolution;
  48663. var x1 = u + invResolution;
  48664. var y1 = v + invResolution;
  48665. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  48666. return solidAngle;
  48667. };
  48668. //--------------------------------------------------------------------------------------
  48669. //The key to the speed of these filtering routines is to quickly define a per-face
  48670. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  48671. // Later these pixels are selectively processed based on their dot products to see if
  48672. // they reside within the filtering cone.
  48673. //
  48674. //This is done by computing the smallest per-texel angle to get a conservative estimate
  48675. // of the number of texels needed to be covered in width and height order to filter the
  48676. // region. the bounding box for the center taps face is defined first, and if the
  48677. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  48678. // defined next
  48679. //--------------------------------------------------------------------------------------
  48680. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  48681. // note that pixels within these regions may be rejected
  48682. // based on the anlge
  48683. var iCubeFace;
  48684. var u;
  48685. var v;
  48686. // bounding box per face to specify region to process
  48687. var filterExtents = [];
  48688. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  48689. filterExtents.push(new CMGBoundinBox());
  48690. }
  48691. // min angle a src texel can cover (in degrees)
  48692. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  48693. // angle about center tap to define filter cone
  48694. // filter angle is 1/2 the cone angle
  48695. var filterAngle = filterConeAngle / 2.0;
  48696. //ensure filter angle is larger than a texel
  48697. if (filterAngle < srcTexelAngle) {
  48698. filterAngle = srcTexelAngle;
  48699. }
  48700. //ensure filter cone is always smaller than the hemisphere
  48701. if (filterAngle > 90.0) {
  48702. filterAngle = 90.0;
  48703. }
  48704. // the maximum number of texels in 1D the filter cone angle will cover
  48705. // used to determine bounding box size for filter extents
  48706. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  48707. // ensure conservative region always covers at least one texel
  48708. if (filterSize < 1) {
  48709. filterSize = 1;
  48710. }
  48711. // dotProdThresh threshold based on cone angle to determine whether or not taps
  48712. // reside within the cone angle
  48713. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  48714. // process required faces
  48715. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  48716. //iterate over dst cube map face texel
  48717. for (v = 0; v < dstSize; v++) {
  48718. for (u = 0; u < dstSize; u++) {
  48719. //get center tap direction
  48720. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  48721. //clear old per-face filter extents
  48722. this.clearFilterExtents(filterExtents);
  48723. //define per-face filter extents
  48724. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  48725. //perform filtering of src faces using filter extents
  48726. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  48727. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  48728. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  48729. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  48730. }
  48731. }
  48732. }
  48733. };
  48734. //--------------------------------------------------------------------------------------
  48735. //Clear filter extents for the 6 cube map faces
  48736. //--------------------------------------------------------------------------------------
  48737. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  48738. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  48739. filterExtents[iCubeFaces].clear();
  48740. }
  48741. };
  48742. //--------------------------------------------------------------------------------------
  48743. //Define per-face bounding box filter extents
  48744. //
  48745. // These define conservative texel regions in each of the faces the filter can possibly
  48746. // process. When the pixels in the regions are actually processed, the dot product
  48747. // between the tap vector and the center tap vector is used to determine the weight of
  48748. // the tap and whether or not the tap is within the cone.
  48749. //
  48750. //--------------------------------------------------------------------------------------
  48751. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  48752. //neighboring face and bleed over amount, and width of BBOX for
  48753. // left, right, top, and bottom edges of this face
  48754. var bleedOverAmount = [0, 0, 0, 0];
  48755. var bleedOverBBoxMin = [0, 0, 0, 0];
  48756. var bleedOverBBoxMax = [0, 0, 0, 0];
  48757. var neighborFace;
  48758. var neighborEdge;
  48759. var oppositeFaceIdx;
  48760. //get face idx, and u, v info from center tap dir
  48761. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  48762. var faceIdx = result.x;
  48763. var u = result.y;
  48764. var v = result.z;
  48765. //define bbox size within face
  48766. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  48767. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  48768. filterExtents[faceIdx].clampMin(0, 0, 0);
  48769. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  48770. //u and v extent in face corresponding to center tap
  48771. var minU = filterExtents[faceIdx].min.x;
  48772. var minV = filterExtents[faceIdx].min.y;
  48773. var maxU = filterExtents[faceIdx].max.x;
  48774. var maxV = filterExtents[faceIdx].max.y;
  48775. //bleed over amounts for face across u=0 edge (left)
  48776. bleedOverAmount[0] = (bboxSize - u);
  48777. bleedOverBBoxMin[0] = minV;
  48778. bleedOverBBoxMax[0] = maxV;
  48779. //bleed over amounts for face across u=1 edge (right)
  48780. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  48781. bleedOverBBoxMin[1] = minV;
  48782. bleedOverBBoxMax[1] = maxV;
  48783. //bleed over to face across v=0 edge (up)
  48784. bleedOverAmount[2] = (bboxSize - v);
  48785. bleedOverBBoxMin[2] = minU;
  48786. bleedOverBBoxMax[2] = maxU;
  48787. //bleed over to face across v=1 edge (down)
  48788. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  48789. bleedOverBBoxMin[3] = minU;
  48790. bleedOverBBoxMax[3] = maxU;
  48791. //compute bleed over regions in neighboring faces
  48792. for (var i = 0; i < 4; i++) {
  48793. if (bleedOverAmount[i] > 0) {
  48794. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  48795. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  48796. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  48797. // be flipped: the cases are
  48798. // if a left edge mates with a left or bottom edge on the neighbor
  48799. // if a top edge mates with a top or right edge on the neighbor
  48800. // if a right edge mates with a right or top edge on the neighbor
  48801. // if a bottom edge mates with a bottom or left edge on the neighbor
  48802. //Seeing as the edges are enumerated as follows
  48803. // left =0
  48804. // right =1
  48805. // top =2
  48806. // bottom =3
  48807. //
  48808. // so if the edge enums are the same, or the sum of the enums == 3,
  48809. // the bbox needs to be flipped
  48810. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  48811. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  48812. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  48813. }
  48814. //The way the bounding box is extended onto the neighboring face
  48815. // depends on which edge of neighboring face abuts with this one
  48816. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  48817. case PMREMGenerator.CP_EDGE_LEFT:
  48818. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  48819. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  48820. break;
  48821. case PMREMGenerator.CP_EDGE_RIGHT:
  48822. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  48823. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  48824. break;
  48825. case PMREMGenerator.CP_EDGE_TOP:
  48826. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  48827. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  48828. break;
  48829. case PMREMGenerator.CP_EDGE_BOTTOM:
  48830. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  48831. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  48832. break;
  48833. }
  48834. //clamp filter extents in non-center tap faces to remain within surface
  48835. filterExtents[neighborFace].clampMin(0, 0, 0);
  48836. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  48837. }
  48838. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  48839. // from the center tap face, then process the opposite face entirely for now.
  48840. //Note that the cases in which this happens, what usually happens is that
  48841. // more than one edge bleeds onto the opposite face, and the bounding box
  48842. // encompasses the entire cube map face.
  48843. if (bleedOverAmount[i] > srcSize) {
  48844. //determine opposite face
  48845. switch (faceIdx) {
  48846. case PMREMGenerator.CP_FACE_X_POS:
  48847. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  48848. break;
  48849. case PMREMGenerator.CP_FACE_X_NEG:
  48850. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  48851. break;
  48852. case PMREMGenerator.CP_FACE_Y_POS:
  48853. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  48854. break;
  48855. case PMREMGenerator.CP_FACE_Y_NEG:
  48856. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  48857. break;
  48858. case PMREMGenerator.CP_FACE_Z_POS:
  48859. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  48860. break;
  48861. case PMREMGenerator.CP_FACE_Z_NEG:
  48862. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  48863. break;
  48864. default:
  48865. break;
  48866. }
  48867. //just encompass entire face for now
  48868. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  48869. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  48870. }
  48871. }
  48872. };
  48873. //--------------------------------------------------------------------------------------
  48874. //ProcessFilterExtents
  48875. // Process bounding box in each cube face
  48876. //
  48877. //--------------------------------------------------------------------------------------
  48878. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  48879. //accumulators are 64-bit floats in order to have the precision needed
  48880. // over a summation of a large number of pixels
  48881. var dstAccum = [0, 0, 0, 0];
  48882. var weightAccum = 0;
  48883. var k = 0;
  48884. var nSrcChannels = this.numChannels;
  48885. // norm cube map and srcCubeMap have same face width
  48886. var faceWidth = srcSize;
  48887. //amount to add to pointer to move to next scanline in images
  48888. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  48889. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  48890. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  48891. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  48892. // iterate over cubefaces
  48893. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  48894. //if bbox is non empty
  48895. if (!filterExtents[iFaceIdx].empty()) {
  48896. var uStart = filterExtents[iFaceIdx].min.x;
  48897. var vStart = filterExtents[iFaceIdx].min.y;
  48898. var uEnd = filterExtents[iFaceIdx].max.x;
  48899. var vEnd = filterExtents[iFaceIdx].max.y;
  48900. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  48901. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  48902. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  48903. for (var v = vStart; v <= vEnd; v++) {
  48904. var normCubeRowWalk = 0;
  48905. var srcCubeRowWalk = 0;
  48906. for (var u = uStart; u <= uEnd; u++) {
  48907. //pointer to direction in cube map associated with texel
  48908. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  48909. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  48910. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  48911. //check dot product to see if texel is within cone
  48912. var tapDotProd = texelVectX * centerTapDir.x +
  48913. texelVectY * centerTapDir.y +
  48914. texelVectZ * centerTapDir.z;
  48915. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  48916. //solid angle stored in 4th channel of normalizer/solid angle cube map
  48917. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  48918. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  48919. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  48920. // so just adding one to specularpower do the trick.
  48921. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  48922. //iterate over channels
  48923. for (k = 0; k < nSrcChannels; k++) {
  48924. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  48925. srcCubeRowWalk++;
  48926. }
  48927. weightAccum += weight; //accumulate weight
  48928. }
  48929. else {
  48930. //step across source pixel
  48931. srcCubeRowWalk += nSrcChannels;
  48932. }
  48933. normCubeRowWalk += 4; // 4 channels per norm cube map.
  48934. }
  48935. startIndexNormCubeMap += normCubePitch;
  48936. startIndexSrcCubeMap += srcCubePitch;
  48937. }
  48938. }
  48939. }
  48940. //divide through by weights if weight is non zero
  48941. if (weightAccum != 0.0) {
  48942. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  48943. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  48944. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  48945. if (this.numChannels > 3) {
  48946. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  48947. }
  48948. }
  48949. else {
  48950. // otherwise sample nearest
  48951. // get face idx and u, v texel coordinate in face
  48952. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  48953. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  48954. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  48955. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  48956. if (this.numChannels > 3) {
  48957. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  48958. }
  48959. }
  48960. return PMREMGenerator._vectorTemp;
  48961. };
  48962. //--------------------------------------------------------------------------------------
  48963. // Fixup cube edges
  48964. //
  48965. // average texels on cube map faces across the edges
  48966. // WARP/BENT Method Only.
  48967. //--------------------------------------------------------------------------------------
  48968. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  48969. var k;
  48970. var j;
  48971. var i;
  48972. var iFace;
  48973. var iCorner = 0;
  48974. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  48975. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  48976. // note that if functionality to filter across the three texels for each corner, then
  48977. //indexed by corner and face idx. the array contains the face the start points belongs to.
  48978. var cornerPtr = [
  48979. [[], [], []],
  48980. [[], [], []],
  48981. [[], [], []],
  48982. [[], [], []],
  48983. [[], [], []],
  48984. [[], [], []],
  48985. [[], [], []],
  48986. [[], [], []]
  48987. ];
  48988. //if there is no fixup, or fixup width = 0, do nothing
  48989. if (cubeMapSize < 1) {
  48990. return;
  48991. }
  48992. //special case 1x1 cubemap, average face colors
  48993. if (cubeMapSize == 1) {
  48994. //iterate over channels
  48995. for (k = 0; k < this.numChannels; k++) {
  48996. var accum = 0.0;
  48997. //iterate over faces to accumulate face colors
  48998. for (iFace = 0; iFace < 6; iFace++) {
  48999. accum += cubeMap[iFace][k];
  49000. }
  49001. //compute average over 6 face colors
  49002. accum /= 6.0;
  49003. //iterate over faces to distribute face colors
  49004. for (iFace = 0; iFace < 6; iFace++) {
  49005. cubeMap[iFace][k] = accum;
  49006. }
  49007. }
  49008. return;
  49009. }
  49010. //iterate over faces to collect list of corner texel pointers
  49011. for (iFace = 0; iFace < 6; iFace++) {
  49012. //the 4 corner pointers for this face
  49013. faceCornerStartIndicies[0] = [iFace, 0];
  49014. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  49015. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  49016. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  49017. //iterate over face corners to collect cube corner pointers
  49018. for (iCorner = 0; iCorner < 4; iCorner++) {
  49019. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  49020. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  49021. cornerNumPtrs[corner]++;
  49022. }
  49023. }
  49024. //iterate over corners to average across corner tap values
  49025. for (iCorner = 0; iCorner < 8; iCorner++) {
  49026. for (k = 0; k < this.numChannels; k++) {
  49027. var cornerTapAccum = 0.0;
  49028. //iterate over corner texels and average results
  49029. for (i = 0; i < 3; i++) {
  49030. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  49031. }
  49032. //divide by 3 to compute average of corner tap values
  49033. cornerTapAccum *= (1.0 / 3.0);
  49034. //iterate over corner texels and average results
  49035. for (i = 0; i < 3; i++) {
  49036. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  49037. }
  49038. }
  49039. }
  49040. //iterate over the twelve edges of the cube to average across edges
  49041. for (i = 0; i < 12; i++) {
  49042. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  49043. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  49044. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  49045. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  49046. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  49047. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  49048. var edgeWalk = 0;
  49049. var neighborEdgeWalk = 0;
  49050. //Determine walking pointers based on edge type
  49051. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  49052. switch (edge) {
  49053. case PMREMGenerator.CP_EDGE_LEFT:
  49054. // no change to faceEdgeStartPtr
  49055. edgeWalk = this.numChannels * cubeMapSize;
  49056. break;
  49057. case PMREMGenerator.CP_EDGE_RIGHT:
  49058. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49059. edgeWalk = this.numChannels * cubeMapSize;
  49060. break;
  49061. case PMREMGenerator.CP_EDGE_TOP:
  49062. // no change to faceEdgeStartPtr
  49063. edgeWalk = this.numChannels;
  49064. break;
  49065. case PMREMGenerator.CP_EDGE_BOTTOM:
  49066. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49067. edgeWalk = this.numChannels;
  49068. break;
  49069. }
  49070. //For certain types of edge abutments, the neighbor edge walk needs to
  49071. // be flipped: the cases are
  49072. // if a left edge mates with a left or bottom edge on the neighbor
  49073. // if a top edge mates with a top or right edge on the neighbor
  49074. // if a right edge mates with a right or top edge on the neighbor
  49075. // if a bottom edge mates with a bottom or left edge on the neighbor
  49076. //Seeing as the edges are enumerated as follows
  49077. // left =0
  49078. // right =1
  49079. // top =2
  49080. // bottom =3
  49081. //
  49082. //If the edge enums are the same, or the sum of the enums == 3,
  49083. // the neighbor edge walk needs to be flipped
  49084. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  49085. switch (neighborEdge) {
  49086. case PMREMGenerator.CP_EDGE_LEFT:
  49087. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  49088. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49089. break;
  49090. case PMREMGenerator.CP_EDGE_RIGHT:
  49091. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49092. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49093. break;
  49094. case PMREMGenerator.CP_EDGE_TOP:
  49095. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49096. neighborEdgeWalk = -this.numChannels;
  49097. break;
  49098. case PMREMGenerator.CP_EDGE_BOTTOM:
  49099. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49100. neighborEdgeWalk = -this.numChannels;
  49101. break;
  49102. }
  49103. }
  49104. else {
  49105. //swapped direction neighbor edge walk
  49106. switch (neighborEdge) {
  49107. case PMREMGenerator.CP_EDGE_LEFT:
  49108. //no change to neighborEdgeStartPtr for this case since it points
  49109. // to the upper left corner already
  49110. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49111. break;
  49112. case PMREMGenerator.CP_EDGE_RIGHT:
  49113. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49114. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49115. break;
  49116. case PMREMGenerator.CP_EDGE_TOP:
  49117. //no change to neighborEdgeStartPtr for this case since it points
  49118. // to the upper left corner already
  49119. neighborEdgeWalk = this.numChannels;
  49120. break;
  49121. case PMREMGenerator.CP_EDGE_BOTTOM:
  49122. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49123. neighborEdgeWalk = this.numChannels;
  49124. break;
  49125. }
  49126. }
  49127. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  49128. //nearby neighborhood
  49129. //step ahead one texel on edge
  49130. edgeStartIndex += edgeWalk;
  49131. neighborEdgeStartIndex += neighborEdgeWalk;
  49132. // note that this loop does not process the corner texels, since they have already been
  49133. // averaged across faces across earlier
  49134. for (j = 1; j < (cubeMapSize - 1); j++) {
  49135. //for each set of taps along edge, average them
  49136. // and rewrite the results into the edges
  49137. for (k = 0; k < this.numChannels; k++) {
  49138. var edgeTap = cubeMap[face][edgeStartIndex + k];
  49139. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  49140. //compute average of tap intensity values
  49141. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  49142. //propagate average of taps to edge taps
  49143. cubeMap[face][edgeStartIndex + k] = avgTap;
  49144. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  49145. }
  49146. edgeStartIndex += edgeWalk;
  49147. neighborEdgeStartIndex += neighborEdgeWalk;
  49148. }
  49149. }
  49150. };
  49151. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  49152. PMREMGenerator.CP_UDIR = 0;
  49153. PMREMGenerator.CP_VDIR = 1;
  49154. PMREMGenerator.CP_FACEAXIS = 2;
  49155. //used to index cube faces
  49156. PMREMGenerator.CP_FACE_X_POS = 0;
  49157. PMREMGenerator.CP_FACE_X_NEG = 1;
  49158. PMREMGenerator.CP_FACE_Y_POS = 2;
  49159. PMREMGenerator.CP_FACE_Y_NEG = 3;
  49160. PMREMGenerator.CP_FACE_Z_POS = 4;
  49161. PMREMGenerator.CP_FACE_Z_NEG = 5;
  49162. //used to index image edges
  49163. // NOTE.. the actual number corresponding to the edge is important
  49164. // do not change these, or the code will break
  49165. //
  49166. // CP_EDGE_LEFT is u = 0
  49167. // CP_EDGE_RIGHT is u = width-1
  49168. // CP_EDGE_TOP is v = 0
  49169. // CP_EDGE_BOTTOM is v = height-1
  49170. PMREMGenerator.CP_EDGE_LEFT = 0;
  49171. PMREMGenerator.CP_EDGE_RIGHT = 1;
  49172. PMREMGenerator.CP_EDGE_TOP = 2;
  49173. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  49174. //corners of CUBE map (P or N specifys if it corresponds to the
  49175. // positive or negative direction each of X, Y, and Z
  49176. PMREMGenerator.CP_CORNER_NNN = 0;
  49177. PMREMGenerator.CP_CORNER_NNP = 1;
  49178. PMREMGenerator.CP_CORNER_NPN = 2;
  49179. PMREMGenerator.CP_CORNER_NPP = 3;
  49180. PMREMGenerator.CP_CORNER_PNN = 4;
  49181. PMREMGenerator.CP_CORNER_PNP = 5;
  49182. PMREMGenerator.CP_CORNER_PPN = 6;
  49183. PMREMGenerator.CP_CORNER_PPP = 7;
  49184. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  49185. //3x2 matrices that map cube map indexing vectors in 3d
  49186. // (after face selection and divide through by the
  49187. // _ABSOLUTE VALUE_ of the max coord)
  49188. // into NVC space
  49189. //Note this currently assumes the D3D cube face ordering and orientation
  49190. PMREMGenerator._sgFace2DMapping = [
  49191. //XPOS face
  49192. [[0, 0, -1],
  49193. [0, -1, 0],
  49194. [1, 0, 0]],
  49195. //XNEG face
  49196. [[0, 0, 1],
  49197. [0, -1, 0],
  49198. [-1, 0, 0]],
  49199. //YPOS face
  49200. [[1, 0, 0],
  49201. [0, 0, 1],
  49202. [0, 1, 0]],
  49203. //YNEG face
  49204. [[1, 0, 0],
  49205. [0, 0, -1],
  49206. [0, -1, 0]],
  49207. //ZPOS face
  49208. [[1, 0, 0],
  49209. [0, -1, 0],
  49210. [0, 0, 1]],
  49211. //ZNEG face
  49212. [[-1, 0, 0],
  49213. [0, -1, 0],
  49214. [0, 0, -1]],
  49215. ];
  49216. //------------------------------------------------------------------------------
  49217. // D3D cube map face specification
  49218. // mapping from 3D x,y,z cube map lookup coordinates
  49219. // to 2D within face u,v coordinates
  49220. //
  49221. // --------------------> U direction
  49222. // | (within-face texture space)
  49223. // | _____
  49224. // | | |
  49225. // | | +Y |
  49226. // | _____|_____|_____ _____
  49227. // | | | | | |
  49228. // | | -X | +Z | +X | -Z |
  49229. // | |_____|_____|_____|_____|
  49230. // | | |
  49231. // | | -Y |
  49232. // | |_____|
  49233. // |
  49234. // v V direction
  49235. // (within-face texture space)
  49236. //------------------------------------------------------------------------------
  49237. //Information about neighbors and how texture coorrdinates change across faces
  49238. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  49239. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  49240. //Note this currently assumes the D3D cube face ordering and orientation
  49241. PMREMGenerator._sgCubeNgh = [
  49242. //XPOS face
  49243. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49244. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49245. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49246. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  49247. //XNEG face
  49248. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49249. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  49250. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  49251. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  49252. //YPOS face
  49253. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  49254. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  49255. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  49256. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  49257. //YNEG face
  49258. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  49259. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49260. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49261. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  49262. //ZPOS face
  49263. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49264. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  49265. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49266. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  49267. //ZNEG face
  49268. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49269. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49270. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  49271. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  49272. ];
  49273. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  49274. // this table is used to average over the edges.
  49275. PMREMGenerator._sgCubeEdgeList = [
  49276. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  49277. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49278. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  49279. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49280. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49281. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49282. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  49283. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  49284. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  49285. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49286. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  49287. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  49288. ];
  49289. //Information about which of the 8 cube corners are correspond to the
  49290. // the 4 corners in each cube face
  49291. // the order is upper left, upper right, lower left, lower right
  49292. PMREMGenerator._sgCubeCornerList = [
  49293. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  49294. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  49295. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  49296. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  49297. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  49298. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  49299. ];
  49300. return PMREMGenerator;
  49301. }());
  49302. Internals.PMREMGenerator = PMREMGenerator;
  49303. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49304. })(BABYLON || (BABYLON = {}));
  49305. var BABYLON;
  49306. (function (BABYLON) {
  49307. /**
  49308. * This represents a texture coming from an HDR input.
  49309. *
  49310. * The only supported format is currently panorama picture stored in RGBE format.
  49311. * Example of such files can be found on HDRLib: http://hdrlib.com/
  49312. */
  49313. var HDRCubeTexture = (function (_super) {
  49314. __extends(HDRCubeTexture, _super);
  49315. /**
  49316. * Instantiates an HDRTexture from the following parameters.
  49317. *
  49318. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  49319. * @param scene The scene the texture will be used in
  49320. * @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.
  49321. * @param noMipmap Forces to not generate the mipmap if true
  49322. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  49323. * @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)
  49324. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  49325. */
  49326. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  49327. if (noMipmap === void 0) { noMipmap = false; }
  49328. if (generateHarmonics === void 0) { generateHarmonics = true; }
  49329. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  49330. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  49331. _super.call(this, scene);
  49332. this._useInGammaSpace = false;
  49333. this._generateHarmonics = true;
  49334. this._isBABYLONPreprocessed = false;
  49335. /**
  49336. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  49337. */
  49338. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49339. /**
  49340. * The spherical polynomial data extracted from the texture.
  49341. */
  49342. this.sphericalPolynomial = null;
  49343. /**
  49344. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  49345. * This is usefull at run time to apply the good shader.
  49346. */
  49347. this.isPMREM = false;
  49348. if (!url) {
  49349. return;
  49350. }
  49351. this.name = url;
  49352. this.url = url;
  49353. this.hasAlpha = false;
  49354. this.isCube = true;
  49355. this._textureMatrix = BABYLON.Matrix.Identity();
  49356. if (size) {
  49357. this._isBABYLONPreprocessed = false;
  49358. this._noMipmap = noMipmap;
  49359. this._size = size;
  49360. this._useInGammaSpace = useInGammaSpace;
  49361. this._usePMREMGenerator = usePMREMGenerator &&
  49362. scene.getEngine().getCaps().textureLOD &&
  49363. this.getScene().getEngine().getCaps().textureFloat &&
  49364. !this._useInGammaSpace;
  49365. }
  49366. else {
  49367. this._isBABYLONPreprocessed = true;
  49368. this._noMipmap = false;
  49369. this._useInGammaSpace = false;
  49370. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  49371. this.getScene().getEngine().getCaps().textureFloat &&
  49372. !this._useInGammaSpace;
  49373. }
  49374. this.isPMREM = this._usePMREMGenerator;
  49375. this._texture = this._getFromCache(url, this._noMipmap);
  49376. if (!this._texture) {
  49377. if (!scene.useDelayedTextureLoading) {
  49378. this.loadTexture();
  49379. }
  49380. else {
  49381. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49382. }
  49383. }
  49384. }
  49385. /**
  49386. * Occurs when the file is a preprocessed .babylon.hdr file.
  49387. */
  49388. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  49389. var _this = this;
  49390. var mipLevels = 0;
  49391. var floatArrayView = null;
  49392. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  49393. var mips = [];
  49394. var startIndex = 30;
  49395. for (var level = 0; level < mipLevels; level++) {
  49396. mips.push([]);
  49397. // Fill each pixel of the mip level.
  49398. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  49399. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49400. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  49401. mips[level].push(faceData);
  49402. startIndex += faceSize;
  49403. }
  49404. }
  49405. return mips;
  49406. } : null;
  49407. var callback = function (buffer) {
  49408. // Create Native Array Views
  49409. var intArrayView = new Int32Array(buffer);
  49410. floatArrayView = new Float32Array(buffer);
  49411. // Fill header.
  49412. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  49413. _this._size = intArrayView[1]; // CubeMap max mip face size.
  49414. // Update Texture Information.
  49415. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  49416. // Fill polynomial information.
  49417. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  49418. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  49419. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  49420. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  49421. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  49422. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  49423. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  49424. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  49425. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  49426. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  49427. // Fill pixel data.
  49428. mipLevels = intArrayView[29]; // Number of mip levels.
  49429. var startIndex = 30;
  49430. var data = [];
  49431. var faceSize = Math.pow(_this._size, 2) * 3;
  49432. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49433. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  49434. startIndex += faceSize;
  49435. }
  49436. var results = [];
  49437. var byteArray = null;
  49438. // Push each faces.
  49439. for (var k = 0; k < 6; k++) {
  49440. var dataFace = null;
  49441. // If special cases.
  49442. if (!mipmapGenerator) {
  49443. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  49444. dataFace = data[j];
  49445. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  49446. // 3 channels of 1 bytes per pixel in bytes.
  49447. var byteBuffer = new ArrayBuffer(faceSize);
  49448. byteArray = new Uint8Array(byteBuffer);
  49449. }
  49450. for (var i = 0; i < _this._size * _this._size; i++) {
  49451. // Put in gamma space if requested.
  49452. if (_this._useInGammaSpace) {
  49453. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  49454. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  49455. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  49456. }
  49457. // Convert to int texture for fallback.
  49458. if (byteArray) {
  49459. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  49460. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  49461. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  49462. // May use luminance instead if the result is not accurate.
  49463. var max = Math.max(Math.max(r, g), b);
  49464. if (max > 255) {
  49465. var scale = 255 / max;
  49466. r *= scale;
  49467. g *= scale;
  49468. b *= scale;
  49469. }
  49470. byteArray[(i * 3) + 0] = r;
  49471. byteArray[(i * 3) + 1] = g;
  49472. byteArray[(i * 3) + 2] = b;
  49473. }
  49474. }
  49475. }
  49476. else {
  49477. dataFace = data[k];
  49478. }
  49479. // Fill the array accordingly.
  49480. if (byteArray) {
  49481. results.push(byteArray);
  49482. }
  49483. else {
  49484. results.push(dataFace);
  49485. }
  49486. }
  49487. return results;
  49488. };
  49489. 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);
  49490. };
  49491. /**
  49492. * Occurs when the file is raw .hdr file.
  49493. */
  49494. HDRCubeTexture.prototype.loadHDRTexture = function () {
  49495. var _this = this;
  49496. var callback = function (buffer) {
  49497. // Extract the raw linear data.
  49498. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  49499. // Generate harmonics if needed.
  49500. if (_this._generateHarmonics) {
  49501. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  49502. }
  49503. var results = [];
  49504. var byteArray = null;
  49505. // Push each faces.
  49506. for (var j = 0; j < 6; j++) {
  49507. // Create uintarray fallback.
  49508. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  49509. // 3 channels of 1 bytes per pixel in bytes.
  49510. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  49511. byteArray = new Uint8Array(byteBuffer);
  49512. }
  49513. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  49514. // If special cases.
  49515. if (_this._useInGammaSpace || byteArray) {
  49516. for (var i = 0; i < _this._size * _this._size; i++) {
  49517. // Put in gamma space if requested.
  49518. if (_this._useInGammaSpace) {
  49519. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  49520. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  49521. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  49522. }
  49523. // Convert to int texture for fallback.
  49524. if (byteArray) {
  49525. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  49526. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  49527. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  49528. // May use luminance instead if the result is not accurate.
  49529. var max = Math.max(Math.max(r, g), b);
  49530. if (max > 255) {
  49531. var scale = 255 / max;
  49532. r *= scale;
  49533. g *= scale;
  49534. b *= scale;
  49535. }
  49536. byteArray[(i * 3) + 0] = r;
  49537. byteArray[(i * 3) + 1] = g;
  49538. byteArray[(i * 3) + 2] = b;
  49539. }
  49540. }
  49541. }
  49542. if (byteArray) {
  49543. results.push(byteArray);
  49544. }
  49545. else {
  49546. results.push(dataFace);
  49547. }
  49548. }
  49549. return results;
  49550. };
  49551. var mipmapGenerator = null;
  49552. if (!this._noMipmap &&
  49553. this._usePMREMGenerator) {
  49554. mipmapGenerator = function (data) {
  49555. // Custom setup of the generator matching with the PBR shader values.
  49556. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  49557. return generator.filterCubeMap();
  49558. };
  49559. }
  49560. 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);
  49561. };
  49562. /**
  49563. * Starts the loading process of the texture.
  49564. */
  49565. HDRCubeTexture.prototype.loadTexture = function () {
  49566. if (this._isBABYLONPreprocessed) {
  49567. this.loadBabylonTexture();
  49568. }
  49569. else {
  49570. this.loadHDRTexture();
  49571. }
  49572. };
  49573. HDRCubeTexture.prototype.clone = function () {
  49574. var size = this._isBABYLONPreprocessed ? null : this._size;
  49575. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  49576. // Base texture
  49577. newTexture.level = this.level;
  49578. newTexture.wrapU = this.wrapU;
  49579. newTexture.wrapV = this.wrapV;
  49580. newTexture.coordinatesIndex = this.coordinatesIndex;
  49581. newTexture.coordinatesMode = this.coordinatesMode;
  49582. return newTexture;
  49583. };
  49584. // Methods
  49585. HDRCubeTexture.prototype.delayLoad = function () {
  49586. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49587. return;
  49588. }
  49589. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49590. this._texture = this._getFromCache(this.url, this._noMipmap);
  49591. if (!this._texture) {
  49592. this.loadTexture();
  49593. }
  49594. };
  49595. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  49596. return this._textureMatrix;
  49597. };
  49598. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49599. var texture = null;
  49600. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  49601. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  49602. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  49603. texture.name = parsedTexture.name;
  49604. texture.hasAlpha = parsedTexture.hasAlpha;
  49605. texture.level = parsedTexture.level;
  49606. texture.coordinatesMode = parsedTexture.coordinatesMode;
  49607. }
  49608. return texture;
  49609. };
  49610. HDRCubeTexture.prototype.serialize = function () {
  49611. if (!this.name) {
  49612. return null;
  49613. }
  49614. var serializationObject = {};
  49615. serializationObject.name = this.name;
  49616. serializationObject.hasAlpha = this.hasAlpha;
  49617. serializationObject.isCube = true;
  49618. serializationObject.level = this.level;
  49619. serializationObject.size = this._size;
  49620. serializationObject.coordinatesMode = this.coordinatesMode;
  49621. serializationObject.useInGammaSpace = this._useInGammaSpace;
  49622. serializationObject.generateHarmonics = this._generateHarmonics;
  49623. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  49624. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  49625. serializationObject.customType = "BABYLON.HDRCubeTexture";
  49626. return serializationObject;
  49627. };
  49628. /**
  49629. * Saves as a file the data contained in the texture in a binary format.
  49630. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  49631. * as the spherical used in the lighting.
  49632. * @param url The HDR file url.
  49633. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  49634. * @param onError Method called if any error happens during download.
  49635. * @return The packed binary data.
  49636. */
  49637. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  49638. if (onError === void 0) { onError = null; }
  49639. var callback = function (buffer) {
  49640. var data = new Blob([buffer], { type: 'application/octet-stream' });
  49641. // Returns a URL you can use as a href.
  49642. var objUrl = window.URL.createObjectURL(data);
  49643. // Simulates a link to it and click to dowload.
  49644. var a = document.createElement("a");
  49645. document.body.appendChild(a);
  49646. a.style.display = "none";
  49647. a.href = objUrl;
  49648. a.download = "envmap.babylon.hdr";
  49649. a.click();
  49650. };
  49651. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  49652. };
  49653. /**
  49654. * Serializes the data contained in the texture in a binary format.
  49655. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  49656. * as the spherical used in the lighting.
  49657. * @param url The HDR file url.
  49658. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  49659. * @param onError Method called if any error happens during download.
  49660. * @return The packed binary data.
  49661. */
  49662. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  49663. if (onError === void 0) { onError = null; }
  49664. // Needs the url tho create the texture.
  49665. if (!url) {
  49666. return null;
  49667. }
  49668. // Check Power of two size.
  49669. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  49670. return null;
  49671. }
  49672. var getDataCallback = function (dataBuffer) {
  49673. // Extract the raw linear data.
  49674. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  49675. // Generate harmonics if needed.
  49676. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  49677. // Generate seamless faces
  49678. var mipGeneratorArray = [];
  49679. // Data are known to be in +X +Y +Z -X -Y -Z
  49680. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  49681. mipGeneratorArray.push(cubeData.right); // +X
  49682. mipGeneratorArray.push(cubeData.left); // -X
  49683. mipGeneratorArray.push(cubeData.up); // +Y
  49684. mipGeneratorArray.push(cubeData.down); // -Y
  49685. mipGeneratorArray.push(cubeData.front); // +Z
  49686. mipGeneratorArray.push(cubeData.back); // -Z
  49687. // Custom setup of the generator matching with the PBR shader values.
  49688. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  49689. var mippedData = generator.filterCubeMap();
  49690. // Compute required byte length.
  49691. var byteLength = 1 * 4; // Raw Data Version int32.
  49692. byteLength += 4; // CubeMap max mip face size int32.
  49693. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  49694. // Add data size.
  49695. byteLength += 4; // Number of mip levels int32.
  49696. for (var level = 0; level < mippedData.length; level++) {
  49697. var mipSize = size >> level;
  49698. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  49699. }
  49700. // Prepare binary structure.
  49701. var buffer = new ArrayBuffer(byteLength);
  49702. var intArrayView = new Int32Array(buffer);
  49703. var floatArrayView = new Float32Array(buffer);
  49704. // Fill header.
  49705. intArrayView[0] = 1; // Version 1.
  49706. intArrayView[1] = size; // CubeMap max mip face size.
  49707. // Fill polynomial information.
  49708. sphericalPolynomial.x.toArray(floatArrayView, 2);
  49709. sphericalPolynomial.y.toArray(floatArrayView, 5);
  49710. sphericalPolynomial.z.toArray(floatArrayView, 8);
  49711. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  49712. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  49713. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  49714. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  49715. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  49716. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  49717. // Fill pixel data.
  49718. intArrayView[29] = mippedData.length; // Number of mip levels.
  49719. var startIndex = 30;
  49720. for (var level = 0; level < mippedData.length; level++) {
  49721. // Fill each pixel of the mip level.
  49722. var faceSize = Math.pow(size >> level, 2) * 3;
  49723. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49724. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  49725. startIndex += faceSize;
  49726. }
  49727. }
  49728. // Callback.
  49729. callback(buffer);
  49730. };
  49731. // Download and process.
  49732. BABYLON.Tools.LoadFile(url, function (data) {
  49733. getDataCallback(data);
  49734. }, null, null, true, onError);
  49735. };
  49736. HDRCubeTexture._facesMapping = [
  49737. "right",
  49738. "up",
  49739. "front",
  49740. "left",
  49741. "down",
  49742. "back"
  49743. ];
  49744. return HDRCubeTexture;
  49745. }(BABYLON.BaseTexture));
  49746. BABYLON.HDRCubeTexture = HDRCubeTexture;
  49747. })(BABYLON || (BABYLON = {}));
  49748. var BABYLON;
  49749. (function (BABYLON) {
  49750. var Debug;
  49751. (function (Debug) {
  49752. /**
  49753. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  49754. */
  49755. var SkeletonViewer = (function () {
  49756. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  49757. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  49758. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  49759. this.skeleton = skeleton;
  49760. this.mesh = mesh;
  49761. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  49762. this.renderingGroupId = renderingGroupId;
  49763. this.color = BABYLON.Color3.White();
  49764. this._debugLines = [];
  49765. this._isEnabled = false;
  49766. this._scene = scene;
  49767. this.update();
  49768. this._renderFunction = this.update.bind(this);
  49769. }
  49770. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  49771. get: function () {
  49772. return this._isEnabled;
  49773. },
  49774. set: function (value) {
  49775. if (this._isEnabled === value) {
  49776. return;
  49777. }
  49778. this._isEnabled = value;
  49779. if (value) {
  49780. this._scene.registerBeforeRender(this._renderFunction);
  49781. }
  49782. else {
  49783. this._scene.unregisterBeforeRender(this._renderFunction);
  49784. }
  49785. },
  49786. enumerable: true,
  49787. configurable: true
  49788. });
  49789. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  49790. if (x === void 0) { x = 0; }
  49791. if (y === void 0) { y = 0; }
  49792. if (z === void 0) { z = 0; }
  49793. var tmat = BABYLON.Tmp.Matrix[0];
  49794. var parentBone = bone.getParent();
  49795. tmat.copyFrom(bone.getLocalMatrix());
  49796. if (x !== 0 || y !== 0 || z !== 0) {
  49797. var tmat2 = BABYLON.Tmp.Matrix[1];
  49798. BABYLON.Matrix.IdentityToRef(tmat2);
  49799. tmat2.m[12] = x;
  49800. tmat2.m[13] = y;
  49801. tmat2.m[14] = z;
  49802. tmat2.multiplyToRef(tmat, tmat);
  49803. }
  49804. if (parentBone) {
  49805. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  49806. }
  49807. tmat.multiplyToRef(meshMat, tmat);
  49808. position.x = tmat.m[12];
  49809. position.y = tmat.m[13];
  49810. position.z = tmat.m[14];
  49811. };
  49812. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  49813. var len = bones.length;
  49814. for (var i = 0; i < len; i++) {
  49815. var bone = bones[i];
  49816. var points = this._debugLines[i];
  49817. if (!points) {
  49818. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  49819. this._debugLines[i] = points;
  49820. }
  49821. this._getBonePosition(points[0], bone, meshMat);
  49822. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  49823. }
  49824. };
  49825. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  49826. var len = bones.length;
  49827. var boneNum = 0;
  49828. for (var i = len - 1; i >= 0; i--) {
  49829. var childBone = bones[i];
  49830. var parentBone = childBone.getParent();
  49831. if (!parentBone) {
  49832. continue;
  49833. }
  49834. var points = this._debugLines[boneNum];
  49835. if (!points) {
  49836. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  49837. this._debugLines[boneNum] = points;
  49838. }
  49839. this._getBonePosition(points[0], childBone, meshMat);
  49840. this._getBonePosition(points[1], parentBone, meshMat);
  49841. boneNum++;
  49842. }
  49843. };
  49844. SkeletonViewer.prototype.update = function () {
  49845. if (this.autoUpdateBonesMatrices) {
  49846. this._updateBoneMatrix(this.skeleton.bones[0]);
  49847. }
  49848. if (this.skeleton.bones[0].length === undefined) {
  49849. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  49850. }
  49851. else {
  49852. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  49853. }
  49854. if (!this._debugMesh) {
  49855. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  49856. this._debugMesh.renderingGroupId = this.renderingGroupId;
  49857. }
  49858. else {
  49859. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  49860. }
  49861. this._debugMesh.color = this.color;
  49862. };
  49863. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  49864. if (bone.getParent()) {
  49865. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  49866. }
  49867. var children = bone.children;
  49868. var len = children.length;
  49869. for (var i = 0; i < len; i++) {
  49870. this._updateBoneMatrix(children[i]);
  49871. }
  49872. };
  49873. SkeletonViewer.prototype.dispose = function () {
  49874. if (this._debugMesh) {
  49875. this.isEnabled = false;
  49876. this._debugMesh.dispose();
  49877. this._debugMesh = null;
  49878. }
  49879. };
  49880. return SkeletonViewer;
  49881. }());
  49882. Debug.SkeletonViewer = SkeletonViewer;
  49883. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  49884. })(BABYLON || (BABYLON = {}));
  49885. var BABYLON;
  49886. (function (BABYLON) {
  49887. /**
  49888. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  49889. * It can help converting any input color in a desired output one. This can then be used to create effects
  49890. * from sepia, black and white to sixties or futuristic rendering...
  49891. *
  49892. * The only supported format is currently 3dl.
  49893. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  49894. */
  49895. var ColorGradingTexture = (function (_super) {
  49896. __extends(ColorGradingTexture, _super);
  49897. /**
  49898. * Instantiates a ColorGradingTexture from the following parameters.
  49899. *
  49900. * @param url The location of the color gradind data (currently only supporting 3dl)
  49901. * @param scene The scene the texture will be used in
  49902. */
  49903. function ColorGradingTexture(url, scene) {
  49904. _super.call(this, scene);
  49905. if (!url) {
  49906. return;
  49907. }
  49908. this._textureMatrix = BABYLON.Matrix.Identity();
  49909. this.name = url;
  49910. this.url = url;
  49911. this.hasAlpha = false;
  49912. this.isCube = false;
  49913. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49914. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49915. this.anisotropicFilteringLevel = 1;
  49916. this._texture = this._getFromCache(url, true);
  49917. if (!this._texture) {
  49918. if (!scene.useDelayedTextureLoading) {
  49919. this.loadTexture();
  49920. }
  49921. else {
  49922. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49923. }
  49924. }
  49925. }
  49926. /**
  49927. * Returns the texture matrix used in most of the material.
  49928. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  49929. */
  49930. ColorGradingTexture.prototype.getTextureMatrix = function () {
  49931. return this._textureMatrix;
  49932. };
  49933. /**
  49934. * Occurs when the file being loaded is a .3dl LUT file.
  49935. */
  49936. ColorGradingTexture.prototype.load3dlTexture = function () {
  49937. var _this = this;
  49938. var mipLevels = 0;
  49939. var floatArrayView = null;
  49940. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49941. this._texture = texture;
  49942. var callback = function (text) {
  49943. var data;
  49944. var tempData;
  49945. var line;
  49946. var lines = text.split('\n');
  49947. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  49948. var maxColor = 0;
  49949. for (var i = 0; i < lines.length; i++) {
  49950. line = lines[i];
  49951. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  49952. continue;
  49953. if (line.indexOf('#') === 0)
  49954. continue;
  49955. var words = line.split(" ");
  49956. if (size === 0) {
  49957. // Number of space + one
  49958. size = words.length;
  49959. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  49960. tempData = new Float32Array(size * size * size * 4);
  49961. continue;
  49962. }
  49963. if (size != 0) {
  49964. var r = Math.max(parseInt(words[0]), 0);
  49965. var g = Math.max(parseInt(words[1]), 0);
  49966. var b = Math.max(parseInt(words[2]), 0);
  49967. maxColor = Math.max(r, maxColor);
  49968. maxColor = Math.max(g, maxColor);
  49969. maxColor = Math.max(b, maxColor);
  49970. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  49971. tempData[pixelStorageIndex + 0] = r;
  49972. tempData[pixelStorageIndex + 1] = g;
  49973. tempData[pixelStorageIndex + 2] = b;
  49974. tempData[pixelStorageIndex + 3] = 0;
  49975. pixelIndexSlice++;
  49976. if (pixelIndexSlice % size == 0) {
  49977. pixelIndexH++;
  49978. pixelIndexSlice = 0;
  49979. if (pixelIndexH % size == 0) {
  49980. pixelIndexW++;
  49981. pixelIndexH = 0;
  49982. }
  49983. }
  49984. }
  49985. }
  49986. for (var i = 0; i < tempData.length; i++) {
  49987. var value = tempData[i];
  49988. data[i] = (value / maxColor * 255);
  49989. }
  49990. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  49991. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  49992. };
  49993. BABYLON.Tools.LoadFile(this.url, callback);
  49994. return this._texture;
  49995. };
  49996. /**
  49997. * Starts the loading process of the texture.
  49998. */
  49999. ColorGradingTexture.prototype.loadTexture = function () {
  50000. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  50001. this.load3dlTexture();
  50002. }
  50003. };
  50004. /**
  50005. * Clones the color gradind texture.
  50006. */
  50007. ColorGradingTexture.prototype.clone = function () {
  50008. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  50009. // Base texture
  50010. newTexture.level = this.level;
  50011. return newTexture;
  50012. };
  50013. /**
  50014. * Called during delayed load for textures.
  50015. */
  50016. ColorGradingTexture.prototype.delayLoad = function () {
  50017. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50018. return;
  50019. }
  50020. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50021. this._texture = this._getFromCache(this.url, true);
  50022. if (!this._texture) {
  50023. this.loadTexture();
  50024. }
  50025. };
  50026. /**
  50027. * Binds the color grading to the shader.
  50028. * @param colorGrading The texture to bind
  50029. * @param effect The effect to bind to
  50030. */
  50031. ColorGradingTexture.Bind = function (colorGrading, effect) {
  50032. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  50033. var x = colorGrading.level; // Texture Level
  50034. var y = colorGrading.getSize().height; // Texture Size example with 8
  50035. var z = y - 1.0; // SizeMinusOne 8 - 1
  50036. var w = 1 / y; // Space of 1 slice 1 / 8
  50037. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  50038. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  50039. 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
  50040. 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
  50041. 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
  50042. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  50043. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  50044. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  50045. };
  50046. /**
  50047. * Prepare the list of uniforms associated with the ColorGrading effects.
  50048. * @param uniformsList The list of uniforms used in the effect
  50049. * @param samplersList The list of samplers used in the effect
  50050. */
  50051. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  50052. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  50053. samplersList.push("cameraColorGrading2DSampler");
  50054. };
  50055. /**
  50056. * Parses a color grading texture serialized by Babylon.
  50057. * @param parsedTexture The texture information being parsedTexture
  50058. * @param scene The scene to load the texture in
  50059. * @param rootUrl The root url of the data assets to load
  50060. * @return A color gradind texture
  50061. */
  50062. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50063. var texture = null;
  50064. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  50065. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  50066. texture.name = parsedTexture.name;
  50067. texture.level = parsedTexture.level;
  50068. }
  50069. return texture;
  50070. };
  50071. /**
  50072. * Serializes the LUT texture to json format.
  50073. */
  50074. ColorGradingTexture.prototype.serialize = function () {
  50075. if (!this.name) {
  50076. return null;
  50077. }
  50078. var serializationObject = {};
  50079. serializationObject.name = this.name;
  50080. serializationObject.level = this.level;
  50081. serializationObject.customType = "BABYLON.ColorGradingTexture";
  50082. return serializationObject;
  50083. };
  50084. /**
  50085. * Empty line regex stored for GC.
  50086. */
  50087. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  50088. return ColorGradingTexture;
  50089. }(BABYLON.BaseTexture));
  50090. BABYLON.ColorGradingTexture = ColorGradingTexture;
  50091. })(BABYLON || (BABYLON = {}));
  50092. var BABYLON;
  50093. (function (BABYLON) {
  50094. /**
  50095. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  50096. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  50097. * 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;
  50098. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  50099. */
  50100. var ColorCurves = (function () {
  50101. function ColorCurves() {
  50102. this._dirty = true;
  50103. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  50104. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  50105. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  50106. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  50107. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  50108. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  50109. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  50110. this._globalHue = 30;
  50111. this._globalDensity = 0;
  50112. this._globalSaturation = 0;
  50113. this._globalExposure = 0;
  50114. this._highlightsHue = 30;
  50115. this._highlightsDensity = 0;
  50116. this._highlightsSaturation = 0;
  50117. this._highlightsExposure = 0;
  50118. this._midtonesHue = 30;
  50119. this._midtonesDensity = 0;
  50120. this._midtonesSaturation = 0;
  50121. this._midtonesExposure = 0;
  50122. this._shadowsHue = 30;
  50123. this._shadowsDensity = 0;
  50124. this._shadowsSaturation = 0;
  50125. this._shadowsExposure = 0;
  50126. }
  50127. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  50128. /**
  50129. * Gets the global Hue value.
  50130. * 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).
  50131. */
  50132. get: function () {
  50133. return this._globalHue;
  50134. },
  50135. /**
  50136. * Sets the global Hue value.
  50137. * 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).
  50138. */
  50139. set: function (value) {
  50140. this._globalHue = value;
  50141. this._dirty = true;
  50142. },
  50143. enumerable: true,
  50144. configurable: true
  50145. });
  50146. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  50147. /**
  50148. * Gets the global Density value.
  50149. * 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.
  50150. * Values less than zero provide a filter of opposite hue.
  50151. */
  50152. get: function () {
  50153. return this._globalDensity;
  50154. },
  50155. /**
  50156. * Sets the global Density value.
  50157. * 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.
  50158. * Values less than zero provide a filter of opposite hue.
  50159. */
  50160. set: function (value) {
  50161. this._globalDensity = value;
  50162. this._dirty = true;
  50163. },
  50164. enumerable: true,
  50165. configurable: true
  50166. });
  50167. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  50168. /**
  50169. * Gets the global Saturation value.
  50170. * 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.
  50171. */
  50172. get: function () {
  50173. return this._globalSaturation;
  50174. },
  50175. /**
  50176. * Sets the global Saturation value.
  50177. * 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.
  50178. */
  50179. set: function (value) {
  50180. this._globalSaturation = value;
  50181. this._dirty = true;
  50182. },
  50183. enumerable: true,
  50184. configurable: true
  50185. });
  50186. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  50187. /**
  50188. * Gets the highlights Hue value.
  50189. * 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).
  50190. */
  50191. get: function () {
  50192. return this._highlightsHue;
  50193. },
  50194. /**
  50195. * Sets the highlights Hue value.
  50196. * 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).
  50197. */
  50198. set: function (value) {
  50199. this._highlightsHue = value;
  50200. this._dirty = true;
  50201. },
  50202. enumerable: true,
  50203. configurable: true
  50204. });
  50205. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  50206. /**
  50207. * Gets the highlights Density value.
  50208. * 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.
  50209. * Values less than zero provide a filter of opposite hue.
  50210. */
  50211. get: function () {
  50212. return this._highlightsDensity;
  50213. },
  50214. /**
  50215. * Sets the highlights Density value.
  50216. * 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.
  50217. * Values less than zero provide a filter of opposite hue.
  50218. */
  50219. set: function (value) {
  50220. this._highlightsDensity = value;
  50221. this._dirty = true;
  50222. },
  50223. enumerable: true,
  50224. configurable: true
  50225. });
  50226. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  50227. /**
  50228. * Gets the highlights Saturation value.
  50229. * 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.
  50230. */
  50231. get: function () {
  50232. return this._highlightsSaturation;
  50233. },
  50234. /**
  50235. * Sets the highlights Saturation value.
  50236. * 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.
  50237. */
  50238. set: function (value) {
  50239. this._highlightsSaturation = value;
  50240. this._dirty = true;
  50241. },
  50242. enumerable: true,
  50243. configurable: true
  50244. });
  50245. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  50246. /**
  50247. * Gets the highlights Exposure value.
  50248. * 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.
  50249. */
  50250. get: function () {
  50251. return this._highlightsExposure;
  50252. },
  50253. /**
  50254. * Sets the highlights Exposure value.
  50255. * 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.
  50256. */
  50257. set: function (value) {
  50258. this._highlightsExposure = value;
  50259. this._dirty = true;
  50260. },
  50261. enumerable: true,
  50262. configurable: true
  50263. });
  50264. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  50265. /**
  50266. * Gets the midtones Hue value.
  50267. * 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).
  50268. */
  50269. get: function () {
  50270. return this._midtonesHue;
  50271. },
  50272. /**
  50273. * Sets the midtones Hue value.
  50274. * 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).
  50275. */
  50276. set: function (value) {
  50277. this._midtonesHue = value;
  50278. this._dirty = true;
  50279. },
  50280. enumerable: true,
  50281. configurable: true
  50282. });
  50283. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  50284. /**
  50285. * Gets the midtones Density value.
  50286. * 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.
  50287. * Values less than zero provide a filter of opposite hue.
  50288. */
  50289. get: function () {
  50290. return this._midtonesDensity;
  50291. },
  50292. /**
  50293. * Sets the midtones Density value.
  50294. * 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.
  50295. * Values less than zero provide a filter of opposite hue.
  50296. */
  50297. set: function (value) {
  50298. this._midtonesDensity = value;
  50299. this._dirty = true;
  50300. },
  50301. enumerable: true,
  50302. configurable: true
  50303. });
  50304. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  50305. /**
  50306. * Gets the midtones Saturation value.
  50307. * 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.
  50308. */
  50309. get: function () {
  50310. return this._midtonesSaturation;
  50311. },
  50312. /**
  50313. * Sets the midtones Saturation value.
  50314. * 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.
  50315. */
  50316. set: function (value) {
  50317. this._midtonesSaturation = value;
  50318. this._dirty = true;
  50319. },
  50320. enumerable: true,
  50321. configurable: true
  50322. });
  50323. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  50324. /**
  50325. * Gets the midtones Exposure value.
  50326. * 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.
  50327. */
  50328. get: function () {
  50329. return this._midtonesExposure;
  50330. },
  50331. /**
  50332. * Sets the midtones Exposure value.
  50333. * 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.
  50334. */
  50335. set: function (value) {
  50336. this._midtonesExposure = value;
  50337. this._dirty = true;
  50338. },
  50339. enumerable: true,
  50340. configurable: true
  50341. });
  50342. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  50343. /**
  50344. * Gets the shadows Hue value.
  50345. * 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).
  50346. */
  50347. get: function () {
  50348. return this._shadowsHue;
  50349. },
  50350. /**
  50351. * Sets the shadows Hue value.
  50352. * 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).
  50353. */
  50354. set: function (value) {
  50355. this._shadowsHue = value;
  50356. this._dirty = true;
  50357. },
  50358. enumerable: true,
  50359. configurable: true
  50360. });
  50361. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  50362. /**
  50363. * Gets the shadows Density value.
  50364. * 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.
  50365. * Values less than zero provide a filter of opposite hue.
  50366. */
  50367. get: function () {
  50368. return this._shadowsDensity;
  50369. },
  50370. /**
  50371. * Sets the shadows Density value.
  50372. * 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.
  50373. * Values less than zero provide a filter of opposite hue.
  50374. */
  50375. set: function (value) {
  50376. this._shadowsDensity = value;
  50377. this._dirty = true;
  50378. },
  50379. enumerable: true,
  50380. configurable: true
  50381. });
  50382. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  50383. /**
  50384. * Gets the shadows Saturation value.
  50385. * 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.
  50386. */
  50387. get: function () {
  50388. return this._shadowsSaturation;
  50389. },
  50390. /**
  50391. * Sets the shadows Saturation value.
  50392. * 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.
  50393. */
  50394. set: function (value) {
  50395. this._shadowsSaturation = value;
  50396. this._dirty = true;
  50397. },
  50398. enumerable: true,
  50399. configurable: true
  50400. });
  50401. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  50402. /**
  50403. * Gets the shadows Exposure value.
  50404. * 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.
  50405. */
  50406. get: function () {
  50407. return this._shadowsExposure;
  50408. },
  50409. /**
  50410. * Sets the shadows Exposure value.
  50411. * 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.
  50412. */
  50413. set: function (value) {
  50414. this._shadowsExposure = value;
  50415. this._dirty = true;
  50416. },
  50417. enumerable: true,
  50418. configurable: true
  50419. });
  50420. /**
  50421. * Binds the color curves to the shader.
  50422. * @param colorCurves The color curve to bind
  50423. * @param effect The effect to bind to
  50424. */
  50425. ColorCurves.Bind = function (colorCurves, effect) {
  50426. if (colorCurves._dirty) {
  50427. colorCurves._dirty = false;
  50428. // Fill in global info.
  50429. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  50430. // Compute highlights info.
  50431. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  50432. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  50433. // Compute midtones info.
  50434. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  50435. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  50436. // Compute shadows info.
  50437. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  50438. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  50439. // Compute deltas (neutral is midtones).
  50440. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  50441. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  50442. }
  50443. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  50444. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  50445. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  50446. };
  50447. /**
  50448. * Prepare the list of uniforms associated with the ColorCurves effects.
  50449. * @param uniformsList The list of uniforms used in the effect
  50450. */
  50451. ColorCurves.PrepareUniforms = function (uniformsList) {
  50452. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  50453. };
  50454. /**
  50455. * Returns color grading data based on a hue, density, saturation and exposure value.
  50456. * @param filterHue The hue of the color filter.
  50457. * @param filterDensity The density of the color filter.
  50458. * @param saturation The saturation.
  50459. * @param exposure The exposure.
  50460. * @param result The result data container.
  50461. */
  50462. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  50463. if (hue == null) {
  50464. return;
  50465. }
  50466. hue = ColorCurves.clamp(hue, 0, 360);
  50467. density = ColorCurves.clamp(density, -100, 100);
  50468. saturation = ColorCurves.clamp(saturation, -100, 100);
  50469. exposure = ColorCurves.clamp(exposure, -100, 100);
  50470. // Remap the slider/config filter density with non-linear mapping and also scale by half
  50471. // so that the maximum filter density is only 50% control. This provides fine control
  50472. // for small values and reasonable range.
  50473. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  50474. density *= 0.5;
  50475. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  50476. if (density < 0) {
  50477. density *= -1;
  50478. hue = (hue + 180) % 360;
  50479. }
  50480. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  50481. result.scaleToRef(2, result);
  50482. result.a = 1 + 0.01 * saturation;
  50483. };
  50484. /**
  50485. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  50486. * @param value The input slider value in range [-100,100].
  50487. * @returns Adjusted value.
  50488. */
  50489. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  50490. value /= 100;
  50491. var x = Math.abs(value);
  50492. x = Math.pow(x, 2);
  50493. if (value < 0) {
  50494. x *= -1;
  50495. }
  50496. x *= 100;
  50497. return x;
  50498. };
  50499. /**
  50500. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  50501. * @param hue The hue (H) input.
  50502. * @param saturation The saturation (S) input.
  50503. * @param brightness The brightness (B) input.
  50504. * @result An RGBA color represented as Vector4.
  50505. */
  50506. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  50507. var h = ColorCurves.clamp(hue, 0, 360);
  50508. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  50509. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  50510. if (s === 0) {
  50511. result.r = v;
  50512. result.g = v;
  50513. result.b = v;
  50514. }
  50515. else {
  50516. // sector 0 to 5
  50517. h /= 60;
  50518. var i = Math.floor(h);
  50519. // fractional part of h
  50520. var f = h - i;
  50521. var p = v * (1 - s);
  50522. var q = v * (1 - s * f);
  50523. var t = v * (1 - s * (1 - f));
  50524. switch (i) {
  50525. case 0:
  50526. result.r = v;
  50527. result.g = t;
  50528. result.b = p;
  50529. break;
  50530. case 1:
  50531. result.r = q;
  50532. result.g = v;
  50533. result.b = p;
  50534. break;
  50535. case 2:
  50536. result.r = p;
  50537. result.g = v;
  50538. result.b = t;
  50539. break;
  50540. case 3:
  50541. result.r = p;
  50542. result.g = q;
  50543. result.b = v;
  50544. break;
  50545. case 4:
  50546. result.r = t;
  50547. result.g = p;
  50548. result.b = v;
  50549. break;
  50550. default:
  50551. result.r = v;
  50552. result.g = p;
  50553. result.b = q;
  50554. break;
  50555. }
  50556. }
  50557. result.a = 1;
  50558. };
  50559. /**
  50560. * Returns a value clamped between min and max
  50561. * @param value The value to clamp
  50562. * @param min The minimum of value
  50563. * @param max The maximum of value
  50564. * @returns The clamped value.
  50565. */
  50566. ColorCurves.clamp = function (value, min, max) {
  50567. return Math.min(Math.max(value, min), max);
  50568. };
  50569. /**
  50570. * Clones the current color curve instance.
  50571. * @return The cloned curves
  50572. */
  50573. ColorCurves.prototype.clone = function () {
  50574. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  50575. };
  50576. /**
  50577. * Serializes the current color curve instance to a json representation.
  50578. * @return a JSON representation
  50579. */
  50580. ColorCurves.prototype.serialize = function () {
  50581. return BABYLON.SerializationHelper.Serialize(this);
  50582. };
  50583. /**
  50584. * Parses the color curve from a json representation.
  50585. * @param source the JSON source to parse
  50586. * @return The parsed curves
  50587. */
  50588. ColorCurves.Parse = function (source) {
  50589. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  50590. };
  50591. __decorate([
  50592. BABYLON.serialize()
  50593. ], ColorCurves.prototype, "_globalHue", void 0);
  50594. __decorate([
  50595. BABYLON.serialize()
  50596. ], ColorCurves.prototype, "_globalDensity", void 0);
  50597. __decorate([
  50598. BABYLON.serialize()
  50599. ], ColorCurves.prototype, "_globalSaturation", void 0);
  50600. __decorate([
  50601. BABYLON.serialize()
  50602. ], ColorCurves.prototype, "_globalExposure", void 0);
  50603. __decorate([
  50604. BABYLON.serialize()
  50605. ], ColorCurves.prototype, "_highlightsHue", void 0);
  50606. __decorate([
  50607. BABYLON.serialize()
  50608. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  50609. __decorate([
  50610. BABYLON.serialize()
  50611. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  50612. __decorate([
  50613. BABYLON.serialize()
  50614. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  50615. __decorate([
  50616. BABYLON.serialize()
  50617. ], ColorCurves.prototype, "_midtonesHue", void 0);
  50618. __decorate([
  50619. BABYLON.serialize()
  50620. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  50621. __decorate([
  50622. BABYLON.serialize()
  50623. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  50624. __decorate([
  50625. BABYLON.serialize()
  50626. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  50627. return ColorCurves;
  50628. }());
  50629. BABYLON.ColorCurves = ColorCurves;
  50630. })(BABYLON || (BABYLON = {}));
  50631. var BABYLON;
  50632. (function (BABYLON) {
  50633. var PBRMaterialDefines = (function (_super) {
  50634. __extends(PBRMaterialDefines, _super);
  50635. function PBRMaterialDefines() {
  50636. _super.call(this);
  50637. this.ALBEDO = false;
  50638. this.AMBIENT = false;
  50639. this.OPACITY = false;
  50640. this.OPACITYRGB = false;
  50641. this.REFLECTION = false;
  50642. this.EMISSIVE = false;
  50643. this.REFLECTIVITY = false;
  50644. this.BUMP = false;
  50645. this.PARALLAX = false;
  50646. this.PARALLAXOCCLUSION = false;
  50647. this.SPECULAROVERALPHA = false;
  50648. this.CLIPPLANE = false;
  50649. this.ALPHATEST = false;
  50650. this.ALPHAFROMALBEDO = false;
  50651. this.POINTSIZE = false;
  50652. this.FOG = false;
  50653. this.SPECULARTERM = false;
  50654. this.OPACITYFRESNEL = false;
  50655. this.EMISSIVEFRESNEL = false;
  50656. this.FRESNEL = false;
  50657. this.NORMAL = false;
  50658. this.UV1 = false;
  50659. this.UV2 = false;
  50660. this.VERTEXCOLOR = false;
  50661. this.VERTEXALPHA = false;
  50662. this.NUM_BONE_INFLUENCERS = 0;
  50663. this.BonesPerMesh = 0;
  50664. this.INSTANCES = false;
  50665. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  50666. this.MICROSURFACEAUTOMATIC = false;
  50667. this.EMISSIVEASILLUMINATION = false;
  50668. this.LINKEMISSIVEWITHALBEDO = false;
  50669. this.LIGHTMAP = false;
  50670. this.USELIGHTMAPASSHADOWMAP = false;
  50671. this.REFLECTIONMAP_3D = false;
  50672. this.REFLECTIONMAP_SPHERICAL = false;
  50673. this.REFLECTIONMAP_PLANAR = false;
  50674. this.REFLECTIONMAP_CUBIC = false;
  50675. this.REFLECTIONMAP_PROJECTION = false;
  50676. this.REFLECTIONMAP_SKYBOX = false;
  50677. this.REFLECTIONMAP_EXPLICIT = false;
  50678. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  50679. this.INVERTCUBICMAP = false;
  50680. this.LOGARITHMICDEPTH = false;
  50681. this.CAMERATONEMAP = false;
  50682. this.CAMERACONTRAST = false;
  50683. this.CAMERACOLORGRADING = false;
  50684. this.CAMERACOLORCURVES = false;
  50685. this.OVERLOADEDVALUES = false;
  50686. this.OVERLOADEDSHADOWVALUES = false;
  50687. this.USESPHERICALFROMREFLECTIONMAP = false;
  50688. this.REFRACTION = false;
  50689. this.REFRACTIONMAP_3D = false;
  50690. this.LINKREFRACTIONTOTRANSPARENCY = false;
  50691. this.REFRACTIONMAPINLINEARSPACE = false;
  50692. this.LODBASEDMICROSFURACE = false;
  50693. this.USEPHYSICALLIGHTFALLOFF = false;
  50694. this.RADIANCEOVERALPHA = false;
  50695. this.USEPMREMREFLECTION = false;
  50696. this.USEPMREMREFRACTION = false;
  50697. this.OPENGLNORMALMAP = false;
  50698. this.INVERTNORMALMAPX = false;
  50699. this.INVERTNORMALMAPY = false;
  50700. this.SHADOWFULLFLOAT = false;
  50701. this.rebuild();
  50702. }
  50703. return PBRMaterialDefines;
  50704. }(BABYLON.MaterialDefines));
  50705. /**
  50706. * The Physically based material of BJS.
  50707. *
  50708. * This offers the main features of a standard PBR material.
  50709. * For more information, please refer to the documentation :
  50710. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  50711. */
  50712. var PBRMaterial = (function (_super) {
  50713. __extends(PBRMaterial, _super);
  50714. /**
  50715. * Instantiates a new PBRMaterial instance.
  50716. *
  50717. * @param name The material name
  50718. * @param scene The scene the material will be use in.
  50719. */
  50720. function PBRMaterial(name, scene) {
  50721. var _this = this;
  50722. _super.call(this, name, scene);
  50723. /**
  50724. * Intensity of the direct lights e.g. the four lights available in your scene.
  50725. * This impacts both the direct diffuse and specular highlights.
  50726. */
  50727. this.directIntensity = 1.0;
  50728. /**
  50729. * Intensity of the emissive part of the material.
  50730. * This helps controlling the emissive effect without modifying the emissive color.
  50731. */
  50732. this.emissiveIntensity = 1.0;
  50733. /**
  50734. * Intensity of the environment e.g. how much the environment will light the object
  50735. * either through harmonics for rough material or through the refelction for shiny ones.
  50736. */
  50737. this.environmentIntensity = 1.0;
  50738. /**
  50739. * This is a special control allowing the reduction of the specular highlights coming from the
  50740. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  50741. */
  50742. this.specularIntensity = 1.0;
  50743. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  50744. /**
  50745. * Debug Control allowing disabling the bump map on this material.
  50746. */
  50747. this.disableBumpMap = false;
  50748. /**
  50749. * Debug Control helping enforcing or dropping the darkness of shadows.
  50750. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  50751. */
  50752. this.overloadedShadowIntensity = 1.0;
  50753. /**
  50754. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  50755. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  50756. */
  50757. this.overloadedShadeIntensity = 1.0;
  50758. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  50759. /**
  50760. * The camera exposure used on this material.
  50761. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  50762. * This corresponds to a photographic exposure.
  50763. */
  50764. this.cameraExposure = 1.0;
  50765. /**
  50766. * The camera contrast used on this material.
  50767. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  50768. */
  50769. this.cameraContrast = 1.0;
  50770. /**
  50771. * Color Grading 2D Lookup Texture.
  50772. * This allows special effects like sepia, black and white to sixties rendering style.
  50773. */
  50774. this.cameraColorGradingTexture = null;
  50775. /**
  50776. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  50777. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  50778. * 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;
  50779. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  50780. */
  50781. this.cameraColorCurves = null;
  50782. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  50783. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  50784. /**
  50785. * Debug Control allowing to overload the ambient color.
  50786. * This as to be use with the overloadedAmbientIntensity parameter.
  50787. */
  50788. this.overloadedAmbient = BABYLON.Color3.White();
  50789. /**
  50790. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  50791. */
  50792. this.overloadedAmbientIntensity = 0.0;
  50793. /**
  50794. * Debug Control allowing to overload the albedo color.
  50795. * This as to be use with the overloadedAlbedoIntensity parameter.
  50796. */
  50797. this.overloadedAlbedo = BABYLON.Color3.White();
  50798. /**
  50799. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  50800. */
  50801. this.overloadedAlbedoIntensity = 0.0;
  50802. /**
  50803. * Debug Control allowing to overload the reflectivity color.
  50804. * This as to be use with the overloadedReflectivityIntensity parameter.
  50805. */
  50806. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  50807. /**
  50808. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  50809. */
  50810. this.overloadedReflectivityIntensity = 0.0;
  50811. /**
  50812. * Debug Control allowing to overload the emissive color.
  50813. * This as to be use with the overloadedEmissiveIntensity parameter.
  50814. */
  50815. this.overloadedEmissive = BABYLON.Color3.White();
  50816. /**
  50817. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  50818. */
  50819. this.overloadedEmissiveIntensity = 0.0;
  50820. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  50821. /**
  50822. * Debug Control allowing to overload the reflection color.
  50823. * This as to be use with the overloadedReflectionIntensity parameter.
  50824. */
  50825. this.overloadedReflection = BABYLON.Color3.White();
  50826. /**
  50827. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  50828. */
  50829. this.overloadedReflectionIntensity = 0.0;
  50830. /**
  50831. * Debug Control allowing to overload the microsurface.
  50832. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  50833. */
  50834. this.overloadedMicroSurface = 0.0;
  50835. /**
  50836. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  50837. */
  50838. this.overloadedMicroSurfaceIntensity = 0.0;
  50839. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  50840. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  50841. /**
  50842. * AKA Diffuse Color in other nomenclature.
  50843. */
  50844. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  50845. /**
  50846. * AKA Specular Color in other nomenclature.
  50847. */
  50848. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  50849. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  50850. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  50851. /**
  50852. * AKA Glossiness in other nomenclature.
  50853. */
  50854. this.microSurface = 0.9;
  50855. /**
  50856. * source material index of refraction (IOR)' / 'destination material IOR.
  50857. */
  50858. this.indexOfRefraction = 0.66;
  50859. /**
  50860. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  50861. */
  50862. this.invertRefractionY = false;
  50863. /**
  50864. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  50865. * Materials half opaque for instance using refraction could benefit from this control.
  50866. */
  50867. this.linkRefractionWithTransparency = false;
  50868. /**
  50869. * The emissive and albedo are linked to never be more than one (Energy conservation).
  50870. */
  50871. this.linkEmissiveWithAlbedo = false;
  50872. this.useLightmapAsShadowmap = false;
  50873. /**
  50874. * In this mode, the emissive informtaion will always be added to the lighting once.
  50875. * A light for instance can be thought as emissive.
  50876. */
  50877. this.useEmissiveAsIllumination = false;
  50878. /**
  50879. * Secifies that the alpha is coming form the albedo channel alpha channel.
  50880. */
  50881. this.useAlphaFromAlbedoTexture = false;
  50882. /**
  50883. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  50884. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  50885. */
  50886. this.useSpecularOverAlpha = true;
  50887. /**
  50888. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  50889. */
  50890. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  50891. /**
  50892. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  50893. * The material will try to infer what glossiness each pixel should be.
  50894. */
  50895. this.useAutoMicroSurfaceFromReflectivityMap = false;
  50896. /**
  50897. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  50898. * the creation of the material.
  50899. */
  50900. this.useScalarInLinearSpace = false;
  50901. /**
  50902. * BJS is using an harcoded light falloff based on a manually sets up range.
  50903. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  50904. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  50905. */
  50906. this.usePhysicalLightFalloff = true;
  50907. /**
  50908. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  50909. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  50910. */
  50911. this.useRadianceOverAlpha = true;
  50912. /**
  50913. * Allows using the bump map in parallax mode.
  50914. */
  50915. this.useParallax = false;
  50916. /**
  50917. * Allows using the bump map in parallax occlusion mode.
  50918. */
  50919. this.useParallaxOcclusion = false;
  50920. /**
  50921. * Controls the scale bias of the parallax mode.
  50922. */
  50923. this.parallaxScaleBias = 0.05;
  50924. /**
  50925. * If sets to true, disables all the lights affecting the material.
  50926. */
  50927. this.disableLighting = false;
  50928. /**
  50929. * Number of Simultaneous lights allowed on the material.
  50930. */
  50931. this.maxSimultaneousLights = 4;
  50932. /**
  50933. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  50934. */
  50935. this.invertNormalMapX = false;
  50936. /**
  50937. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  50938. */
  50939. this.invertNormalMapY = false;
  50940. this._renderTargets = new BABYLON.SmartArray(16);
  50941. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  50942. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  50943. this._tempColor = new BABYLON.Color3();
  50944. this._defines = new PBRMaterialDefines();
  50945. this._cachedDefines = new PBRMaterialDefines();
  50946. this._myScene = null;
  50947. this._myShadowGenerator = null;
  50948. this._cachedDefines.BonesPerMesh = -1;
  50949. this.getRenderTargetTextures = function () {
  50950. _this._renderTargets.reset();
  50951. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  50952. _this._renderTargets.push(_this.reflectionTexture);
  50953. }
  50954. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  50955. _this._renderTargets.push(_this.refractionTexture);
  50956. }
  50957. return _this._renderTargets;
  50958. };
  50959. }
  50960. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  50961. get: function () {
  50962. return this._useLogarithmicDepth;
  50963. },
  50964. set: function (value) {
  50965. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  50966. },
  50967. enumerable: true,
  50968. configurable: true
  50969. });
  50970. PBRMaterial.prototype.needAlphaBlending = function () {
  50971. if (this.linkRefractionWithTransparency) {
  50972. return false;
  50973. }
  50974. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  50975. };
  50976. PBRMaterial.prototype.needAlphaTesting = function () {
  50977. if (this.linkRefractionWithTransparency) {
  50978. return false;
  50979. }
  50980. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  50981. };
  50982. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  50983. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  50984. };
  50985. PBRMaterial.prototype.getAlphaTestTexture = function () {
  50986. return this.albedoTexture;
  50987. };
  50988. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  50989. if (!mesh) {
  50990. return true;
  50991. }
  50992. if (this._defines.INSTANCES !== useInstances) {
  50993. return false;
  50994. }
  50995. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  50996. return true;
  50997. }
  50998. return false;
  50999. };
  51000. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  51001. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  51002. };
  51003. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  51004. if (!useScalarInLinear) {
  51005. color.toLinearSpaceToRef(ref);
  51006. }
  51007. else {
  51008. ref.r = color.r;
  51009. ref.g = color.g;
  51010. ref.b = color.b;
  51011. }
  51012. };
  51013. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  51014. var lightIndex = 0;
  51015. var depthValuesAlreadySet = false;
  51016. for (var index = 0; index < scene.lights.length; index++) {
  51017. var light = scene.lights[index];
  51018. if (!light.isEnabled()) {
  51019. continue;
  51020. }
  51021. if (!light.canAffectMesh(mesh)) {
  51022. continue;
  51023. }
  51024. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  51025. // GAMMA CORRECTION.
  51026. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  51027. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  51028. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  51029. if (defines["SPECULARTERM"]) {
  51030. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  51031. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  51032. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  51033. }
  51034. // Shadows
  51035. if (scene.shadowsEnabled) {
  51036. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  51037. }
  51038. lightIndex++;
  51039. if (lightIndex === maxSimultaneousLights)
  51040. break;
  51041. }
  51042. };
  51043. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  51044. if (this.checkReadyOnlyOnce) {
  51045. if (this._wasPreviouslyReady) {
  51046. return true;
  51047. }
  51048. }
  51049. var scene = this.getScene();
  51050. if (!this.checkReadyOnEveryCall) {
  51051. if (this._renderId === scene.getRenderId()) {
  51052. if (this._checkCache(scene, mesh, useInstances)) {
  51053. return true;
  51054. }
  51055. }
  51056. }
  51057. var engine = scene.getEngine();
  51058. var needNormals = false;
  51059. var needUVs = false;
  51060. this._defines.reset();
  51061. if (scene.texturesEnabled) {
  51062. // Textures
  51063. if (scene.texturesEnabled) {
  51064. if (scene.getEngine().getCaps().textureLOD) {
  51065. this._defines.LODBASEDMICROSFURACE = true;
  51066. }
  51067. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  51068. if (!this.albedoTexture.isReady()) {
  51069. return false;
  51070. }
  51071. else {
  51072. needUVs = true;
  51073. this._defines.ALBEDO = true;
  51074. }
  51075. }
  51076. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  51077. if (!this.ambientTexture.isReady()) {
  51078. return false;
  51079. }
  51080. else {
  51081. needUVs = true;
  51082. this._defines.AMBIENT = true;
  51083. }
  51084. }
  51085. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  51086. if (!this.opacityTexture.isReady()) {
  51087. return false;
  51088. }
  51089. else {
  51090. needUVs = true;
  51091. this._defines.OPACITY = true;
  51092. if (this.opacityTexture.getAlphaFromRGB) {
  51093. this._defines.OPACITYRGB = true;
  51094. }
  51095. }
  51096. }
  51097. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  51098. if (!this.reflectionTexture.isReady()) {
  51099. return false;
  51100. }
  51101. else {
  51102. needNormals = true;
  51103. this._defines.REFLECTION = true;
  51104. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  51105. this._defines.INVERTCUBICMAP = true;
  51106. }
  51107. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  51108. switch (this.reflectionTexture.coordinatesMode) {
  51109. case BABYLON.Texture.CUBIC_MODE:
  51110. case BABYLON.Texture.INVCUBIC_MODE:
  51111. this._defines.REFLECTIONMAP_CUBIC = true;
  51112. break;
  51113. case BABYLON.Texture.EXPLICIT_MODE:
  51114. this._defines.REFLECTIONMAP_EXPLICIT = true;
  51115. break;
  51116. case BABYLON.Texture.PLANAR_MODE:
  51117. this._defines.REFLECTIONMAP_PLANAR = true;
  51118. break;
  51119. case BABYLON.Texture.PROJECTION_MODE:
  51120. this._defines.REFLECTIONMAP_PROJECTION = true;
  51121. break;
  51122. case BABYLON.Texture.SKYBOX_MODE:
  51123. this._defines.REFLECTIONMAP_SKYBOX = true;
  51124. break;
  51125. case BABYLON.Texture.SPHERICAL_MODE:
  51126. this._defines.REFLECTIONMAP_SPHERICAL = true;
  51127. break;
  51128. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  51129. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  51130. break;
  51131. }
  51132. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  51133. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  51134. needNormals = true;
  51135. if (this.reflectionTexture.isPMREM) {
  51136. this._defines.USEPMREMREFLECTION = true;
  51137. }
  51138. }
  51139. }
  51140. }
  51141. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  51142. if (!this.lightmapTexture.isReady()) {
  51143. return false;
  51144. }
  51145. else {
  51146. needUVs = true;
  51147. this._defines.LIGHTMAP = true;
  51148. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  51149. }
  51150. }
  51151. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  51152. if (!this.emissiveTexture.isReady()) {
  51153. return false;
  51154. }
  51155. else {
  51156. needUVs = true;
  51157. this._defines.EMISSIVE = true;
  51158. }
  51159. }
  51160. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  51161. if (!this.reflectivityTexture.isReady()) {
  51162. return false;
  51163. }
  51164. else {
  51165. needUVs = true;
  51166. this._defines.REFLECTIVITY = true;
  51167. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  51168. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  51169. }
  51170. }
  51171. }
  51172. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  51173. if (!this.bumpTexture.isReady()) {
  51174. return false;
  51175. }
  51176. else {
  51177. needUVs = true;
  51178. this._defines.BUMP = true;
  51179. if (this.useParallax) {
  51180. this._defines.PARALLAX = true;
  51181. if (this.useParallaxOcclusion) {
  51182. this._defines.PARALLAXOCCLUSION = true;
  51183. }
  51184. }
  51185. if (this.invertNormalMapX) {
  51186. this._defines.INVERTNORMALMAPX = true;
  51187. }
  51188. if (this.invertNormalMapY) {
  51189. this._defines.INVERTNORMALMAPY = true;
  51190. }
  51191. }
  51192. }
  51193. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  51194. if (!this.refractionTexture.isReady()) {
  51195. return false;
  51196. }
  51197. else {
  51198. needUVs = true;
  51199. this._defines.REFRACTION = true;
  51200. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  51201. if (this.linkRefractionWithTransparency) {
  51202. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  51203. }
  51204. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  51205. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  51206. if (this.refractionTexture.isPMREM) {
  51207. this._defines.USEPMREMREFRACTION = true;
  51208. }
  51209. }
  51210. }
  51211. }
  51212. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  51213. if (!this.cameraColorGradingTexture.isReady()) {
  51214. return false;
  51215. }
  51216. else {
  51217. this._defines.CAMERACOLORGRADING = true;
  51218. }
  51219. }
  51220. }
  51221. // Effect
  51222. if (scene.clipPlane) {
  51223. this._defines.CLIPPLANE = true;
  51224. }
  51225. if (engine.getAlphaTesting()) {
  51226. this._defines.ALPHATEST = true;
  51227. }
  51228. if (this._shouldUseAlphaFromAlbedoTexture()) {
  51229. this._defines.ALPHAFROMALBEDO = true;
  51230. }
  51231. if (this.useEmissiveAsIllumination) {
  51232. this._defines.EMISSIVEASILLUMINATION = true;
  51233. }
  51234. if (this.linkEmissiveWithAlbedo) {
  51235. this._defines.LINKEMISSIVEWITHALBEDO = true;
  51236. }
  51237. if (this.useLogarithmicDepth) {
  51238. this._defines.LOGARITHMICDEPTH = true;
  51239. }
  51240. if (this.cameraContrast != 1) {
  51241. this._defines.CAMERACONTRAST = true;
  51242. }
  51243. if (this.cameraExposure != 1) {
  51244. this._defines.CAMERATONEMAP = true;
  51245. }
  51246. if (this.cameraColorCurves) {
  51247. this._defines.CAMERACOLORCURVES = true;
  51248. }
  51249. if (this.overloadedShadeIntensity != 1 ||
  51250. this.overloadedShadowIntensity != 1) {
  51251. this._defines.OVERLOADEDSHADOWVALUES = true;
  51252. }
  51253. if (this.overloadedMicroSurfaceIntensity > 0 ||
  51254. this.overloadedEmissiveIntensity > 0 ||
  51255. this.overloadedReflectivityIntensity > 0 ||
  51256. this.overloadedAlbedoIntensity > 0 ||
  51257. this.overloadedAmbientIntensity > 0 ||
  51258. this.overloadedReflectionIntensity > 0) {
  51259. this._defines.OVERLOADEDVALUES = true;
  51260. }
  51261. // Point size
  51262. if (this.pointsCloud || scene.forcePointsCloud) {
  51263. this._defines.POINTSIZE = true;
  51264. }
  51265. // Fog
  51266. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  51267. this._defines.FOG = true;
  51268. }
  51269. if (scene.lightsEnabled && !this.disableLighting) {
  51270. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  51271. }
  51272. if (BABYLON.StandardMaterial.FresnelEnabled) {
  51273. // Fresnel
  51274. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  51275. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  51276. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  51277. this._defines.OPACITYFRESNEL = true;
  51278. }
  51279. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  51280. this._defines.EMISSIVEFRESNEL = true;
  51281. }
  51282. needNormals = true;
  51283. this._defines.FRESNEL = true;
  51284. }
  51285. }
  51286. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  51287. this._defines.SPECULAROVERALPHA = true;
  51288. }
  51289. if (this.usePhysicalLightFalloff) {
  51290. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  51291. }
  51292. if (this.useRadianceOverAlpha) {
  51293. this._defines.RADIANCEOVERALPHA = true;
  51294. }
  51295. // Attribs
  51296. if (mesh) {
  51297. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  51298. this._defines.NORMAL = true;
  51299. }
  51300. if (needUVs) {
  51301. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51302. this._defines.UV1 = true;
  51303. }
  51304. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51305. this._defines.UV2 = true;
  51306. }
  51307. }
  51308. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  51309. this._defines.VERTEXCOLOR = true;
  51310. if (mesh.hasVertexAlpha) {
  51311. this._defines.VERTEXALPHA = true;
  51312. }
  51313. }
  51314. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51315. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  51316. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  51317. }
  51318. // Instances
  51319. if (useInstances) {
  51320. this._defines.INSTANCES = true;
  51321. }
  51322. }
  51323. // Get correct effect
  51324. if (!this._defines.isEqual(this._cachedDefines)) {
  51325. this._defines.cloneTo(this._cachedDefines);
  51326. scene.resetCachedMaterial();
  51327. // Fallbacks
  51328. var fallbacks = new BABYLON.EffectFallbacks();
  51329. if (this._defines.REFLECTION) {
  51330. fallbacks.addFallback(0, "REFLECTION");
  51331. }
  51332. if (this._defines.REFRACTION) {
  51333. fallbacks.addFallback(0, "REFRACTION");
  51334. }
  51335. if (this._defines.REFLECTIVITY) {
  51336. fallbacks.addFallback(0, "REFLECTIVITY");
  51337. }
  51338. if (this._defines.BUMP) {
  51339. fallbacks.addFallback(0, "BUMP");
  51340. }
  51341. if (this._defines.PARALLAX) {
  51342. fallbacks.addFallback(1, "PARALLAX");
  51343. }
  51344. if (this._defines.PARALLAXOCCLUSION) {
  51345. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  51346. }
  51347. if (this._defines.SPECULAROVERALPHA) {
  51348. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  51349. }
  51350. if (this._defines.FOG) {
  51351. fallbacks.addFallback(1, "FOG");
  51352. }
  51353. if (this._defines.POINTSIZE) {
  51354. fallbacks.addFallback(0, "POINTSIZE");
  51355. }
  51356. if (this._defines.LOGARITHMICDEPTH) {
  51357. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  51358. }
  51359. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  51360. if (this._defines.SPECULARTERM) {
  51361. fallbacks.addFallback(0, "SPECULARTERM");
  51362. }
  51363. if (this._defines.OPACITYFRESNEL) {
  51364. fallbacks.addFallback(1, "OPACITYFRESNEL");
  51365. }
  51366. if (this._defines.EMISSIVEFRESNEL) {
  51367. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  51368. }
  51369. if (this._defines.FRESNEL) {
  51370. fallbacks.addFallback(3, "FRESNEL");
  51371. }
  51372. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  51373. fallbacks.addCPUSkinningFallback(0, mesh);
  51374. }
  51375. //Attributes
  51376. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51377. if (this._defines.NORMAL) {
  51378. attribs.push(BABYLON.VertexBuffer.NormalKind);
  51379. }
  51380. if (this._defines.UV1) {
  51381. attribs.push(BABYLON.VertexBuffer.UVKind);
  51382. }
  51383. if (this._defines.UV2) {
  51384. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51385. }
  51386. if (this._defines.VERTEXCOLOR) {
  51387. attribs.push(BABYLON.VertexBuffer.ColorKind);
  51388. }
  51389. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  51390. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  51391. // Legacy browser patch
  51392. var shaderName = "pbr";
  51393. if (!scene.getEngine().getCaps().standardDerivatives) {
  51394. shaderName = "legacypbr";
  51395. }
  51396. var join = this._defines.toString();
  51397. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  51398. "vFogInfos", "vFogColor", "pointSize",
  51399. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  51400. "mBones",
  51401. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  51402. "depthValues",
  51403. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  51404. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  51405. "logarithmicDepthConstant",
  51406. "vSphericalX", "vSphericalY", "vSphericalZ",
  51407. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  51408. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  51409. "vMicrosurfaceTextureLods",
  51410. "vCameraInfos"
  51411. ];
  51412. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  51413. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  51414. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  51415. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  51416. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  51417. }
  51418. if (!this._effect.isReady()) {
  51419. return false;
  51420. }
  51421. this._renderId = scene.getRenderId();
  51422. this._wasPreviouslyReady = true;
  51423. if (mesh) {
  51424. if (!mesh._materialDefines) {
  51425. mesh._materialDefines = new PBRMaterialDefines();
  51426. }
  51427. this._defines.cloneTo(mesh._materialDefines);
  51428. }
  51429. return true;
  51430. };
  51431. PBRMaterial.prototype.unbind = function () {
  51432. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  51433. this._effect.setTexture("reflection2DSampler", null);
  51434. }
  51435. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  51436. this._effect.setTexture("refraction2DSampler", null);
  51437. }
  51438. _super.prototype.unbind.call(this);
  51439. };
  51440. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  51441. this._effect.setMatrix("world", world);
  51442. };
  51443. PBRMaterial.prototype.bind = function (world, mesh) {
  51444. this._myScene = this.getScene();
  51445. // Matrices
  51446. this.bindOnlyWorldMatrix(world);
  51447. // Bones
  51448. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  51449. if (this._myScene.getCachedMaterial() !== this) {
  51450. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  51451. if (BABYLON.StandardMaterial.FresnelEnabled) {
  51452. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  51453. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  51454. }
  51455. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  51456. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  51457. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  51458. }
  51459. }
  51460. // Textures
  51461. if (this._myScene.texturesEnabled) {
  51462. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  51463. this._effect.setTexture("albedoSampler", this.albedoTexture);
  51464. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  51465. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  51466. }
  51467. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  51468. this._effect.setTexture("ambientSampler", this.ambientTexture);
  51469. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  51470. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  51471. }
  51472. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  51473. this._effect.setTexture("opacitySampler", this.opacityTexture);
  51474. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  51475. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  51476. }
  51477. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  51478. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  51479. if (this.reflectionTexture.isCube) {
  51480. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  51481. }
  51482. else {
  51483. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  51484. }
  51485. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  51486. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  51487. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  51488. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  51489. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  51490. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  51491. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  51492. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  51493. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  51494. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  51495. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  51496. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  51497. }
  51498. }
  51499. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  51500. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  51501. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  51502. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  51503. }
  51504. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  51505. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  51506. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  51507. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  51508. }
  51509. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  51510. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  51511. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  51512. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  51513. }
  51514. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  51515. this._effect.setTexture("bumpSampler", this.bumpTexture);
  51516. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  51517. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  51518. }
  51519. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  51520. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  51521. var depth = 1.0;
  51522. if (this.refractionTexture.isCube) {
  51523. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  51524. }
  51525. else {
  51526. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  51527. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  51528. if (this.refractionTexture.depth) {
  51529. depth = this.refractionTexture.depth;
  51530. }
  51531. }
  51532. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  51533. }
  51534. if ((this.reflectionTexture || this.refractionTexture)) {
  51535. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  51536. }
  51537. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  51538. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  51539. }
  51540. }
  51541. // Clip plane
  51542. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  51543. // Point size
  51544. if (this.pointsCloud) {
  51545. this._effect.setFloat("pointSize", this.pointSize);
  51546. }
  51547. // Colors
  51548. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  51549. // GAMMA CORRECTION.
  51550. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  51551. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  51552. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  51553. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  51554. // GAMMA CORRECTION.
  51555. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  51556. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  51557. // GAMMA CORRECTION.
  51558. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  51559. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  51560. }
  51561. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  51562. // GAMMA CORRECTION.
  51563. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  51564. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  51565. // Lights
  51566. if (this._myScene.lightsEnabled && !this.disableLighting) {
  51567. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  51568. }
  51569. // View
  51570. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  51571. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  51572. }
  51573. // Fog
  51574. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  51575. this._lightingInfos.x = this.directIntensity;
  51576. this._lightingInfos.y = this.emissiveIntensity;
  51577. this._lightingInfos.z = this.environmentIntensity;
  51578. this._lightingInfos.w = this.specularIntensity;
  51579. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  51580. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  51581. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  51582. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  51583. this._cameraInfos.x = this.cameraExposure;
  51584. this._cameraInfos.y = this.cameraContrast;
  51585. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  51586. if (this.cameraColorCurves) {
  51587. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  51588. }
  51589. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  51590. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  51591. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  51592. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  51593. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  51594. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  51595. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  51596. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  51597. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  51598. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  51599. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  51600. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  51601. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  51602. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  51603. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  51604. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  51605. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  51606. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  51607. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  51608. // Log. depth
  51609. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  51610. }
  51611. _super.prototype.bind.call(this, world, mesh);
  51612. this._myScene = null;
  51613. };
  51614. PBRMaterial.prototype.getAnimatables = function () {
  51615. var results = [];
  51616. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  51617. results.push(this.albedoTexture);
  51618. }
  51619. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  51620. results.push(this.ambientTexture);
  51621. }
  51622. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  51623. results.push(this.opacityTexture);
  51624. }
  51625. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  51626. results.push(this.reflectionTexture);
  51627. }
  51628. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  51629. results.push(this.emissiveTexture);
  51630. }
  51631. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  51632. results.push(this.reflectivityTexture);
  51633. }
  51634. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  51635. results.push(this.bumpTexture);
  51636. }
  51637. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  51638. results.push(this.lightmapTexture);
  51639. }
  51640. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  51641. results.push(this.refractionTexture);
  51642. }
  51643. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  51644. results.push(this.cameraColorGradingTexture);
  51645. }
  51646. return results;
  51647. };
  51648. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  51649. if (forceDisposeTextures) {
  51650. if (this.albedoTexture) {
  51651. this.albedoTexture.dispose();
  51652. }
  51653. if (this.ambientTexture) {
  51654. this.ambientTexture.dispose();
  51655. }
  51656. if (this.opacityTexture) {
  51657. this.opacityTexture.dispose();
  51658. }
  51659. if (this.reflectionTexture) {
  51660. this.reflectionTexture.dispose();
  51661. }
  51662. if (this.emissiveTexture) {
  51663. this.emissiveTexture.dispose();
  51664. }
  51665. if (this.reflectivityTexture) {
  51666. this.reflectivityTexture.dispose();
  51667. }
  51668. if (this.bumpTexture) {
  51669. this.bumpTexture.dispose();
  51670. }
  51671. if (this.lightmapTexture) {
  51672. this.lightmapTexture.dispose();
  51673. }
  51674. if (this.refractionTexture) {
  51675. this.refractionTexture.dispose();
  51676. }
  51677. if (this.cameraColorGradingTexture) {
  51678. this.cameraColorGradingTexture.dispose();
  51679. }
  51680. }
  51681. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  51682. };
  51683. PBRMaterial.prototype.clone = function (name) {
  51684. var _this = this;
  51685. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  51686. };
  51687. PBRMaterial.prototype.serialize = function () {
  51688. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51689. serializationObject.customType = "BABYLON.PBRMaterial";
  51690. return serializationObject;
  51691. };
  51692. // Statics
  51693. PBRMaterial.Parse = function (source, scene, rootUrl) {
  51694. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  51695. };
  51696. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  51697. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  51698. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  51699. PBRMaterial._scaledReflection = new BABYLON.Color3();
  51700. __decorate([
  51701. BABYLON.serialize()
  51702. ], PBRMaterial.prototype, "directIntensity", void 0);
  51703. __decorate([
  51704. BABYLON.serialize()
  51705. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  51706. __decorate([
  51707. BABYLON.serialize()
  51708. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  51709. __decorate([
  51710. BABYLON.serialize()
  51711. ], PBRMaterial.prototype, "specularIntensity", void 0);
  51712. __decorate([
  51713. BABYLON.serialize()
  51714. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  51715. __decorate([
  51716. BABYLON.serialize()
  51717. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  51718. __decorate([
  51719. BABYLON.serialize()
  51720. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  51721. __decorate([
  51722. BABYLON.serialize()
  51723. ], PBRMaterial.prototype, "cameraExposure", void 0);
  51724. __decorate([
  51725. BABYLON.serialize()
  51726. ], PBRMaterial.prototype, "cameraContrast", void 0);
  51727. __decorate([
  51728. BABYLON.serializeAsTexture()
  51729. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  51730. __decorate([
  51731. BABYLON.serializeAsColorCurves()
  51732. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  51733. __decorate([
  51734. BABYLON.serializeAsColor3()
  51735. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  51736. __decorate([
  51737. BABYLON.serialize()
  51738. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  51739. __decorate([
  51740. BABYLON.serializeAsColor3()
  51741. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  51742. __decorate([
  51743. BABYLON.serialize()
  51744. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  51745. __decorate([
  51746. BABYLON.serializeAsColor3()
  51747. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  51748. __decorate([
  51749. BABYLON.serialize()
  51750. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  51751. __decorate([
  51752. BABYLON.serializeAsColor3()
  51753. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  51754. __decorate([
  51755. BABYLON.serialize()
  51756. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  51757. __decorate([
  51758. BABYLON.serializeAsColor3()
  51759. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  51760. __decorate([
  51761. BABYLON.serialize()
  51762. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  51763. __decorate([
  51764. BABYLON.serialize()
  51765. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  51766. __decorate([
  51767. BABYLON.serialize()
  51768. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  51769. __decorate([
  51770. BABYLON.serializeAsTexture()
  51771. ], PBRMaterial.prototype, "albedoTexture", void 0);
  51772. __decorate([
  51773. BABYLON.serializeAsTexture()
  51774. ], PBRMaterial.prototype, "ambientTexture", void 0);
  51775. __decorate([
  51776. BABYLON.serializeAsTexture()
  51777. ], PBRMaterial.prototype, "opacityTexture", void 0);
  51778. __decorate([
  51779. BABYLON.serializeAsTexture()
  51780. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  51781. __decorate([
  51782. BABYLON.serializeAsTexture()
  51783. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  51784. __decorate([
  51785. BABYLON.serializeAsTexture()
  51786. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  51787. __decorate([
  51788. BABYLON.serializeAsTexture()
  51789. ], PBRMaterial.prototype, "bumpTexture", void 0);
  51790. __decorate([
  51791. BABYLON.serializeAsTexture()
  51792. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  51793. __decorate([
  51794. BABYLON.serializeAsTexture()
  51795. ], PBRMaterial.prototype, "refractionTexture", void 0);
  51796. __decorate([
  51797. BABYLON.serializeAsColor3("ambient")
  51798. ], PBRMaterial.prototype, "ambientColor", void 0);
  51799. __decorate([
  51800. BABYLON.serializeAsColor3("albedo")
  51801. ], PBRMaterial.prototype, "albedoColor", void 0);
  51802. __decorate([
  51803. BABYLON.serializeAsColor3("reflectivity")
  51804. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  51805. __decorate([
  51806. BABYLON.serializeAsColor3("reflection")
  51807. ], PBRMaterial.prototype, "reflectionColor", void 0);
  51808. __decorate([
  51809. BABYLON.serializeAsColor3("emissive")
  51810. ], PBRMaterial.prototype, "emissiveColor", void 0);
  51811. __decorate([
  51812. BABYLON.serialize()
  51813. ], PBRMaterial.prototype, "microSurface", void 0);
  51814. __decorate([
  51815. BABYLON.serialize()
  51816. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  51817. __decorate([
  51818. BABYLON.serialize()
  51819. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  51820. __decorate([
  51821. BABYLON.serializeAsFresnelParameters()
  51822. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  51823. __decorate([
  51824. BABYLON.serializeAsFresnelParameters()
  51825. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  51826. __decorate([
  51827. BABYLON.serialize()
  51828. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  51829. __decorate([
  51830. BABYLON.serialize()
  51831. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  51832. __decorate([
  51833. BABYLON.serialize()
  51834. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  51835. __decorate([
  51836. BABYLON.serialize()
  51837. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  51838. __decorate([
  51839. BABYLON.serialize()
  51840. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  51841. __decorate([
  51842. BABYLON.serialize()
  51843. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  51844. __decorate([
  51845. BABYLON.serialize()
  51846. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  51847. __decorate([
  51848. BABYLON.serialize()
  51849. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  51850. __decorate([
  51851. BABYLON.serialize()
  51852. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  51853. __decorate([
  51854. BABYLON.serialize()
  51855. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  51856. __decorate([
  51857. BABYLON.serialize()
  51858. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  51859. __decorate([
  51860. BABYLON.serialize()
  51861. ], PBRMaterial.prototype, "useParallax", void 0);
  51862. __decorate([
  51863. BABYLON.serialize()
  51864. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  51865. __decorate([
  51866. BABYLON.serialize()
  51867. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  51868. __decorate([
  51869. BABYLON.serialize()
  51870. ], PBRMaterial.prototype, "disableLighting", void 0);
  51871. __decorate([
  51872. BABYLON.serialize()
  51873. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  51874. __decorate([
  51875. BABYLON.serialize()
  51876. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  51877. __decorate([
  51878. BABYLON.serialize()
  51879. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  51880. __decorate([
  51881. BABYLON.serialize()
  51882. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  51883. return PBRMaterial;
  51884. }(BABYLON.Material));
  51885. BABYLON.PBRMaterial = PBRMaterial;
  51886. })(BABYLON || (BABYLON = {}));
  51887. var BABYLON;
  51888. (function (BABYLON) {
  51889. var DebugLayer = (function () {
  51890. function DebugLayer(scene) {
  51891. var _this = this;
  51892. this._transformationMatrix = BABYLON.Matrix.Identity();
  51893. this._enabled = false;
  51894. this._labelsEnabled = false;
  51895. this._displayStatistics = true;
  51896. this._displayTree = false;
  51897. this._displayLogs = false;
  51898. this._skeletonViewers = new Array();
  51899. this._identityMatrix = BABYLON.Matrix.Identity();
  51900. this.axisRatio = 0.02;
  51901. this.accentColor = "orange";
  51902. this._scene = scene;
  51903. this._syncPositions = function () {
  51904. var engine = _this._scene.getEngine();
  51905. var canvasRect = engine.getRenderingCanvasClientRect();
  51906. if (_this._showUI) {
  51907. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  51908. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  51909. _this._statsDiv.style.width = "400px";
  51910. _this._statsDiv.style.height = "auto";
  51911. _this._statsSubsetDiv.style.maxHeight = "240px";
  51912. _this._optionsDiv.style.left = "0px";
  51913. _this._optionsDiv.style.top = "10px";
  51914. _this._optionsDiv.style.width = "200px";
  51915. _this._optionsDiv.style.height = "auto";
  51916. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  51917. _this._logDiv.style.left = "0px";
  51918. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  51919. _this._logDiv.style.width = "600px";
  51920. _this._logDiv.style.height = "160px";
  51921. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  51922. _this._treeDiv.style.top = "10px";
  51923. _this._treeDiv.style.width = "300px";
  51924. _this._treeDiv.style.height = "auto";
  51925. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  51926. }
  51927. _this._globalDiv.style.left = canvasRect.left + "px";
  51928. _this._globalDiv.style.top = canvasRect.top + "px";
  51929. _this._drawingCanvas.style.left = "0px";
  51930. _this._drawingCanvas.style.top = "0px";
  51931. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  51932. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  51933. var devicePixelRatio = window.devicePixelRatio || 1;
  51934. var context = _this._drawingContext;
  51935. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  51936. context.mozBackingStorePixelRatio ||
  51937. context.msBackingStorePixelRatio ||
  51938. context.oBackingStorePixelRatio ||
  51939. context.backingStorePixelRatio || 1;
  51940. _this._ratio = devicePixelRatio / backingStoreRatio;
  51941. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  51942. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  51943. };
  51944. this._onCanvasClick = function (evt) {
  51945. _this._clickPosition = {
  51946. x: evt.clientX * _this._ratio,
  51947. y: evt.clientY * _this._ratio
  51948. };
  51949. };
  51950. this._syncUI = function () {
  51951. if (_this._showUI) {
  51952. if (_this._displayStatistics) {
  51953. _this._displayStats();
  51954. _this._statsDiv.style.display = "";
  51955. }
  51956. else {
  51957. _this._statsDiv.style.display = "none";
  51958. }
  51959. if (_this._displayLogs) {
  51960. _this._logDiv.style.display = "";
  51961. }
  51962. else {
  51963. _this._logDiv.style.display = "none";
  51964. }
  51965. if (_this._displayTree) {
  51966. _this._treeDiv.style.display = "";
  51967. if (_this._needToRefreshMeshesTree) {
  51968. _this._needToRefreshMeshesTree = false;
  51969. _this._refreshMeshesTreeContent();
  51970. }
  51971. }
  51972. else {
  51973. _this._treeDiv.style.display = "none";
  51974. }
  51975. }
  51976. };
  51977. this._syncData = function () {
  51978. if (_this._labelsEnabled || !_this._showUI) {
  51979. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  51980. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  51981. var engine = _this._scene.getEngine();
  51982. var viewport = _this._camera.viewport;
  51983. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  51984. // Meshes
  51985. var meshes = _this._camera.getActiveMeshes();
  51986. var index;
  51987. var projectedPosition;
  51988. for (index = 0; index < meshes.length; index++) {
  51989. var mesh = meshes.data[index];
  51990. var position = mesh.getBoundingInfo().boundingSphere.center;
  51991. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  51992. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  51993. _this._renderAxis(projectedPosition, mesh, globalViewport);
  51994. }
  51995. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  51996. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  51997. }
  51998. }
  51999. // Cameras
  52000. var cameras = _this._scene.cameras;
  52001. for (index = 0; index < cameras.length; index++) {
  52002. var camera = cameras[index];
  52003. if (camera === _this._camera) {
  52004. continue;
  52005. }
  52006. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  52007. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  52008. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  52009. _this._camera.detachControl(engine.getRenderingCanvas());
  52010. _this._camera = camera;
  52011. _this._camera.attachControl(engine.getRenderingCanvas());
  52012. }, function () { return "purple"; });
  52013. }
  52014. }
  52015. // Lights
  52016. var lights = _this._scene.lights;
  52017. for (index = 0; index < lights.length; index++) {
  52018. var light = lights[index];
  52019. if (light.position) {
  52020. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  52021. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  52022. _this._renderLabel(light.name, projectedPosition, -20, function () {
  52023. light.setEnabled(!light.isEnabled());
  52024. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  52025. }
  52026. }
  52027. }
  52028. }
  52029. _this._clickPosition = undefined;
  52030. };
  52031. }
  52032. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  52033. while (this._treeSubsetDiv.hasChildNodes()) {
  52034. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  52035. }
  52036. // Add meshes
  52037. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  52038. sortedArray.sort(function (a, b) {
  52039. if (a.name === b.name) {
  52040. return 0;
  52041. }
  52042. return (a.name > b.name) ? 1 : -1;
  52043. });
  52044. for (var index = 0; index < sortedArray.length; index++) {
  52045. var mesh = sortedArray[index];
  52046. if (!mesh.isEnabled()) {
  52047. continue;
  52048. }
  52049. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  52050. m.isVisible = element.checked;
  52051. }, mesh);
  52052. }
  52053. };
  52054. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  52055. this._drawingContext.beginPath();
  52056. this._drawingContext.moveTo(zero.x, zero.y);
  52057. this._drawingContext.lineTo(unit.x, unit.y);
  52058. this._drawingContext.strokeStyle = color;
  52059. this._drawingContext.lineWidth = 4;
  52060. this._drawingContext.stroke();
  52061. this._drawingContext.font = "normal 14px Segoe UI";
  52062. this._drawingContext.fillStyle = color;
  52063. this._drawingContext.fillText(label, unitText.x, unitText.y);
  52064. };
  52065. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  52066. var position = mesh.getBoundingInfo().boundingSphere.center;
  52067. var worldMatrix = mesh.getWorldMatrix();
  52068. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  52069. var unit = (unprojectedVector.subtract(position)).length();
  52070. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52071. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52072. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  52073. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52074. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52075. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  52076. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  52077. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  52078. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  52079. };
  52080. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  52081. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  52082. this._drawingContext.font = "normal 12px Segoe UI";
  52083. var textMetrics = this._drawingContext.measureText(text);
  52084. var centerX = projectedPosition.x - textMetrics.width / 2;
  52085. var centerY = projectedPosition.y;
  52086. var clientRect = this._drawingCanvas.getBoundingClientRect();
  52087. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  52088. onClick();
  52089. }
  52090. this._drawingContext.beginPath();
  52091. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  52092. this._drawingContext.fillStyle = getFillStyle();
  52093. this._drawingContext.globalAlpha = 0.5;
  52094. this._drawingContext.fill();
  52095. this._drawingContext.globalAlpha = 1.0;
  52096. this._drawingContext.strokeStyle = '#FFFFFF';
  52097. this._drawingContext.lineWidth = 1;
  52098. this._drawingContext.stroke();
  52099. this._drawingContext.fillStyle = "#FFFFFF";
  52100. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  52101. this._drawingContext.beginPath();
  52102. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  52103. this._drawingContext.fill();
  52104. }
  52105. };
  52106. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  52107. if (!this._clickPosition) {
  52108. return false;
  52109. }
  52110. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  52111. return false;
  52112. }
  52113. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  52114. return false;
  52115. }
  52116. return true;
  52117. };
  52118. DebugLayer.prototype.isVisible = function () {
  52119. return this._enabled;
  52120. };
  52121. DebugLayer.prototype.hide = function () {
  52122. if (!this._enabled) {
  52123. return;
  52124. }
  52125. this._enabled = false;
  52126. var engine = this._scene.getEngine();
  52127. this._scene.unregisterBeforeRender(this._syncData);
  52128. this._scene.unregisterAfterRender(this._syncUI);
  52129. this._rootElement.removeChild(this._globalDiv);
  52130. this._scene.forceShowBoundingBoxes = false;
  52131. this._scene.forceWireframe = false;
  52132. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  52133. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  52134. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  52135. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  52136. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  52137. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  52138. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  52139. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  52140. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  52141. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  52142. this._scene.shadowsEnabled = true;
  52143. this._scene.particlesEnabled = true;
  52144. this._scene.postProcessesEnabled = true;
  52145. this._scene.collisionsEnabled = true;
  52146. this._scene.lightsEnabled = true;
  52147. this._scene.texturesEnabled = true;
  52148. this._scene.lensFlaresEnabled = true;
  52149. this._scene.proceduralTexturesEnabled = true;
  52150. this._scene.renderTargetsEnabled = true;
  52151. this._scene.probesEnabled = true;
  52152. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  52153. this._clearSkeletonViewers();
  52154. };
  52155. DebugLayer.prototype._clearSkeletonViewers = function () {
  52156. for (var index = 0; index < this._skeletonViewers.length; index++) {
  52157. this._skeletonViewers[index].dispose();
  52158. }
  52159. this._skeletonViewers = [];
  52160. };
  52161. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  52162. if (showUI === void 0) { showUI = true; }
  52163. if (camera === void 0) { camera = null; }
  52164. if (rootElement === void 0) { rootElement = null; }
  52165. if (this._enabled) {
  52166. return;
  52167. }
  52168. this._enabled = true;
  52169. if (camera) {
  52170. this._camera = camera;
  52171. }
  52172. else {
  52173. this._camera = this._scene.activeCamera;
  52174. }
  52175. this._showUI = showUI;
  52176. var engine = this._scene.getEngine();
  52177. this._globalDiv = document.createElement("div");
  52178. this._rootElement = rootElement || document.body;
  52179. this._rootElement.appendChild(this._globalDiv);
  52180. this._generateDOMelements();
  52181. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  52182. this._syncPositions();
  52183. this._scene.registerBeforeRender(this._syncData);
  52184. this._scene.registerAfterRender(this._syncUI);
  52185. };
  52186. DebugLayer.prototype._clearLabels = function () {
  52187. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  52188. for (var index = 0; index < this._scene.meshes.length; index++) {
  52189. var mesh = this._scene.meshes[index];
  52190. mesh.renderOverlay = false;
  52191. }
  52192. };
  52193. DebugLayer.prototype._generateheader = function (root, text) {
  52194. var header = document.createElement("div");
  52195. header.innerHTML = text + "&nbsp;";
  52196. header.style.textAlign = "right";
  52197. header.style.width = "100%";
  52198. header.style.color = "white";
  52199. header.style.backgroundColor = "Black";
  52200. header.style.padding = "5px 5px 4px 0px";
  52201. header.style.marginLeft = "-5px";
  52202. header.style.fontWeight = "bold";
  52203. root.appendChild(header);
  52204. };
  52205. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  52206. var label = document.createElement("label");
  52207. label.style.display = "inline";
  52208. label.innerHTML = title;
  52209. label.style.color = color;
  52210. root.appendChild(label);
  52211. root.appendChild(document.createElement("br"));
  52212. };
  52213. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  52214. if (tag === void 0) { tag = null; }
  52215. var label = document.createElement("label");
  52216. label.style.display = "inline";
  52217. var boundingBoxesCheckbox = document.createElement("input");
  52218. boundingBoxesCheckbox.type = "checkbox";
  52219. boundingBoxesCheckbox.checked = initialState;
  52220. boundingBoxesCheckbox.style.display = "inline";
  52221. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  52222. boundingBoxesCheckbox.style.verticalAlign = "sub";
  52223. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  52224. task(evt.target, tag);
  52225. });
  52226. label.appendChild(boundingBoxesCheckbox);
  52227. var container = document.createElement("span");
  52228. var leftPart = document.createElement("span");
  52229. var rightPart = document.createElement("span");
  52230. rightPart.style.cssFloat = "right";
  52231. leftPart.innerHTML = leftTitle;
  52232. rightPart.innerHTML = rightTitle;
  52233. rightPart.style.fontSize = "12px";
  52234. rightPart.style.maxWidth = "200px";
  52235. container.appendChild(leftPart);
  52236. container.appendChild(rightPart);
  52237. label.appendChild(container);
  52238. root.appendChild(label);
  52239. root.appendChild(document.createElement("br"));
  52240. };
  52241. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  52242. if (tag === void 0) { tag = null; }
  52243. var label = document.createElement("label");
  52244. label.style.display = "inline";
  52245. var checkBox = document.createElement("input");
  52246. checkBox.type = "checkbox";
  52247. checkBox.checked = initialState;
  52248. checkBox.style.display = "inline";
  52249. checkBox.style.margin = "0px 5px 0px 0px";
  52250. checkBox.style.verticalAlign = "sub";
  52251. checkBox.addEventListener("change", function (evt) {
  52252. task(evt.target, tag);
  52253. });
  52254. label.appendChild(checkBox);
  52255. label.appendChild(document.createTextNode(title));
  52256. root.appendChild(label);
  52257. root.appendChild(document.createElement("br"));
  52258. };
  52259. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  52260. if (tag === void 0) { tag = null; }
  52261. var button = document.createElement("button");
  52262. button.innerHTML = title;
  52263. button.style.height = "24px";
  52264. button.style.width = "150px";
  52265. button.style.marginBottom = "5px";
  52266. button.style.color = "#444444";
  52267. button.style.border = "1px solid white";
  52268. button.className = "debugLayerButton";
  52269. button.addEventListener("click", function (evt) {
  52270. task(evt.target, tag);
  52271. });
  52272. root.appendChild(button);
  52273. root.appendChild(document.createElement("br"));
  52274. };
  52275. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  52276. if (tag === void 0) { tag = null; }
  52277. var label = document.createElement("label");
  52278. label.style.display = "inline";
  52279. var boundingBoxesRadio = document.createElement("input");
  52280. boundingBoxesRadio.type = "radio";
  52281. boundingBoxesRadio.name = name;
  52282. boundingBoxesRadio.checked = initialState;
  52283. boundingBoxesRadio.style.display = "inline";
  52284. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  52285. boundingBoxesRadio.style.verticalAlign = "sub";
  52286. boundingBoxesRadio.addEventListener("change", function (evt) {
  52287. task(evt.target, tag);
  52288. });
  52289. label.appendChild(boundingBoxesRadio);
  52290. label.appendChild(document.createTextNode(title));
  52291. root.appendChild(label);
  52292. root.appendChild(document.createElement("br"));
  52293. };
  52294. DebugLayer.prototype._generateDOMelements = function () {
  52295. var _this = this;
  52296. this._globalDiv.id = "DebugLayer";
  52297. this._globalDiv.style.position = "absolute";
  52298. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  52299. this._globalDiv.style.fontSize = "14px";
  52300. this._globalDiv.style.color = "white";
  52301. // Drawing canvas
  52302. this._drawingCanvas = document.createElement("canvas");
  52303. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  52304. this._drawingCanvas.style.position = "absolute";
  52305. this._drawingCanvas.style.pointerEvents = "none";
  52306. this._drawingCanvas.style.backgroundColor = "transparent";
  52307. this._drawingContext = this._drawingCanvas.getContext("2d");
  52308. this._globalDiv.appendChild(this._drawingCanvas);
  52309. if (this._showUI) {
  52310. var background = "rgba(128, 128, 128, 0.4)";
  52311. var border = "rgb(180, 180, 180) solid 1px";
  52312. // Stats
  52313. this._statsDiv = document.createElement("div");
  52314. this._statsDiv.id = "DebugLayerStats";
  52315. this._statsDiv.style.border = border;
  52316. this._statsDiv.style.position = "absolute";
  52317. this._statsDiv.style.background = background;
  52318. this._statsDiv.style.padding = "0px 0px 0px 5px";
  52319. this._generateheader(this._statsDiv, "STATISTICS");
  52320. this._statsSubsetDiv = document.createElement("div");
  52321. this._statsSubsetDiv.style.paddingTop = "5px";
  52322. this._statsSubsetDiv.style.paddingBottom = "5px";
  52323. this._statsSubsetDiv.style.overflowY = "auto";
  52324. this._statsDiv.appendChild(this._statsSubsetDiv);
  52325. // Tree
  52326. this._treeDiv = document.createElement("div");
  52327. this._treeDiv.id = "DebugLayerTree";
  52328. this._treeDiv.style.border = border;
  52329. this._treeDiv.style.position = "absolute";
  52330. this._treeDiv.style.background = background;
  52331. this._treeDiv.style.padding = "0px 0px 0px 5px";
  52332. this._treeDiv.style.display = "none";
  52333. this._generateheader(this._treeDiv, "MESHES TREE");
  52334. this._treeSubsetDiv = document.createElement("div");
  52335. this._treeSubsetDiv.style.paddingTop = "5px";
  52336. this._treeSubsetDiv.style.paddingRight = "5px";
  52337. this._treeSubsetDiv.style.overflowY = "auto";
  52338. this._treeSubsetDiv.style.maxHeight = "300px";
  52339. this._treeDiv.appendChild(this._treeSubsetDiv);
  52340. this._needToRefreshMeshesTree = true;
  52341. // Logs
  52342. this._logDiv = document.createElement("div");
  52343. this._logDiv.style.border = border;
  52344. this._logDiv.id = "DebugLayerLogs";
  52345. this._logDiv.style.position = "absolute";
  52346. this._logDiv.style.background = background;
  52347. this._logDiv.style.padding = "0px 0px 0px 5px";
  52348. this._logDiv.style.display = "none";
  52349. this._generateheader(this._logDiv, "LOGS");
  52350. this._logSubsetDiv = document.createElement("div");
  52351. this._logSubsetDiv.style.height = "127px";
  52352. this._logSubsetDiv.style.paddingTop = "5px";
  52353. this._logSubsetDiv.style.overflowY = "auto";
  52354. this._logSubsetDiv.style.fontSize = "12px";
  52355. this._logSubsetDiv.style.fontFamily = "consolas";
  52356. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  52357. this._logDiv.appendChild(this._logSubsetDiv);
  52358. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  52359. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  52360. };
  52361. // Options
  52362. this._optionsDiv = document.createElement("div");
  52363. this._optionsDiv.id = "DebugLayerOptions";
  52364. this._optionsDiv.style.border = border;
  52365. this._optionsDiv.style.position = "absolute";
  52366. this._optionsDiv.style.background = background;
  52367. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  52368. this._optionsDiv.style.overflowY = "auto";
  52369. this._generateheader(this._optionsDiv, "OPTIONS");
  52370. this._optionsSubsetDiv = document.createElement("div");
  52371. this._optionsSubsetDiv.style.paddingTop = "5px";
  52372. this._optionsSubsetDiv.style.paddingBottom = "5px";
  52373. this._optionsSubsetDiv.style.overflowY = "auto";
  52374. this._optionsSubsetDiv.style.maxHeight = "200px";
  52375. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  52376. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  52377. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  52378. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  52379. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  52380. _this._displayTree = element.checked;
  52381. _this._needToRefreshMeshesTree = true;
  52382. });
  52383. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52384. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  52385. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  52386. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  52387. _this._labelsEnabled = element.checked;
  52388. if (!_this._labelsEnabled) {
  52389. _this._clearLabels();
  52390. }
  52391. });
  52392. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  52393. if (element.checked) {
  52394. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  52395. }
  52396. else {
  52397. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  52398. }
  52399. });
  52400. ;
  52401. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52402. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  52403. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  52404. if (element.checked) {
  52405. _this._scene.forceWireframe = false;
  52406. _this._scene.forcePointsCloud = false;
  52407. }
  52408. });
  52409. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  52410. if (element.checked) {
  52411. _this._scene.forceWireframe = true;
  52412. _this._scene.forcePointsCloud = false;
  52413. }
  52414. });
  52415. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  52416. if (element.checked) {
  52417. _this._scene.forceWireframe = false;
  52418. _this._scene.forcePointsCloud = true;
  52419. }
  52420. });
  52421. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52422. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  52423. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  52424. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  52425. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  52426. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  52427. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  52428. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  52429. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  52430. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  52431. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  52432. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  52433. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  52434. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52435. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  52436. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  52437. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  52438. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  52439. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  52440. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  52441. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  52442. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  52443. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  52444. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  52445. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  52446. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  52447. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  52448. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  52449. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  52450. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  52451. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52452. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  52453. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  52454. if (element.checked) {
  52455. _this._scene.headphone = true;
  52456. }
  52457. });
  52458. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  52459. if (element.checked) {
  52460. _this._scene.headphone = false;
  52461. }
  52462. });
  52463. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  52464. _this._scene.audioEnabled = !element.checked;
  52465. });
  52466. }
  52467. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52468. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  52469. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  52470. if (!element.checked) {
  52471. _this._clearSkeletonViewers();
  52472. return;
  52473. }
  52474. for (var index = 0; index < _this._scene.meshes.length; index++) {
  52475. var mesh = _this._scene.meshes[index];
  52476. if (mesh.skeleton) {
  52477. var found = false;
  52478. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  52479. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  52480. found = true;
  52481. break;
  52482. }
  52483. }
  52484. if (found) {
  52485. continue;
  52486. }
  52487. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  52488. viewer.isEnabled = true;
  52489. _this._skeletonViewers.push(viewer);
  52490. }
  52491. }
  52492. });
  52493. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52494. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  52495. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  52496. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  52497. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  52498. if (_this._camera) {
  52499. console.log(_this._camera);
  52500. }
  52501. else {
  52502. console.warn("No camera defined, or debug layer created before camera creation!");
  52503. }
  52504. });
  52505. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52506. this._globalDiv.appendChild(this._statsDiv);
  52507. this._globalDiv.appendChild(this._logDiv);
  52508. this._globalDiv.appendChild(this._optionsDiv);
  52509. this._globalDiv.appendChild(this._treeDiv);
  52510. }
  52511. };
  52512. DebugLayer.prototype._displayStats = function () {
  52513. var scene = this._scene;
  52514. var engine = scene.getEngine();
  52515. var glInfo = engine.getGlInfo();
  52516. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  52517. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  52518. + "<b>Count</b><br>"
  52519. + "Total meshes: " + scene.meshes.length + "<br>"
  52520. + "Total lights: " + scene.lights.length + "<br>"
  52521. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  52522. + "Total materials: " + scene.materials.length + "<br>"
  52523. + "Total textures: " + scene.textures.length + "<br>"
  52524. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  52525. + "Active indices: " + scene.getActiveIndices() + "<br>"
  52526. + "Active bones: " + scene.getActiveBones() + "<br>"
  52527. + "Active particles: " + scene.getActiveParticles() + "<br>"
  52528. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  52529. + "<b>Duration</b><br>"
  52530. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  52531. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  52532. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  52533. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  52534. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  52535. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  52536. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  52537. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  52538. + "</div>"
  52539. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  52540. + "<b>Extensions</b><br>"
  52541. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  52542. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  52543. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  52544. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  52545. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  52546. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  52547. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  52548. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  52549. + "</div><br>"
  52550. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  52551. + "<b>Caps.</b><br>"
  52552. + "Stencil: " + (engine.isStencilEnable ? "Enabled" : "Disabled") + "<br>"
  52553. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  52554. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  52555. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  52556. + "<b>Info</b><br>"
  52557. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  52558. + glInfo.version + "<br>"
  52559. + "</div><br>"
  52560. + glInfo.renderer + "<br>";
  52561. if (this.customStatsFunction) {
  52562. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  52563. }
  52564. };
  52565. return DebugLayer;
  52566. }());
  52567. BABYLON.DebugLayer = DebugLayer;
  52568. })(BABYLON || (BABYLON = {}));
  52569. var BABYLON;
  52570. (function (BABYLON) {
  52571. var StandardRenderingPipeline = (function (_super) {
  52572. __extends(StandardRenderingPipeline, _super);
  52573. /**
  52574. * @constructor
  52575. * @param {string} name - The rendering pipeline name
  52576. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52577. * @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)
  52578. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  52579. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52580. */
  52581. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  52582. var _this = this;
  52583. if (originalPostProcess === void 0) { originalPostProcess = null; }
  52584. _super.call(this, scene.getEngine(), name);
  52585. this.downSampleX4PostProcess = null;
  52586. this.brightPassPostProcess = null;
  52587. this.gaussianBlurHPostProcesses = [];
  52588. this.gaussianBlurVPostProcesses = [];
  52589. this.textureAdderPostProcess = null;
  52590. this.textureAdderFinalPostProcess = null;
  52591. this.lensFlarePostProcess = null;
  52592. this.lensFlareShiftPostProcess = null;
  52593. this.lensFlareComposePostProcess = null;
  52594. this.depthOfFieldPostProcess = null;
  52595. this.motionBlurPostProcess = null;
  52596. // Values
  52597. this.brightThreshold = 1.0;
  52598. this.gaussianCoefficient = 0.25;
  52599. this.gaussianMean = 1.0;
  52600. this.gaussianStandardDeviation = 1.0;
  52601. this.exposure = 1.0;
  52602. this.lensTexture = null;
  52603. this.lensColorTexture = null;
  52604. this.lensFlareStrength = 1.0;
  52605. this.lensFlareGhostDispersal = 1.0;
  52606. this.lensFlareHaloWidth = 0.4;
  52607. this.lensFlareDistortionStrength = 4.0;
  52608. this.lensStarTexture = null;
  52609. this.lensFlareDirtTexture = null;
  52610. this.depthOfFieldDistance = 10.0;
  52611. this._depthRenderer = null;
  52612. // Getters and setters
  52613. this._depthOfFieldEnabled = true;
  52614. this._lensFlareEnabled = true;
  52615. // Initialize
  52616. this._scene = scene;
  52617. // Create pass post-processe
  52618. if (!originalPostProcess) {
  52619. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  52620. }
  52621. else {
  52622. this.originalPostProcess = originalPostProcess;
  52623. }
  52624. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  52625. // Create down sample X4 post-process
  52626. this._createDownSampleX4PostProcess(scene, ratio / 2);
  52627. // Create bright pass post-process
  52628. this._createBrightPassPostProcess(scene, ratio / 2);
  52629. // Create gaussian blur post-processes (down sampling blurs)
  52630. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  52631. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  52632. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  52633. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  52634. // Create texture adder post-process
  52635. this._createTextureAdderPostProcess(scene, ratio);
  52636. // Create depth-of-field source post-process
  52637. this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRTextureAdderPostProcess", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52638. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  52639. // Create lens flare post-process
  52640. this._createLensFlarePostProcess(scene, ratio);
  52641. // Create gaussian blur used by depth-of-field
  52642. this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  52643. // Create depth-of-field post-process
  52644. this._createDepthOfFieldPostProcess(scene, ratio);
  52645. // Finish
  52646. scene.postProcessRenderPipelineManager.addPipeline(this);
  52647. if (cameras !== null) {
  52648. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52649. }
  52650. // Deactivate
  52651. this.LensFlareEnabled = false;
  52652. this.DepthOfFieldEnabled = false;
  52653. }
  52654. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  52655. get: function () {
  52656. return this._depthOfFieldEnabled;
  52657. },
  52658. set: function (enabled) {
  52659. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  52660. if (enabled && !this._depthOfFieldEnabled) {
  52661. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  52662. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  52663. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  52664. this._depthRenderer = this._scene.enableDepthRenderer();
  52665. }
  52666. else if (!enabled && this._depthOfFieldEnabled) {
  52667. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  52668. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  52669. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  52670. }
  52671. this._depthOfFieldEnabled = enabled;
  52672. },
  52673. enumerable: true,
  52674. configurable: true
  52675. });
  52676. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  52677. get: function () {
  52678. return this._lensFlareEnabled;
  52679. },
  52680. set: function (enabled) {
  52681. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  52682. if (enabled && !this._lensFlareEnabled) {
  52683. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  52684. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  52685. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  52686. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  52687. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  52688. this._depthRenderer = this._scene.enableDepthRenderer();
  52689. }
  52690. else if (!enabled && this._lensFlareEnabled) {
  52691. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  52692. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  52693. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  52694. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  52695. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  52696. }
  52697. this._lensFlareEnabled = enabled;
  52698. },
  52699. enumerable: true,
  52700. configurable: true
  52701. });
  52702. // Down Sample X4 Post-Processs
  52703. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  52704. var _this = this;
  52705. var downSampleX4Offsets = new Array(32);
  52706. 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);
  52707. this.downSampleX4PostProcess.onApply = function (effect) {
  52708. var id = 0;
  52709. for (var i = -2; i < 2; i++) {
  52710. for (var j = -2; j < 2; j++) {
  52711. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  52712. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  52713. id += 2;
  52714. }
  52715. }
  52716. effect.setArray2("dsOffsets", downSampleX4Offsets);
  52717. };
  52718. // Add to pipeline
  52719. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  52720. };
  52721. // Brightpass Post-Process
  52722. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  52723. var _this = this;
  52724. var brightOffsets = new Array(8);
  52725. 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);
  52726. this.brightPassPostProcess.onApply = function (effect) {
  52727. var sU = (1.0 / _this.brightPassPostProcess.width);
  52728. var sV = (1.0 / _this.brightPassPostProcess.height);
  52729. brightOffsets[0] = -0.5 * sU;
  52730. brightOffsets[1] = 0.5 * sV;
  52731. brightOffsets[2] = 0.5 * sU;
  52732. brightOffsets[3] = 0.5 * sV;
  52733. brightOffsets[4] = -0.5 * sU;
  52734. brightOffsets[5] = -0.5 * sV;
  52735. brightOffsets[6] = 0.5 * sU;
  52736. brightOffsets[7] = -0.5 * sV;
  52737. effect.setArray2("dsOffsets", brightOffsets);
  52738. effect.setFloat("brightThreshold", _this.brightThreshold);
  52739. };
  52740. // Add to pipeline
  52741. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  52742. };
  52743. // Create gaussian blur H&V post-processes
  52744. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  52745. var _this = this;
  52746. var blurOffsets = new Array(9);
  52747. var blurWeights = new Array(9);
  52748. var uniforms = ["blurOffsets", "blurWeights"];
  52749. var callback = function (height) {
  52750. return function (effect) {
  52751. // Weights
  52752. var x = 0.0;
  52753. for (var i = 0; i < 9; i++) {
  52754. x = (i - 4.0) / 4.0;
  52755. blurWeights[i] =
  52756. _this.gaussianCoefficient
  52757. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  52758. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  52759. }
  52760. var lastOutputDimensions = {
  52761. width: scene.getEngine().getRenderWidth(),
  52762. height: scene.getEngine().getRenderHeight()
  52763. };
  52764. for (var i = 0; i < 9; i++) {
  52765. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  52766. blurOffsets[i] = value;
  52767. }
  52768. effect.setArray("blurOffsets", blurOffsets);
  52769. effect.setArray("blurWeights", blurWeights);
  52770. };
  52771. };
  52772. // Create horizontal gaussian blur post-processes
  52773. 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);
  52774. gaussianBlurHPostProcess.onApply = callback(false);
  52775. // Create vertical gaussian blur post-process
  52776. 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);
  52777. gaussianBlurVPostProcess.onApply = callback(true);
  52778. // Add to pipeline
  52779. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  52780. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  52781. // Finish
  52782. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  52783. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  52784. };
  52785. // Create texture adder post-process
  52786. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  52787. var _this = this;
  52788. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  52789. 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);
  52790. this.textureAdderPostProcess.onApply = function (effect) {
  52791. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  52792. effect.setTexture("lensSampler", _this.lensTexture);
  52793. effect.setFloat("exposure", _this.exposure);
  52794. };
  52795. // Add to pipeline
  52796. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  52797. };
  52798. // Create lens flare post-process
  52799. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  52800. var _this = this;
  52801. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth"], ["lensColorSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52802. this.lensFlareShiftPostProcess = new BABYLON.PostProcess("HDRLensFlareShift", "standard", ["resolution", "distortionStrength"], [], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_SHIFT", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52803. this._createGaussianBlurPostProcesses(scene, ratio / 8, 4);
  52804. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["viewMatrix", "scaleBias1", "scaleBias2"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52805. var resolution = new BABYLON.Vector2(0, 0);
  52806. // Lens flare
  52807. this.lensFlarePostProcess.onApply = function (effect) {
  52808. effect.setTextureFromPostProcess("textureSampler", _this.textureAdderPostProcess);
  52809. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  52810. effect.setFloat("strength", _this.lensFlareStrength);
  52811. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  52812. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  52813. };
  52814. // Shift
  52815. this.lensFlareShiftPostProcess.onApply = function (effect) {
  52816. resolution.x = _this.lensFlareShiftPostProcess.width;
  52817. resolution.y = _this.lensFlareShiftPostProcess.height;
  52818. effect.setVector2("resolution", resolution);
  52819. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  52820. };
  52821. // Compose
  52822. var scaleBias1 = BABYLON.Matrix.GetAsMatrix3x3(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, 0.0));
  52823. var scaleBias2 = BABYLON.Matrix.GetAsMatrix3x3(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, 0.0));
  52824. this.lensFlareComposePostProcess.onApply = function (effect) {
  52825. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  52826. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  52827. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  52828. effect.setMatrix("viewMatrix", _this._scene.activeCamera.getViewMatrix());
  52829. effect.setMatrix3x3("scaleBias1", scaleBias1);
  52830. effect.setMatrix3x3("scaleBias2", scaleBias2);
  52831. };
  52832. // Add to pipeline
  52833. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  52834. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareShift", function () { return _this.lensFlareShiftPostProcess; }, false));
  52835. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  52836. };
  52837. // Create depth-of-field post-process
  52838. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  52839. var _this = this;
  52840. 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);
  52841. this.depthOfFieldPostProcess.onApply = function (effect) {
  52842. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  52843. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  52844. effect.setFloat("distance", _this.depthOfFieldDistance);
  52845. };
  52846. // Add to pipeline
  52847. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  52848. };
  52849. return StandardRenderingPipeline;
  52850. }(BABYLON.PostProcessRenderPipeline));
  52851. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  52852. })(BABYLON || (BABYLON = {}));
  52853. 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#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\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).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);\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).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);\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 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 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(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;\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 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(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 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(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<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\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#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\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\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.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).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);\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).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 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(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}"};
  52854. 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":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\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"};
  52855. 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,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){r.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],r.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],r.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n,s=t.z+(i.z-t.z)*n;return new r(o,e,s)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){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,r.copyFrom(M.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,(-(t.y/o*2-1)),t.z),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=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(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,r.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(),r.CrossToRef(_,T,A),A.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z),(-this.w))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.substract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r,n,o,e=this.x,s=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=e*s+h*a;if(u>.499&&(r=2*Math.atan2(e,a),n=Math.PI/2,o=0),u<-.499&&(r=-2*Math.atan2(e,a),n=-Math.PI/2,o=0),isNaN(r)){var m=e*e,y=s*s,c=h*h;r=Math.atan2(2*s*a-2*e*h,1-2*y-2*c),n=Math.asin(2*u),o=Math.atan2(2*e*a-2*s*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=r,t.z=n,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o,e,s=n,h=i.x*r.x+i.y*r.y+i.z*r.z+i.w*r.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*r.x,e*i.y+o*r.y,e*i.z+o*r.z,e*i.w+o*r.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],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},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 r=new t;return this.addToRef(i,r),r},t.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];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],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),b=1/(i*T+r*_+n*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]=-(r*z-n*w+o*v)*b,t.m[5]=(i*z-n*d+o*g)*b,t.m[9]=-(i*w-r*d+o*R)*b,t.m[13]=(i*v-r*g+n*R)*b,t.m[2]=(r*F-n*L+o*C)*b,t.m[6]=-(i*F-n*P+o*Z)*b,t.m[10]=(i*L-r*P+o*S)*b,t.m[14]=-(i*C-r*Z+n*S)*b,t.m[3]=-(r*I-n*H+o*D)*b,t.m[7]=(i*I-n*q+o*V)*b,t.m[11]=-(i*H-r*q+o*N)*b,t.m[15]=(i*D-r*V+n*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 r=new t;return this.multiplyToRef(i,r),r},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 r=0;r<16;r++)t[i+r]=this.m[r];return this},t.prototype.multiplyToRef=function(t,i){\nreturn this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],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[r]=n*v+o*T+e*b+s*P,i[r+1]=n*d+o*_+e*F+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*b+m*P,i[r+5]=h*d+a*_+u*F+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*b+f*P,i[r+9]=y*d+c*_+p*F+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*b+w*P,i[r+13]=x*d+l*_+z*F+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},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(r,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return r.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),r.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),r.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===r.x||0===r.y||0===r.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(t.FromValuesToRef(this.m[0]/r.x,this.m[1]/r.x,this.m[2]/r.x,0,this.m[4]/r.y,this.m[5]/r.y,this.m[6]/r.y,0,this.m[8]/r.z,this.m[9]/r.z,this.m[10]/r.z,0,0,0,0,1,M.Matrix[0]),a.FromRotationMatrixToRef(M.Matrix[0],n),!0)},t.FromArray=function(i,r){var n=new t;return r||(r=0),t.FromArrayToRef(i,r,n),n},t.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},t.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},t.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},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 r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},t.FromValues=function(i,r,n,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]=r,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},t.Compose=function(i,r,n){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 r.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),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 r=new t;return t.RotationXToRef(i,r),r},t.Invert=function(i){var r=new t;return i.invertToRef(r),r},t.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var r=new t;return t.RotationYToRef(i,r),r},t.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var r=new t;return t.RotationZToRef(i,r),r},t.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,r){var n=t.Zero();return t.RotationAxisToRef(i,r,n),n},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},t.Scaling=function(i,r,n){var o=t.Zero();return t.ScalingToRef(i,r,n,o),o},t.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},t.Translation=function(i,r,n){var o=t.Identity();return t.TranslationToRef(i,r,n,o),o},t.TranslationToRef=function(i,r,n,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,r,n,1,o)},t.Lerp=function(i,r,n){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-n)+r.m[e]*n;return o},t.DecomposeLerp=function(i,r,n){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);r.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return t.Compose(c,p,f)},t.LookAtLH=function(i,r,n){var o=t.Zero();return t.LookAtLHToRef(i,r,n,o),o},t.LookAtLHToRef=function(i,r,n,o){r.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,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,r,n){var o=t.Zero();return t.LookAtRHToRef(i,r,n,o),o},t.LookAtRHToRef=function(i,r,n,o){i.subtractToRef(r,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,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,r,n,o){var e=t.Zero();return t.OrthoLHToRef(i,r,n,o,e),e},t.OrthoLHToRef=function(i,r,n,o,e){var s=2/i,h=2/r,a=1/(o-n),u=n/(n-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,r,n,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(n-r),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]=(n+r)/(r-n),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,r,n,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,r,n,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,r,n,o,e,s,h){t.OrthoOffCenterLHToRef(i,r,n,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,r,n,o){var e=t.Zero();return e.m[0]=2*n/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*n/r,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(n-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]=n*o/(n-o),e},t.PerspectiveFovLH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,r,n,o,e),e},t.PerspectiveFovLHToRef=function(t,i,r,n,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]=n/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(r*n)/(n-r)},t.PerspectiveFovRH=function(i,r,n,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,r,n,o,e),e},t.PerspectiveFovRHToRef=function(t,i,r,n,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]=n/(r-n),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=r*n/(r-n)},t.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-r/(i-r),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=i*r/(i-r)},t.GetFinalMatrix=function(i,r,n,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 r.multiply(n).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 r=new t;return r.m[0]=i.m[0],r.m[1]=i.m[4],r.m[2]=i.m[8],r.m[3]=i.m[12],r.m[4]=i.m[1],r.m[5]=i.m[5],r.m[6]=i.m[9],r.m[7]=i.m[13],r.m[8]=i.m[2],r.m[9]=i.m[6],r.m[10]=i.m[10],r.m[11]=i.m[14],r.m[12]=i.m[3],r.m[13]=i.m[7],r.m[14]=i.m[11],r.m[15]=i.m[15],r},t.Reflection=function(i){var r=new t;return t.ReflectionToRef(i,r),r},t.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},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,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,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,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=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,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var z=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=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 r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new 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],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=w;var v=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=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,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=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 r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=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,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[r.Black(),r.Black(),r.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={}));";
  52856. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  52857. module.exports = BABYLON;
  52858. };