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 qx = this.x;
  1558. var qy = this.y;
  1559. var qz = this.z;
  1560. var qw = this.w;
  1561. var xsqr = qx * qx;
  1562. var t0 = -2.0 * (xsqr + qy * qy) + 1.0;
  1563. var t1 = 2.0 * (qz * qx + qw * qy);
  1564. var t2 = -2.0 * (qz * qy - qw * qx);
  1565. var t3 = 2.0 * (qx * qy + qw * qz);
  1566. var t4 = -2.0 * (qz * qz + xsqr) + 1.0;
  1567. t2 = t2 > 1.0 ? 1.0 : t2;
  1568. t2 = t2 < -1.0 ? -1.0 : t2;
  1569. result.x = Math.asin(t2);
  1570. result.z = Math.atan2(t3, t4);
  1571. result.y = Math.atan2(t1, t0);
  1572. return this;
  1573. };
  1574. ;
  1575. Quaternion.prototype.toRotationMatrix = function (result) {
  1576. var xx = this.x * this.x;
  1577. var yy = this.y * this.y;
  1578. var zz = this.z * this.z;
  1579. var xy = this.x * this.y;
  1580. var zw = this.z * this.w;
  1581. var zx = this.z * this.x;
  1582. var yw = this.y * this.w;
  1583. var yz = this.y * this.z;
  1584. var xw = this.x * this.w;
  1585. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1586. result.m[1] = 2.0 * (xy + zw);
  1587. result.m[2] = 2.0 * (zx - yw);
  1588. result.m[3] = 0;
  1589. result.m[4] = 2.0 * (xy - zw);
  1590. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1591. result.m[6] = 2.0 * (yz + xw);
  1592. result.m[7] = 0;
  1593. result.m[8] = 2.0 * (zx + yw);
  1594. result.m[9] = 2.0 * (yz - xw);
  1595. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1596. result.m[11] = 0;
  1597. result.m[12] = 0;
  1598. result.m[13] = 0;
  1599. result.m[14] = 0;
  1600. result.m[15] = 1.0;
  1601. return this;
  1602. };
  1603. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1604. Quaternion.FromRotationMatrixToRef(matrix, this);
  1605. return this;
  1606. };
  1607. // Statics
  1608. Quaternion.FromRotationMatrix = function (matrix) {
  1609. var result = new Quaternion();
  1610. Quaternion.FromRotationMatrixToRef(matrix, result);
  1611. return result;
  1612. };
  1613. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1614. var data = matrix.m;
  1615. var m11 = data[0], m12 = data[4], m13 = data[8];
  1616. var m21 = data[1], m22 = data[5], m23 = data[9];
  1617. var m31 = data[2], m32 = data[6], m33 = data[10];
  1618. var trace = m11 + m22 + m33;
  1619. var s;
  1620. if (trace > 0) {
  1621. s = 0.5 / Math.sqrt(trace + 1.0);
  1622. result.w = 0.25 / s;
  1623. result.x = (m32 - m23) * s;
  1624. result.y = (m13 - m31) * s;
  1625. result.z = (m21 - m12) * s;
  1626. }
  1627. else if (m11 > m22 && m11 > m33) {
  1628. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1629. result.w = (m32 - m23) / s;
  1630. result.x = 0.25 * s;
  1631. result.y = (m12 + m21) / s;
  1632. result.z = (m13 + m31) / s;
  1633. }
  1634. else if (m22 > m33) {
  1635. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1636. result.w = (m13 - m31) / s;
  1637. result.x = (m12 + m21) / s;
  1638. result.y = 0.25 * s;
  1639. result.z = (m23 + m32) / s;
  1640. }
  1641. else {
  1642. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1643. result.w = (m21 - m12) / s;
  1644. result.x = (m13 + m31) / s;
  1645. result.y = (m23 + m32) / s;
  1646. result.z = 0.25 * s;
  1647. }
  1648. };
  1649. Quaternion.Inverse = function (q) {
  1650. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1651. };
  1652. Quaternion.Identity = function () {
  1653. return new Quaternion(0, 0, 0, 1);
  1654. };
  1655. Quaternion.RotationAxis = function (axis, angle) {
  1656. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1657. };
  1658. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1659. var sin = Math.sin(angle / 2);
  1660. axis.normalize();
  1661. result.w = Math.cos(angle / 2);
  1662. result.x = axis.x * sin;
  1663. result.y = axis.y * sin;
  1664. result.z = axis.z * sin;
  1665. return result;
  1666. };
  1667. Quaternion.FromArray = function (array, offset) {
  1668. if (!offset) {
  1669. offset = 0;
  1670. }
  1671. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1672. };
  1673. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1674. var q = new Quaternion();
  1675. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1676. return q;
  1677. };
  1678. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1679. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1680. var halfRoll = roll * 0.5;
  1681. var halfPitch = pitch * 0.5;
  1682. var halfYaw = yaw * 0.5;
  1683. var sinRoll = Math.sin(halfRoll);
  1684. var cosRoll = Math.cos(halfRoll);
  1685. var sinPitch = Math.sin(halfPitch);
  1686. var cosPitch = Math.cos(halfPitch);
  1687. var sinYaw = Math.sin(halfYaw);
  1688. var cosYaw = Math.cos(halfYaw);
  1689. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1690. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1691. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1692. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1693. };
  1694. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1695. var result = new Quaternion();
  1696. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1697. return result;
  1698. };
  1699. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1700. // Produces a quaternion from Euler angles in the z-x-z orientation
  1701. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1702. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1703. var halfBeta = beta * 0.5;
  1704. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1705. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1706. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1707. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1708. };
  1709. Quaternion.Slerp = function (left, right, amount) {
  1710. var num2;
  1711. var num3;
  1712. var num = amount;
  1713. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1714. var flag = false;
  1715. if (num4 < 0) {
  1716. flag = true;
  1717. num4 = -num4;
  1718. }
  1719. if (num4 > 0.999999) {
  1720. num3 = 1 - num;
  1721. num2 = flag ? -num : num;
  1722. }
  1723. else {
  1724. var num5 = Math.acos(num4);
  1725. var num6 = (1.0 / Math.sin(num5));
  1726. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1727. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1728. }
  1729. 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));
  1730. };
  1731. return Quaternion;
  1732. }());
  1733. BABYLON.Quaternion = Quaternion;
  1734. var Matrix = (function () {
  1735. function Matrix() {
  1736. this.m = new Float32Array(16);
  1737. }
  1738. // Properties
  1739. Matrix.prototype.isIdentity = function () {
  1740. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1741. return false;
  1742. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1743. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1744. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1745. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1746. return false;
  1747. return true;
  1748. };
  1749. Matrix.prototype.determinant = function () {
  1750. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1751. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1752. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1753. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1754. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1755. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1756. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1757. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1758. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1759. };
  1760. // Methods
  1761. Matrix.prototype.toArray = function () {
  1762. return this.m;
  1763. };
  1764. Matrix.prototype.asArray = function () {
  1765. return this.toArray();
  1766. };
  1767. Matrix.prototype.invert = function () {
  1768. this.invertToRef(this);
  1769. return this;
  1770. };
  1771. Matrix.prototype.reset = function () {
  1772. for (var index = 0; index < 16; index++) {
  1773. this.m[index] = 0;
  1774. }
  1775. return this;
  1776. };
  1777. Matrix.prototype.add = function (other) {
  1778. var result = new Matrix();
  1779. this.addToRef(other, result);
  1780. return result;
  1781. };
  1782. Matrix.prototype.addToRef = function (other, result) {
  1783. for (var index = 0; index < 16; index++) {
  1784. result.m[index] = this.m[index] + other.m[index];
  1785. }
  1786. return this;
  1787. };
  1788. Matrix.prototype.addToSelf = function (other) {
  1789. for (var index = 0; index < 16; index++) {
  1790. this.m[index] += other.m[index];
  1791. }
  1792. return this;
  1793. };
  1794. Matrix.prototype.invertToRef = function (other) {
  1795. var l1 = this.m[0];
  1796. var l2 = this.m[1];
  1797. var l3 = this.m[2];
  1798. var l4 = this.m[3];
  1799. var l5 = this.m[4];
  1800. var l6 = this.m[5];
  1801. var l7 = this.m[6];
  1802. var l8 = this.m[7];
  1803. var l9 = this.m[8];
  1804. var l10 = this.m[9];
  1805. var l11 = this.m[10];
  1806. var l12 = this.m[11];
  1807. var l13 = this.m[12];
  1808. var l14 = this.m[13];
  1809. var l15 = this.m[14];
  1810. var l16 = this.m[15];
  1811. var l17 = (l11 * l16) - (l12 * l15);
  1812. var l18 = (l10 * l16) - (l12 * l14);
  1813. var l19 = (l10 * l15) - (l11 * l14);
  1814. var l20 = (l9 * l16) - (l12 * l13);
  1815. var l21 = (l9 * l15) - (l11 * l13);
  1816. var l22 = (l9 * l14) - (l10 * l13);
  1817. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1818. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1819. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1820. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1821. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1822. var l28 = (l7 * l16) - (l8 * l15);
  1823. var l29 = (l6 * l16) - (l8 * l14);
  1824. var l30 = (l6 * l15) - (l7 * l14);
  1825. var l31 = (l5 * l16) - (l8 * l13);
  1826. var l32 = (l5 * l15) - (l7 * l13);
  1827. var l33 = (l5 * l14) - (l6 * l13);
  1828. var l34 = (l7 * l12) - (l8 * l11);
  1829. var l35 = (l6 * l12) - (l8 * l10);
  1830. var l36 = (l6 * l11) - (l7 * l10);
  1831. var l37 = (l5 * l12) - (l8 * l9);
  1832. var l38 = (l5 * l11) - (l7 * l9);
  1833. var l39 = (l5 * l10) - (l6 * l9);
  1834. other.m[0] = l23 * l27;
  1835. other.m[4] = l24 * l27;
  1836. other.m[8] = l25 * l27;
  1837. other.m[12] = l26 * l27;
  1838. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1839. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1840. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1841. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1842. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1843. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1844. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1845. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1846. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1847. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1848. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1849. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1850. return this;
  1851. };
  1852. Matrix.prototype.setTranslation = function (vector3) {
  1853. this.m[12] = vector3.x;
  1854. this.m[13] = vector3.y;
  1855. this.m[14] = vector3.z;
  1856. return this;
  1857. };
  1858. Matrix.prototype.getTranslation = function () {
  1859. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1860. };
  1861. Matrix.prototype.multiply = function (other) {
  1862. var result = new Matrix();
  1863. this.multiplyToRef(other, result);
  1864. return result;
  1865. };
  1866. Matrix.prototype.copyFrom = function (other) {
  1867. for (var index = 0; index < 16; index++) {
  1868. this.m[index] = other.m[index];
  1869. }
  1870. return this;
  1871. };
  1872. Matrix.prototype.copyToArray = function (array, offset) {
  1873. if (offset === void 0) { offset = 0; }
  1874. for (var index = 0; index < 16; index++) {
  1875. array[offset + index] = this.m[index];
  1876. }
  1877. return this;
  1878. };
  1879. Matrix.prototype.multiplyToRef = function (other, result) {
  1880. this.multiplyToArray(other, result.m, 0);
  1881. return this;
  1882. };
  1883. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1884. var tm0 = this.m[0];
  1885. var tm1 = this.m[1];
  1886. var tm2 = this.m[2];
  1887. var tm3 = this.m[3];
  1888. var tm4 = this.m[4];
  1889. var tm5 = this.m[5];
  1890. var tm6 = this.m[6];
  1891. var tm7 = this.m[7];
  1892. var tm8 = this.m[8];
  1893. var tm9 = this.m[9];
  1894. var tm10 = this.m[10];
  1895. var tm11 = this.m[11];
  1896. var tm12 = this.m[12];
  1897. var tm13 = this.m[13];
  1898. var tm14 = this.m[14];
  1899. var tm15 = this.m[15];
  1900. var om0 = other.m[0];
  1901. var om1 = other.m[1];
  1902. var om2 = other.m[2];
  1903. var om3 = other.m[3];
  1904. var om4 = other.m[4];
  1905. var om5 = other.m[5];
  1906. var om6 = other.m[6];
  1907. var om7 = other.m[7];
  1908. var om8 = other.m[8];
  1909. var om9 = other.m[9];
  1910. var om10 = other.m[10];
  1911. var om11 = other.m[11];
  1912. var om12 = other.m[12];
  1913. var om13 = other.m[13];
  1914. var om14 = other.m[14];
  1915. var om15 = other.m[15];
  1916. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1917. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1918. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1919. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1920. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1921. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1922. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1923. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1924. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1925. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1926. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1927. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1928. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1929. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1930. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1931. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1932. return this;
  1933. };
  1934. Matrix.prototype.equals = function (value) {
  1935. return value &&
  1936. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1937. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1938. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1939. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1940. };
  1941. Matrix.prototype.clone = function () {
  1942. 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]);
  1943. };
  1944. Matrix.prototype.getClassName = function () {
  1945. return "Matrix";
  1946. };
  1947. Matrix.prototype.getHashCode = function () {
  1948. var hash = this.m[0] || 0;
  1949. for (var i = 1; i < 16; i++) {
  1950. hash = (hash * 397) ^ (this.m[i] || 0);
  1951. }
  1952. return hash;
  1953. };
  1954. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1955. translation.x = this.m[12];
  1956. translation.y = this.m[13];
  1957. translation.z = this.m[14];
  1958. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1959. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1960. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1961. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1962. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1963. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1964. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1965. rotation.x = 0;
  1966. rotation.y = 0;
  1967. rotation.z = 0;
  1968. rotation.w = 1;
  1969. return false;
  1970. }
  1971. 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]);
  1972. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  1973. return true;
  1974. };
  1975. // Statics
  1976. Matrix.FromArray = function (array, offset) {
  1977. var result = new Matrix();
  1978. if (!offset) {
  1979. offset = 0;
  1980. }
  1981. Matrix.FromArrayToRef(array, offset, result);
  1982. return result;
  1983. };
  1984. Matrix.FromArrayToRef = function (array, offset, result) {
  1985. for (var index = 0; index < 16; index++) {
  1986. result.m[index] = array[index + offset];
  1987. }
  1988. };
  1989. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1990. for (var index = 0; index < 16; index++) {
  1991. result.m[index] = array[index + offset] * scale;
  1992. }
  1993. };
  1994. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1995. result.m[0] = initialM11;
  1996. result.m[1] = initialM12;
  1997. result.m[2] = initialM13;
  1998. result.m[3] = initialM14;
  1999. result.m[4] = initialM21;
  2000. result.m[5] = initialM22;
  2001. result.m[6] = initialM23;
  2002. result.m[7] = initialM24;
  2003. result.m[8] = initialM31;
  2004. result.m[9] = initialM32;
  2005. result.m[10] = initialM33;
  2006. result.m[11] = initialM34;
  2007. result.m[12] = initialM41;
  2008. result.m[13] = initialM42;
  2009. result.m[14] = initialM43;
  2010. result.m[15] = initialM44;
  2011. };
  2012. Matrix.prototype.getRow = function (index) {
  2013. if (index < 0 || index > 3) {
  2014. return null;
  2015. }
  2016. var i = index * 4;
  2017. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2018. };
  2019. Matrix.prototype.setRow = function (index, row) {
  2020. if (index < 0 || index > 3) {
  2021. return this;
  2022. }
  2023. var i = index * 4;
  2024. this.m[i + 0] = row.x;
  2025. this.m[i + 1] = row.y;
  2026. this.m[i + 2] = row.z;
  2027. this.m[i + 3] = row.w;
  2028. return this;
  2029. };
  2030. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2031. var result = new Matrix();
  2032. result.m[0] = initialM11;
  2033. result.m[1] = initialM12;
  2034. result.m[2] = initialM13;
  2035. result.m[3] = initialM14;
  2036. result.m[4] = initialM21;
  2037. result.m[5] = initialM22;
  2038. result.m[6] = initialM23;
  2039. result.m[7] = initialM24;
  2040. result.m[8] = initialM31;
  2041. result.m[9] = initialM32;
  2042. result.m[10] = initialM33;
  2043. result.m[11] = initialM34;
  2044. result.m[12] = initialM41;
  2045. result.m[13] = initialM42;
  2046. result.m[14] = initialM43;
  2047. result.m[15] = initialM44;
  2048. return result;
  2049. };
  2050. Matrix.Compose = function (scale, rotation, translation) {
  2051. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2052. var rotationMatrix = Matrix.Identity();
  2053. rotation.toRotationMatrix(rotationMatrix);
  2054. result = result.multiply(rotationMatrix);
  2055. result.setTranslation(translation);
  2056. return result;
  2057. };
  2058. Matrix.Identity = function () {
  2059. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2060. };
  2061. Matrix.IdentityToRef = function (result) {
  2062. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2063. };
  2064. Matrix.Zero = function () {
  2065. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2066. };
  2067. Matrix.RotationX = function (angle) {
  2068. var result = new Matrix();
  2069. Matrix.RotationXToRef(angle, result);
  2070. return result;
  2071. };
  2072. Matrix.Invert = function (source) {
  2073. var result = new Matrix();
  2074. source.invertToRef(result);
  2075. return result;
  2076. };
  2077. Matrix.RotationXToRef = function (angle, result) {
  2078. var s = Math.sin(angle);
  2079. var c = Math.cos(angle);
  2080. result.m[0] = 1.0;
  2081. result.m[15] = 1.0;
  2082. result.m[5] = c;
  2083. result.m[10] = c;
  2084. result.m[9] = -s;
  2085. result.m[6] = s;
  2086. result.m[1] = 0;
  2087. result.m[2] = 0;
  2088. result.m[3] = 0;
  2089. result.m[4] = 0;
  2090. result.m[7] = 0;
  2091. result.m[8] = 0;
  2092. result.m[11] = 0;
  2093. result.m[12] = 0;
  2094. result.m[13] = 0;
  2095. result.m[14] = 0;
  2096. };
  2097. Matrix.RotationY = function (angle) {
  2098. var result = new Matrix();
  2099. Matrix.RotationYToRef(angle, result);
  2100. return result;
  2101. };
  2102. Matrix.RotationYToRef = function (angle, result) {
  2103. var s = Math.sin(angle);
  2104. var c = Math.cos(angle);
  2105. result.m[5] = 1.0;
  2106. result.m[15] = 1.0;
  2107. result.m[0] = c;
  2108. result.m[2] = -s;
  2109. result.m[8] = s;
  2110. result.m[10] = c;
  2111. result.m[1] = 0;
  2112. result.m[3] = 0;
  2113. result.m[4] = 0;
  2114. result.m[6] = 0;
  2115. result.m[7] = 0;
  2116. result.m[9] = 0;
  2117. result.m[11] = 0;
  2118. result.m[12] = 0;
  2119. result.m[13] = 0;
  2120. result.m[14] = 0;
  2121. };
  2122. Matrix.RotationZ = function (angle) {
  2123. var result = new Matrix();
  2124. Matrix.RotationZToRef(angle, result);
  2125. return result;
  2126. };
  2127. Matrix.RotationZToRef = function (angle, result) {
  2128. var s = Math.sin(angle);
  2129. var c = Math.cos(angle);
  2130. result.m[10] = 1.0;
  2131. result.m[15] = 1.0;
  2132. result.m[0] = c;
  2133. result.m[1] = s;
  2134. result.m[4] = -s;
  2135. result.m[5] = c;
  2136. result.m[2] = 0;
  2137. result.m[3] = 0;
  2138. result.m[6] = 0;
  2139. result.m[7] = 0;
  2140. result.m[8] = 0;
  2141. result.m[9] = 0;
  2142. result.m[11] = 0;
  2143. result.m[12] = 0;
  2144. result.m[13] = 0;
  2145. result.m[14] = 0;
  2146. };
  2147. Matrix.RotationAxis = function (axis, angle) {
  2148. var result = Matrix.Zero();
  2149. Matrix.RotationAxisToRef(axis, angle, result);
  2150. return result;
  2151. };
  2152. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2153. var s = Math.sin(-angle);
  2154. var c = Math.cos(-angle);
  2155. var c1 = 1 - c;
  2156. axis.normalize();
  2157. result.m[0] = (axis.x * axis.x) * c1 + c;
  2158. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2159. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2160. result.m[3] = 0.0;
  2161. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2162. result.m[5] = (axis.y * axis.y) * c1 + c;
  2163. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2164. result.m[7] = 0.0;
  2165. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2166. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2167. result.m[10] = (axis.z * axis.z) * c1 + c;
  2168. result.m[11] = 0.0;
  2169. result.m[15] = 1.0;
  2170. };
  2171. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2172. var result = new Matrix();
  2173. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2174. return result;
  2175. };
  2176. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2177. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2178. this._tempQuaternion.toRotationMatrix(result);
  2179. };
  2180. Matrix.Scaling = function (x, y, z) {
  2181. var result = Matrix.Zero();
  2182. Matrix.ScalingToRef(x, y, z, result);
  2183. return result;
  2184. };
  2185. Matrix.ScalingToRef = function (x, y, z, result) {
  2186. result.m[0] = x;
  2187. result.m[1] = 0;
  2188. result.m[2] = 0;
  2189. result.m[3] = 0;
  2190. result.m[4] = 0;
  2191. result.m[5] = y;
  2192. result.m[6] = 0;
  2193. result.m[7] = 0;
  2194. result.m[8] = 0;
  2195. result.m[9] = 0;
  2196. result.m[10] = z;
  2197. result.m[11] = 0;
  2198. result.m[12] = 0;
  2199. result.m[13] = 0;
  2200. result.m[14] = 0;
  2201. result.m[15] = 1.0;
  2202. };
  2203. Matrix.Translation = function (x, y, z) {
  2204. var result = Matrix.Identity();
  2205. Matrix.TranslationToRef(x, y, z, result);
  2206. return result;
  2207. };
  2208. Matrix.TranslationToRef = function (x, y, z, result) {
  2209. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2210. };
  2211. Matrix.Lerp = function (startValue, endValue, gradient) {
  2212. var result = Matrix.Zero();
  2213. for (var index = 0; index < 16; index++) {
  2214. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2215. }
  2216. return result;
  2217. };
  2218. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2219. var startScale = new Vector3(0, 0, 0);
  2220. var startRotation = new Quaternion();
  2221. var startTranslation = new Vector3(0, 0, 0);
  2222. startValue.decompose(startScale, startRotation, startTranslation);
  2223. var endScale = new Vector3(0, 0, 0);
  2224. var endRotation = new Quaternion();
  2225. var endTranslation = new Vector3(0, 0, 0);
  2226. endValue.decompose(endScale, endRotation, endTranslation);
  2227. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2228. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2229. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2230. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2231. };
  2232. Matrix.LookAtLH = function (eye, target, up) {
  2233. var result = Matrix.Zero();
  2234. Matrix.LookAtLHToRef(eye, target, up, result);
  2235. return result;
  2236. };
  2237. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2238. // Z axis
  2239. target.subtractToRef(eye, this._zAxis);
  2240. this._zAxis.normalize();
  2241. // X axis
  2242. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2243. if (this._xAxis.lengthSquared() === 0) {
  2244. this._xAxis.x = 1.0;
  2245. }
  2246. else {
  2247. this._xAxis.normalize();
  2248. }
  2249. // Y axis
  2250. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2251. this._yAxis.normalize();
  2252. // Eye angles
  2253. var ex = -Vector3.Dot(this._xAxis, eye);
  2254. var ey = -Vector3.Dot(this._yAxis, eye);
  2255. var ez = -Vector3.Dot(this._zAxis, eye);
  2256. 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);
  2257. };
  2258. Matrix.LookAtRH = function (eye, target, up) {
  2259. var result = Matrix.Zero();
  2260. Matrix.LookAtRHToRef(eye, target, up, result);
  2261. return result;
  2262. };
  2263. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2264. // Z axis
  2265. eye.subtractToRef(target, this._zAxis);
  2266. this._zAxis.normalize();
  2267. // X axis
  2268. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2269. if (this._xAxis.lengthSquared() === 0) {
  2270. this._xAxis.x = 1.0;
  2271. }
  2272. else {
  2273. this._xAxis.normalize();
  2274. }
  2275. // Y axis
  2276. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2277. this._yAxis.normalize();
  2278. // Eye angles
  2279. var ex = -Vector3.Dot(this._xAxis, eye);
  2280. var ey = -Vector3.Dot(this._yAxis, eye);
  2281. var ez = -Vector3.Dot(this._zAxis, eye);
  2282. 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);
  2283. };
  2284. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2285. var matrix = Matrix.Zero();
  2286. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2287. return matrix;
  2288. };
  2289. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2290. var hw = 2.0 / width;
  2291. var hh = 2.0 / height;
  2292. var id = 1.0 / (zfar - znear);
  2293. var nid = znear / (znear - zfar);
  2294. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2295. };
  2296. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2297. var matrix = Matrix.Zero();
  2298. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2299. return matrix;
  2300. };
  2301. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2302. result.m[0] = 2.0 / (right - left);
  2303. result.m[1] = result.m[2] = result.m[3] = 0;
  2304. result.m[5] = 2.0 / (top - bottom);
  2305. result.m[4] = result.m[6] = result.m[7] = 0;
  2306. result.m[10] = 1.0 / (zfar - znear);
  2307. result.m[8] = result.m[9] = result.m[11] = 0;
  2308. result.m[12] = (left + right) / (left - right);
  2309. result.m[13] = (top + bottom) / (bottom - top);
  2310. result.m[14] = -znear / (zfar - znear);
  2311. result.m[15] = 1.0;
  2312. };
  2313. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2314. var matrix = Matrix.Zero();
  2315. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2316. return matrix;
  2317. };
  2318. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2319. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2320. result.m[10] *= -1.0;
  2321. };
  2322. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2323. var matrix = Matrix.Zero();
  2324. matrix.m[0] = (2.0 * znear) / width;
  2325. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2326. matrix.m[5] = (2.0 * znear) / height;
  2327. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2328. matrix.m[10] = -zfar / (znear - zfar);
  2329. matrix.m[8] = matrix.m[9] = 0.0;
  2330. matrix.m[11] = 1.0;
  2331. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2332. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2333. return matrix;
  2334. };
  2335. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2336. var matrix = Matrix.Zero();
  2337. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2338. return matrix;
  2339. };
  2340. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2341. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2342. var tan = 1.0 / (Math.tan(fov * 0.5));
  2343. if (isVerticalFovFixed) {
  2344. result.m[0] = tan / aspect;
  2345. }
  2346. else {
  2347. result.m[0] = tan;
  2348. }
  2349. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2350. if (isVerticalFovFixed) {
  2351. result.m[5] = tan;
  2352. }
  2353. else {
  2354. result.m[5] = tan * aspect;
  2355. }
  2356. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2357. result.m[8] = result.m[9] = 0.0;
  2358. result.m[10] = zfar / (zfar - znear);
  2359. result.m[11] = 1.0;
  2360. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2361. result.m[14] = -(znear * zfar) / (zfar - znear);
  2362. };
  2363. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2364. var matrix = Matrix.Zero();
  2365. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2366. return matrix;
  2367. };
  2368. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2369. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2370. var tan = 1.0 / (Math.tan(fov * 0.5));
  2371. if (isVerticalFovFixed) {
  2372. result.m[0] = tan / aspect;
  2373. }
  2374. else {
  2375. result.m[0] = tan;
  2376. }
  2377. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2378. if (isVerticalFovFixed) {
  2379. result.m[5] = tan;
  2380. }
  2381. else {
  2382. result.m[5] = tan * aspect;
  2383. }
  2384. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2385. result.m[8] = result.m[9] = 0.0;
  2386. result.m[10] = zfar / (znear - zfar);
  2387. result.m[11] = -1.0;
  2388. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2389. result.m[14] = (znear * zfar) / (znear - zfar);
  2390. };
  2391. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2392. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2393. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2394. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2395. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2396. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2397. var xScale = 2.0 / (leftTan + rightTan);
  2398. var yScale = 2.0 / (upTan + downTan);
  2399. result.m[0] = xScale;
  2400. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2401. result.m[5] = yScale;
  2402. result.m[6] = result.m[7] = 0.0;
  2403. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2404. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2405. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2406. result.m[10] = -zfar / (znear - zfar);
  2407. result.m[11] = 1.0;
  2408. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2409. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2410. result.m[14] = (znear * zfar) / (znear - zfar);
  2411. };
  2412. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2413. var cw = viewport.width;
  2414. var ch = viewport.height;
  2415. var cx = viewport.x;
  2416. var cy = viewport.y;
  2417. 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);
  2418. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2419. };
  2420. Matrix.GetAsMatrix2x2 = function (matrix) {
  2421. return new Float32Array([
  2422. matrix.m[0], matrix.m[1],
  2423. matrix.m[4], matrix.m[5]
  2424. ]);
  2425. };
  2426. Matrix.GetAsMatrix3x3 = function (matrix) {
  2427. return new Float32Array([
  2428. matrix.m[0], matrix.m[1], matrix.m[2],
  2429. matrix.m[4], matrix.m[5], matrix.m[6],
  2430. matrix.m[8], matrix.m[9], matrix.m[10]
  2431. ]);
  2432. };
  2433. Matrix.Transpose = function (matrix) {
  2434. var result = new Matrix();
  2435. result.m[0] = matrix.m[0];
  2436. result.m[1] = matrix.m[4];
  2437. result.m[2] = matrix.m[8];
  2438. result.m[3] = matrix.m[12];
  2439. result.m[4] = matrix.m[1];
  2440. result.m[5] = matrix.m[5];
  2441. result.m[6] = matrix.m[9];
  2442. result.m[7] = matrix.m[13];
  2443. result.m[8] = matrix.m[2];
  2444. result.m[9] = matrix.m[6];
  2445. result.m[10] = matrix.m[10];
  2446. result.m[11] = matrix.m[14];
  2447. result.m[12] = matrix.m[3];
  2448. result.m[13] = matrix.m[7];
  2449. result.m[14] = matrix.m[11];
  2450. result.m[15] = matrix.m[15];
  2451. return result;
  2452. };
  2453. Matrix.Reflection = function (plane) {
  2454. var matrix = new Matrix();
  2455. Matrix.ReflectionToRef(plane, matrix);
  2456. return matrix;
  2457. };
  2458. Matrix.ReflectionToRef = function (plane, result) {
  2459. plane.normalize();
  2460. var x = plane.normal.x;
  2461. var y = plane.normal.y;
  2462. var z = plane.normal.z;
  2463. var temp = -2 * x;
  2464. var temp2 = -2 * y;
  2465. var temp3 = -2 * z;
  2466. result.m[0] = (temp * x) + 1;
  2467. result.m[1] = temp2 * x;
  2468. result.m[2] = temp3 * x;
  2469. result.m[3] = 0.0;
  2470. result.m[4] = temp * y;
  2471. result.m[5] = (temp2 * y) + 1;
  2472. result.m[6] = temp3 * y;
  2473. result.m[7] = 0.0;
  2474. result.m[8] = temp * z;
  2475. result.m[9] = temp2 * z;
  2476. result.m[10] = (temp3 * z) + 1;
  2477. result.m[11] = 0.0;
  2478. result.m[12] = temp * plane.d;
  2479. result.m[13] = temp2 * plane.d;
  2480. result.m[14] = temp3 * plane.d;
  2481. result.m[15] = 1.0;
  2482. };
  2483. Matrix._tempQuaternion = new Quaternion();
  2484. Matrix._xAxis = Vector3.Zero();
  2485. Matrix._yAxis = Vector3.Zero();
  2486. Matrix._zAxis = Vector3.Zero();
  2487. return Matrix;
  2488. }());
  2489. BABYLON.Matrix = Matrix;
  2490. var Plane = (function () {
  2491. function Plane(a, b, c, d) {
  2492. this.normal = new Vector3(a, b, c);
  2493. this.d = d;
  2494. }
  2495. Plane.prototype.asArray = function () {
  2496. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2497. };
  2498. // Methods
  2499. Plane.prototype.clone = function () {
  2500. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2501. };
  2502. Plane.prototype.getClassName = function () {
  2503. return "Plane";
  2504. };
  2505. Plane.prototype.getHashCode = function () {
  2506. var hash = this.normal.getHashCode();
  2507. hash = (hash * 397) ^ (this.d || 0);
  2508. return hash;
  2509. };
  2510. Plane.prototype.normalize = function () {
  2511. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2512. var magnitude = 0;
  2513. if (norm !== 0) {
  2514. magnitude = 1.0 / norm;
  2515. }
  2516. this.normal.x *= magnitude;
  2517. this.normal.y *= magnitude;
  2518. this.normal.z *= magnitude;
  2519. this.d *= magnitude;
  2520. return this;
  2521. };
  2522. Plane.prototype.transform = function (transformation) {
  2523. var transposedMatrix = Matrix.Transpose(transformation);
  2524. var x = this.normal.x;
  2525. var y = this.normal.y;
  2526. var z = this.normal.z;
  2527. var d = this.d;
  2528. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2529. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2530. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2531. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2532. return new Plane(normalX, normalY, normalZ, finalD);
  2533. };
  2534. Plane.prototype.dotCoordinate = function (point) {
  2535. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2536. };
  2537. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2538. var x1 = point2.x - point1.x;
  2539. var y1 = point2.y - point1.y;
  2540. var z1 = point2.z - point1.z;
  2541. var x2 = point3.x - point1.x;
  2542. var y2 = point3.y - point1.y;
  2543. var z2 = point3.z - point1.z;
  2544. var yz = (y1 * z2) - (z1 * y2);
  2545. var xz = (z1 * x2) - (x1 * z2);
  2546. var xy = (x1 * y2) - (y1 * x2);
  2547. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2548. var invPyth;
  2549. if (pyth !== 0) {
  2550. invPyth = 1.0 / pyth;
  2551. }
  2552. else {
  2553. invPyth = 0;
  2554. }
  2555. this.normal.x = yz * invPyth;
  2556. this.normal.y = xz * invPyth;
  2557. this.normal.z = xy * invPyth;
  2558. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2559. return this;
  2560. };
  2561. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2562. var dot = Vector3.Dot(this.normal, direction);
  2563. return (dot <= epsilon);
  2564. };
  2565. Plane.prototype.signedDistanceTo = function (point) {
  2566. return Vector3.Dot(point, this.normal) + this.d;
  2567. };
  2568. // Statics
  2569. Plane.FromArray = function (array) {
  2570. return new Plane(array[0], array[1], array[2], array[3]);
  2571. };
  2572. Plane.FromPoints = function (point1, point2, point3) {
  2573. var result = new Plane(0, 0, 0, 0);
  2574. result.copyFromPoints(point1, point2, point3);
  2575. return result;
  2576. };
  2577. Plane.FromPositionAndNormal = function (origin, normal) {
  2578. var result = new Plane(0, 0, 0, 0);
  2579. normal.normalize();
  2580. result.normal = normal;
  2581. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2582. return result;
  2583. };
  2584. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2585. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2586. return Vector3.Dot(point, normal) + d;
  2587. };
  2588. return Plane;
  2589. }());
  2590. BABYLON.Plane = Plane;
  2591. var Viewport = (function () {
  2592. function Viewport(x, y, width, height) {
  2593. this.x = x;
  2594. this.y = y;
  2595. this.width = width;
  2596. this.height = height;
  2597. }
  2598. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2599. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2600. };
  2601. return Viewport;
  2602. }());
  2603. BABYLON.Viewport = Viewport;
  2604. var Frustum = (function () {
  2605. function Frustum() {
  2606. }
  2607. Frustum.GetPlanes = function (transform) {
  2608. var frustumPlanes = [];
  2609. for (var index = 0; index < 6; index++) {
  2610. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2611. }
  2612. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2613. return frustumPlanes;
  2614. };
  2615. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2616. // Near
  2617. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2618. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2619. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2620. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2621. frustumPlanes[0].normalize();
  2622. // Far
  2623. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2624. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2625. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2626. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2627. frustumPlanes[1].normalize();
  2628. // Left
  2629. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2630. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2631. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2632. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2633. frustumPlanes[2].normalize();
  2634. // Right
  2635. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2636. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2637. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2638. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2639. frustumPlanes[3].normalize();
  2640. // Top
  2641. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2642. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2643. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2644. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2645. frustumPlanes[4].normalize();
  2646. // Bottom
  2647. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2648. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2649. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2650. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2651. frustumPlanes[5].normalize();
  2652. };
  2653. return Frustum;
  2654. }());
  2655. BABYLON.Frustum = Frustum;
  2656. (function (Space) {
  2657. Space[Space["LOCAL"] = 0] = "LOCAL";
  2658. Space[Space["WORLD"] = 1] = "WORLD";
  2659. })(BABYLON.Space || (BABYLON.Space = {}));
  2660. var Space = BABYLON.Space;
  2661. var Axis = (function () {
  2662. function Axis() {
  2663. }
  2664. Axis.X = new Vector3(1, 0, 0);
  2665. Axis.Y = new Vector3(0, 1, 0);
  2666. Axis.Z = new Vector3(0, 0, 1);
  2667. return Axis;
  2668. }());
  2669. BABYLON.Axis = Axis;
  2670. ;
  2671. var BezierCurve = (function () {
  2672. function BezierCurve() {
  2673. }
  2674. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2675. // Extract X (which is equal to time here)
  2676. var f0 = 1 - 3 * x2 + 3 * x1;
  2677. var f1 = 3 * x2 - 6 * x1;
  2678. var f2 = 3 * x1;
  2679. var refinedT = t;
  2680. for (var i = 0; i < 5; i++) {
  2681. var refinedT2 = refinedT * refinedT;
  2682. var refinedT3 = refinedT2 * refinedT;
  2683. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2684. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2685. refinedT -= (x - t) * slope;
  2686. refinedT = Math.min(1, Math.max(0, refinedT));
  2687. }
  2688. // Resolve cubic bezier for the given x
  2689. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2690. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2691. Math.pow(refinedT, 3);
  2692. };
  2693. return BezierCurve;
  2694. }());
  2695. BABYLON.BezierCurve = BezierCurve;
  2696. (function (Orientation) {
  2697. Orientation[Orientation["CW"] = 0] = "CW";
  2698. Orientation[Orientation["CCW"] = 1] = "CCW";
  2699. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2700. var Orientation = BABYLON.Orientation;
  2701. var Angle = (function () {
  2702. function Angle(radians) {
  2703. var _this = this;
  2704. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2705. this.radians = function () { return _this._radians; };
  2706. this._radians = radians;
  2707. if (this._radians < 0)
  2708. this._radians += (2 * Math.PI);
  2709. }
  2710. Angle.BetweenTwoPoints = function (a, b) {
  2711. var delta = b.subtract(a);
  2712. var theta = Math.atan2(delta.y, delta.x);
  2713. return new Angle(theta);
  2714. };
  2715. Angle.FromRadians = function (radians) {
  2716. return new Angle(radians);
  2717. };
  2718. Angle.FromDegrees = function (degrees) {
  2719. return new Angle(degrees * Math.PI / 180);
  2720. };
  2721. return Angle;
  2722. }());
  2723. BABYLON.Angle = Angle;
  2724. var Arc2 = (function () {
  2725. function Arc2(startPoint, midPoint, endPoint) {
  2726. this.startPoint = startPoint;
  2727. this.midPoint = midPoint;
  2728. this.endPoint = endPoint;
  2729. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2730. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2731. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2732. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2733. 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);
  2734. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2735. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2736. var a1 = this.startAngle.degrees();
  2737. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2738. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2739. // angles correction
  2740. if (a2 - a1 > +180.0)
  2741. a2 -= 360.0;
  2742. if (a2 - a1 < -180.0)
  2743. a2 += 360.0;
  2744. if (a3 - a2 > +180.0)
  2745. a3 -= 360.0;
  2746. if (a3 - a2 < -180.0)
  2747. a3 += 360.0;
  2748. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2749. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2750. }
  2751. return Arc2;
  2752. }());
  2753. BABYLON.Arc2 = Arc2;
  2754. var Path2 = (function () {
  2755. function Path2(x, y) {
  2756. this._points = new Array();
  2757. this._length = 0;
  2758. this.closed = false;
  2759. this._points.push(new Vector2(x, y));
  2760. }
  2761. Path2.prototype.addLineTo = function (x, y) {
  2762. if (closed) {
  2763. //Tools.Error("cannot add lines to closed paths");
  2764. return this;
  2765. }
  2766. var newPoint = new Vector2(x, y);
  2767. var previousPoint = this._points[this._points.length - 1];
  2768. this._points.push(newPoint);
  2769. this._length += newPoint.subtract(previousPoint).length();
  2770. return this;
  2771. };
  2772. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2773. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2774. if (closed) {
  2775. //Tools.Error("cannot add arcs to closed paths");
  2776. return this;
  2777. }
  2778. var startPoint = this._points[this._points.length - 1];
  2779. var midPoint = new Vector2(midX, midY);
  2780. var endPoint = new Vector2(endX, endY);
  2781. var arc = new Arc2(startPoint, midPoint, endPoint);
  2782. var increment = arc.angle.radians() / numberOfSegments;
  2783. if (arc.orientation === Orientation.CW)
  2784. increment *= -1;
  2785. var currentAngle = arc.startAngle.radians() + increment;
  2786. for (var i = 0; i < numberOfSegments; i++) {
  2787. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2788. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2789. this.addLineTo(x, y);
  2790. currentAngle += increment;
  2791. }
  2792. return this;
  2793. };
  2794. Path2.prototype.close = function () {
  2795. this.closed = true;
  2796. return this;
  2797. };
  2798. Path2.prototype.length = function () {
  2799. var result = this._length;
  2800. if (!this.closed) {
  2801. var lastPoint = this._points[this._points.length - 1];
  2802. var firstPoint = this._points[0];
  2803. result += (firstPoint.subtract(lastPoint).length());
  2804. }
  2805. return result;
  2806. };
  2807. Path2.prototype.getPoints = function () {
  2808. return this._points;
  2809. };
  2810. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2811. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2812. //Tools.Error("normalized length position should be between 0 and 1.");
  2813. return Vector2.Zero();
  2814. }
  2815. var lengthPosition = normalizedLengthPosition * this.length();
  2816. var previousOffset = 0;
  2817. for (var i = 0; i < this._points.length; i++) {
  2818. var j = (i + 1) % this._points.length;
  2819. var a = this._points[i];
  2820. var b = this._points[j];
  2821. var bToA = b.subtract(a);
  2822. var nextOffset = (bToA.length() + previousOffset);
  2823. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2824. var dir = bToA.normalize();
  2825. var localOffset = lengthPosition - previousOffset;
  2826. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2827. }
  2828. previousOffset = nextOffset;
  2829. }
  2830. //Tools.Error("internal error");
  2831. return Vector2.Zero();
  2832. };
  2833. Path2.StartingAt = function (x, y) {
  2834. return new Path2(x, y);
  2835. };
  2836. return Path2;
  2837. }());
  2838. BABYLON.Path2 = Path2;
  2839. var Path3D = (function () {
  2840. /**
  2841. * new Path3D(path, normal, raw)
  2842. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2843. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2844. * path : an array of Vector3, the curve axis of the Path3D
  2845. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2846. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2847. */
  2848. function Path3D(path, firstNormal, raw) {
  2849. this.path = path;
  2850. this._curve = new Array();
  2851. this._distances = new Array();
  2852. this._tangents = new Array();
  2853. this._normals = new Array();
  2854. this._binormals = new Array();
  2855. for (var p = 0; p < path.length; p++) {
  2856. this._curve[p] = path[p].clone(); // hard copy
  2857. }
  2858. this._raw = raw || false;
  2859. this._compute(firstNormal);
  2860. }
  2861. /**
  2862. * Returns the Path3D array of successive Vector3 designing its curve.
  2863. */
  2864. Path3D.prototype.getCurve = function () {
  2865. return this._curve;
  2866. };
  2867. /**
  2868. * Returns an array populated with tangent vectors on each Path3D curve point.
  2869. */
  2870. Path3D.prototype.getTangents = function () {
  2871. return this._tangents;
  2872. };
  2873. /**
  2874. * Returns an array populated with normal vectors on each Path3D curve point.
  2875. */
  2876. Path3D.prototype.getNormals = function () {
  2877. return this._normals;
  2878. };
  2879. /**
  2880. * Returns an array populated with binormal vectors on each Path3D curve point.
  2881. */
  2882. Path3D.prototype.getBinormals = function () {
  2883. return this._binormals;
  2884. };
  2885. /**
  2886. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2887. */
  2888. Path3D.prototype.getDistances = function () {
  2889. return this._distances;
  2890. };
  2891. /**
  2892. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2893. * Returns the same object updated.
  2894. */
  2895. Path3D.prototype.update = function (path, firstNormal) {
  2896. for (var p = 0; p < path.length; p++) {
  2897. this._curve[p].x = path[p].x;
  2898. this._curve[p].y = path[p].y;
  2899. this._curve[p].z = path[p].z;
  2900. }
  2901. this._compute(firstNormal);
  2902. return this;
  2903. };
  2904. // private function compute() : computes tangents, normals and binormals
  2905. Path3D.prototype._compute = function (firstNormal) {
  2906. var l = this._curve.length;
  2907. // first and last tangents
  2908. this._tangents[0] = this._getFirstNonNullVector(0);
  2909. if (!this._raw) {
  2910. this._tangents[0].normalize();
  2911. }
  2912. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2913. if (!this._raw) {
  2914. this._tangents[l - 1].normalize();
  2915. }
  2916. // normals and binormals at first point : arbitrary vector with _normalVector()
  2917. var tg0 = this._tangents[0];
  2918. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2919. this._normals[0] = pp0;
  2920. if (!this._raw) {
  2921. this._normals[0].normalize();
  2922. }
  2923. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2924. if (!this._raw) {
  2925. this._binormals[0].normalize();
  2926. }
  2927. this._distances[0] = 0.0;
  2928. // normals and binormals : next points
  2929. var prev; // previous vector (segment)
  2930. var cur; // current vector (segment)
  2931. var curTang; // current tangent
  2932. // previous normal
  2933. var prevBinor; // previous binormal
  2934. for (var i = 1; i < l; i++) {
  2935. // tangents
  2936. prev = this._getLastNonNullVector(i);
  2937. if (i < l - 1) {
  2938. cur = this._getFirstNonNullVector(i);
  2939. this._tangents[i] = prev.add(cur);
  2940. this._tangents[i].normalize();
  2941. }
  2942. this._distances[i] = this._distances[i - 1] + prev.length();
  2943. // normals and binormals
  2944. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2945. curTang = this._tangents[i];
  2946. prevBinor = this._binormals[i - 1];
  2947. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2948. if (!this._raw) {
  2949. this._normals[i].normalize();
  2950. }
  2951. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2952. if (!this._raw) {
  2953. this._binormals[i].normalize();
  2954. }
  2955. }
  2956. };
  2957. // private function getFirstNonNullVector(index)
  2958. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2959. Path3D.prototype._getFirstNonNullVector = function (index) {
  2960. var i = 1;
  2961. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2962. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2963. i++;
  2964. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2965. }
  2966. return nNVector;
  2967. };
  2968. // private function getLastNonNullVector(index)
  2969. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2970. Path3D.prototype._getLastNonNullVector = function (index) {
  2971. var i = 1;
  2972. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2973. while (nLVector.length() === 0 && index > i + 1) {
  2974. i++;
  2975. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2976. }
  2977. return nLVector;
  2978. };
  2979. // private function normalVector(v0, vt, va) :
  2980. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2981. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2982. Path3D.prototype._normalVector = function (v0, vt, va) {
  2983. var normal0;
  2984. var tgl = vt.length();
  2985. if (tgl === 0.0) {
  2986. tgl = 1.0;
  2987. }
  2988. if (va === undefined || va === null) {
  2989. var point;
  2990. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  2991. point = new Vector3(0.0, -1.0, 0.0);
  2992. }
  2993. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  2994. point = new Vector3(1.0, 0.0, 0.0);
  2995. }
  2996. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  2997. point = new Vector3(0.0, 0.0, 1.0);
  2998. }
  2999. normal0 = Vector3.Cross(vt, point);
  3000. }
  3001. else {
  3002. normal0 = Vector3.Cross(vt, va);
  3003. Vector3.CrossToRef(normal0, vt, normal0);
  3004. }
  3005. normal0.normalize();
  3006. return normal0;
  3007. };
  3008. return Path3D;
  3009. }());
  3010. BABYLON.Path3D = Path3D;
  3011. var Curve3 = (function () {
  3012. /**
  3013. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3014. * A Curve3 is designed from a series of successive Vector3.
  3015. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3016. */
  3017. function Curve3(points) {
  3018. this._length = 0.0;
  3019. this._points = points;
  3020. this._length = this._computeLength(points);
  3021. }
  3022. /**
  3023. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3024. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3025. * @param v1 (Vector3) the control point
  3026. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3027. * @param nbPoints (integer) the wanted number of points in the curve
  3028. */
  3029. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3030. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3031. var bez = new Array();
  3032. var equation = function (t, val0, val1, val2) {
  3033. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3034. return res;
  3035. };
  3036. for (var i = 0; i <= nbPoints; i++) {
  3037. 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)));
  3038. }
  3039. return new Curve3(bez);
  3040. };
  3041. /**
  3042. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3043. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3044. * @param v1 (Vector3) the first control point
  3045. * @param v2 (Vector3) the second control point
  3046. * @param v3 (Vector3) the end point of the Cubic Bezier
  3047. * @param nbPoints (integer) the wanted number of points in the curve
  3048. */
  3049. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3050. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3051. var bez = new Array();
  3052. var equation = function (t, val0, val1, val2, val3) {
  3053. 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;
  3054. return res;
  3055. };
  3056. for (var i = 0; i <= nbPoints; i++) {
  3057. 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)));
  3058. }
  3059. return new Curve3(bez);
  3060. };
  3061. /**
  3062. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3063. * @param p1 (Vector3) the origin point of the Hermite Spline
  3064. * @param t1 (Vector3) the tangent vector at the origin point
  3065. * @param p2 (Vector3) the end point of the Hermite Spline
  3066. * @param t2 (Vector3) the tangent vector at the end point
  3067. * @param nbPoints (integer) the wanted number of points in the curve
  3068. */
  3069. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3070. var hermite = new Array();
  3071. var step = 1.0 / nbPoints;
  3072. for (var i = 0; i <= nbPoints; i++) {
  3073. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3074. }
  3075. return new Curve3(hermite);
  3076. };
  3077. /**
  3078. * Returns the Curve3 stored array of successive Vector3
  3079. */
  3080. Curve3.prototype.getPoints = function () {
  3081. return this._points;
  3082. };
  3083. /**
  3084. * Returns the computed length (float) of the curve.
  3085. */
  3086. Curve3.prototype.length = function () {
  3087. return this._length;
  3088. };
  3089. /**
  3090. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3091. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3092. * curveA and curveB keep unchanged.
  3093. */
  3094. Curve3.prototype.continue = function (curve) {
  3095. var lastPoint = this._points[this._points.length - 1];
  3096. var continuedPoints = this._points.slice();
  3097. var curvePoints = curve.getPoints();
  3098. for (var i = 1; i < curvePoints.length; i++) {
  3099. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3100. }
  3101. var continuedCurve = new Curve3(continuedPoints);
  3102. return continuedCurve;
  3103. };
  3104. Curve3.prototype._computeLength = function (path) {
  3105. var l = 0;
  3106. for (var i = 1; i < path.length; i++) {
  3107. l += (path[i].subtract(path[i - 1])).length();
  3108. }
  3109. return l;
  3110. };
  3111. return Curve3;
  3112. }());
  3113. BABYLON.Curve3 = Curve3;
  3114. // SphericalHarmonics
  3115. var SphericalHarmonics = (function () {
  3116. function SphericalHarmonics() {
  3117. this.L00 = Vector3.Zero();
  3118. this.L1_1 = Vector3.Zero();
  3119. this.L10 = Vector3.Zero();
  3120. this.L11 = Vector3.Zero();
  3121. this.L2_2 = Vector3.Zero();
  3122. this.L2_1 = Vector3.Zero();
  3123. this.L20 = Vector3.Zero();
  3124. this.L21 = Vector3.Zero();
  3125. this.L22 = Vector3.Zero();
  3126. }
  3127. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3128. var colorVector = new Vector3(color.r, color.g, color.b);
  3129. var c = colorVector.scale(deltaSolidAngle);
  3130. this.L00 = this.L00.add(c.scale(0.282095));
  3131. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3132. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3133. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3134. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3135. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3136. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3137. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3138. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3139. };
  3140. SphericalHarmonics.prototype.scale = function (scale) {
  3141. this.L00 = this.L00.scale(scale);
  3142. this.L1_1 = this.L1_1.scale(scale);
  3143. this.L10 = this.L10.scale(scale);
  3144. this.L11 = this.L11.scale(scale);
  3145. this.L2_2 = this.L2_2.scale(scale);
  3146. this.L2_1 = this.L2_1.scale(scale);
  3147. this.L20 = this.L20.scale(scale);
  3148. this.L21 = this.L21.scale(scale);
  3149. this.L22 = this.L22.scale(scale);
  3150. };
  3151. return SphericalHarmonics;
  3152. }());
  3153. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3154. // SphericalPolynomial
  3155. var SphericalPolynomial = (function () {
  3156. function SphericalPolynomial() {
  3157. this.x = Vector3.Zero();
  3158. this.y = Vector3.Zero();
  3159. this.z = Vector3.Zero();
  3160. this.xx = Vector3.Zero();
  3161. this.yy = Vector3.Zero();
  3162. this.zz = Vector3.Zero();
  3163. this.xy = Vector3.Zero();
  3164. this.yz = Vector3.Zero();
  3165. this.zx = Vector3.Zero();
  3166. }
  3167. SphericalPolynomial.prototype.addAmbient = function (color) {
  3168. var colorVector = new Vector3(color.r, color.g, color.b);
  3169. this.xx = this.xx.add(colorVector);
  3170. this.yy = this.yy.add(colorVector);
  3171. this.zz = this.zz.add(colorVector);
  3172. };
  3173. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3174. var result = new SphericalPolynomial();
  3175. result.x = harmonics.L11.scale(1.02333);
  3176. result.y = harmonics.L1_1.scale(1.02333);
  3177. result.z = harmonics.L10.scale(1.02333);
  3178. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3179. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3180. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3181. result.yz = harmonics.L2_1.scale(0.858086);
  3182. result.zx = harmonics.L21.scale(0.858086);
  3183. result.xy = harmonics.L2_2.scale(0.858086);
  3184. return result;
  3185. };
  3186. return SphericalPolynomial;
  3187. }());
  3188. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3189. // Vertex formats
  3190. var PositionNormalVertex = (function () {
  3191. function PositionNormalVertex(position, normal) {
  3192. if (position === void 0) { position = Vector3.Zero(); }
  3193. if (normal === void 0) { normal = Vector3.Up(); }
  3194. this.position = position;
  3195. this.normal = normal;
  3196. }
  3197. PositionNormalVertex.prototype.clone = function () {
  3198. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3199. };
  3200. return PositionNormalVertex;
  3201. }());
  3202. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3203. var PositionNormalTextureVertex = (function () {
  3204. function PositionNormalTextureVertex(position, normal, uv) {
  3205. if (position === void 0) { position = Vector3.Zero(); }
  3206. if (normal === void 0) { normal = Vector3.Up(); }
  3207. if (uv === void 0) { uv = Vector2.Zero(); }
  3208. this.position = position;
  3209. this.normal = normal;
  3210. this.uv = uv;
  3211. }
  3212. PositionNormalTextureVertex.prototype.clone = function () {
  3213. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3214. };
  3215. return PositionNormalTextureVertex;
  3216. }());
  3217. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3218. // Temporary pre-allocated objects for engine internal use
  3219. // usage in any internal function :
  3220. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3221. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3222. var Tmp = (function () {
  3223. function Tmp() {
  3224. }
  3225. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3226. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3227. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3228. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3229. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3230. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3231. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3232. Matrix.Zero(), Matrix.Zero(),
  3233. Matrix.Zero(), Matrix.Zero(),
  3234. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3235. return Tmp;
  3236. }());
  3237. BABYLON.Tmp = Tmp;
  3238. })(BABYLON || (BABYLON = {}));
  3239. var BABYLON;
  3240. (function (BABYLON) {
  3241. function generateSerializableMember(type, sourceName) {
  3242. return function (target, propertyKey) {
  3243. if (!target.__serializableMembers) {
  3244. target.__serializableMembers = {};
  3245. }
  3246. if (!target.__serializableMembers[propertyKey]) {
  3247. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3248. }
  3249. };
  3250. }
  3251. function serialize(sourceName) {
  3252. return generateSerializableMember(0, sourceName); // value member
  3253. }
  3254. BABYLON.serialize = serialize;
  3255. function serializeAsTexture(sourceName) {
  3256. return generateSerializableMember(1, sourceName); // texture member
  3257. }
  3258. BABYLON.serializeAsTexture = serializeAsTexture;
  3259. function serializeAsColor3(sourceName) {
  3260. return generateSerializableMember(2, sourceName); // color3 member
  3261. }
  3262. BABYLON.serializeAsColor3 = serializeAsColor3;
  3263. function serializeAsFresnelParameters(sourceName) {
  3264. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3265. }
  3266. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3267. function serializeAsVector2(sourceName) {
  3268. return generateSerializableMember(4, sourceName); // vector2 member
  3269. }
  3270. BABYLON.serializeAsVector2 = serializeAsVector2;
  3271. function serializeAsVector3(sourceName) {
  3272. return generateSerializableMember(5, sourceName); // vector3 member
  3273. }
  3274. BABYLON.serializeAsVector3 = serializeAsVector3;
  3275. function serializeAsMeshReference(sourceName) {
  3276. return generateSerializableMember(6, sourceName); // mesh reference member
  3277. }
  3278. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3279. function serializeAsColorCurves(sourceName) {
  3280. return generateSerializableMember(7, sourceName); // color curves
  3281. }
  3282. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3283. var SerializationHelper = (function () {
  3284. function SerializationHelper() {
  3285. }
  3286. SerializationHelper.Serialize = function (entity, serializationObject) {
  3287. if (!serializationObject) {
  3288. serializationObject = {};
  3289. }
  3290. // Tags
  3291. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3292. // Properties
  3293. for (var property in entity.__serializableMembers) {
  3294. var propertyDescriptor = entity.__serializableMembers[property];
  3295. var targetPropertyName = propertyDescriptor.sourceName || property;
  3296. var propertyType = propertyDescriptor.type;
  3297. var sourceProperty = entity[property];
  3298. if (sourceProperty !== undefined && sourceProperty !== null) {
  3299. switch (propertyType) {
  3300. case 0:
  3301. serializationObject[targetPropertyName] = sourceProperty;
  3302. break;
  3303. case 1:
  3304. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3305. break;
  3306. case 2:
  3307. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3308. break;
  3309. case 3:
  3310. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3311. break;
  3312. case 4:
  3313. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3314. break;
  3315. case 5:
  3316. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3317. break;
  3318. case 6:
  3319. serializationObject[targetPropertyName] = sourceProperty.id;
  3320. break;
  3321. case 7:
  3322. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3323. break;
  3324. }
  3325. }
  3326. }
  3327. return serializationObject;
  3328. };
  3329. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3330. var destination = creationFunction();
  3331. // Tags
  3332. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3333. // Properties
  3334. for (var property in destination.__serializableMembers) {
  3335. var propertyDescriptor = destination.__serializableMembers[property];
  3336. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3337. var propertyType = propertyDescriptor.type;
  3338. if (sourceProperty !== undefined && sourceProperty !== null) {
  3339. switch (propertyType) {
  3340. case 0:
  3341. destination[property] = sourceProperty;
  3342. break;
  3343. case 1:
  3344. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3345. break;
  3346. case 2:
  3347. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3348. break;
  3349. case 3:
  3350. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3351. break;
  3352. case 4:
  3353. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3354. break;
  3355. case 5:
  3356. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3357. break;
  3358. case 6:
  3359. destination[property] = scene.getLastMeshByID(sourceProperty);
  3360. break;
  3361. case 7:
  3362. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3363. break;
  3364. }
  3365. }
  3366. }
  3367. return destination;
  3368. };
  3369. SerializationHelper.Clone = function (creationFunction, source) {
  3370. var destination = creationFunction();
  3371. // Tags
  3372. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3373. // Properties
  3374. for (var property in destination.__serializableMembers) {
  3375. var propertyDescriptor = destination.__serializableMembers[property];
  3376. var sourceProperty = source[property];
  3377. var propertyType = propertyDescriptor.type;
  3378. if (sourceProperty !== undefined && sourceProperty !== null) {
  3379. switch (propertyType) {
  3380. case 0: // Value
  3381. case 6:
  3382. destination[property] = sourceProperty;
  3383. break;
  3384. case 1: // Texture
  3385. case 2: // Color3
  3386. case 3: // FresnelParameters
  3387. case 4: // Vector2
  3388. case 5: // Vector3
  3389. case 7:
  3390. destination[property] = sourceProperty.clone();
  3391. break;
  3392. }
  3393. }
  3394. }
  3395. return destination;
  3396. };
  3397. return SerializationHelper;
  3398. }());
  3399. BABYLON.SerializationHelper = SerializationHelper;
  3400. })(BABYLON || (BABYLON = {}));
  3401. var BABYLON;
  3402. (function (BABYLON) {
  3403. /**
  3404. * A class serves as a medium between the observable and its observers
  3405. */
  3406. var EventState = (function () {
  3407. /**
  3408. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3409. */
  3410. function EventState(mask, skipNextObservers) {
  3411. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3412. this.initalize(mask, skipNextObservers);
  3413. }
  3414. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3415. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3416. this.mask = mask;
  3417. this.skipNextObservers = skipNextObservers;
  3418. return this;
  3419. };
  3420. return EventState;
  3421. }());
  3422. BABYLON.EventState = EventState;
  3423. /**
  3424. * Represent an Observer registered to a given Observable object.
  3425. */
  3426. var Observer = (function () {
  3427. function Observer(callback, mask) {
  3428. this.callback = callback;
  3429. this.mask = mask;
  3430. }
  3431. return Observer;
  3432. }());
  3433. BABYLON.Observer = Observer;
  3434. /**
  3435. * The Observable class is a simple implementation of the Observable pattern.
  3436. * 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.
  3437. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3438. * 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).
  3439. * 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.
  3440. */
  3441. var Observable = (function () {
  3442. function Observable() {
  3443. this._observers = new Array();
  3444. this._eventState = new EventState(0);
  3445. }
  3446. /**
  3447. * Create a new Observer with the specified callback
  3448. * @param callback the callback that will be executed for that Observer
  3449. * @param mask the mask used to filter observers
  3450. * @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.
  3451. */
  3452. Observable.prototype.add = function (callback, mask, insertFirst) {
  3453. if (mask === void 0) { mask = -1; }
  3454. if (insertFirst === void 0) { insertFirst = false; }
  3455. if (!callback) {
  3456. return null;
  3457. }
  3458. var observer = new Observer(callback, mask);
  3459. if (insertFirst) {
  3460. this._observers.unshift(observer);
  3461. }
  3462. else {
  3463. this._observers.push(observer);
  3464. }
  3465. return observer;
  3466. };
  3467. /**
  3468. * Remove an Observer from the Observable object
  3469. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3470. */
  3471. Observable.prototype.remove = function (observer) {
  3472. var index = this._observers.indexOf(observer);
  3473. if (index !== -1) {
  3474. this._observers.splice(index, 1);
  3475. return true;
  3476. }
  3477. return false;
  3478. };
  3479. /**
  3480. * Remove a callback from the Observable object
  3481. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3482. */
  3483. Observable.prototype.removeCallback = function (callback) {
  3484. for (var index = 0; index < this._observers.length; index++) {
  3485. if (this._observers[index].callback === callback) {
  3486. this._observers.splice(index, 1);
  3487. return true;
  3488. }
  3489. }
  3490. return false;
  3491. };
  3492. /**
  3493. * Notify all Observers by calling their respective callback with the given data
  3494. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3495. * @param eventData
  3496. * @param mask
  3497. */
  3498. Observable.prototype.notifyObservers = function (eventData, mask) {
  3499. if (mask === void 0) { mask = -1; }
  3500. var state = this._eventState;
  3501. state.mask = mask;
  3502. state.skipNextObservers = false;
  3503. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3504. var obs = _a[_i];
  3505. if (obs.mask & mask) {
  3506. obs.callback(eventData, state);
  3507. }
  3508. if (state.skipNextObservers) {
  3509. return false;
  3510. }
  3511. }
  3512. return true;
  3513. };
  3514. /**
  3515. * return true is the Observable has at least one Observer registered
  3516. */
  3517. Observable.prototype.hasObservers = function () {
  3518. return this._observers.length > 0;
  3519. };
  3520. /**
  3521. * Clear the list of observers
  3522. */
  3523. Observable.prototype.clear = function () {
  3524. this._observers = new Array();
  3525. };
  3526. /**
  3527. * Clone the current observable
  3528. */
  3529. Observable.prototype.clone = function () {
  3530. var result = new Observable();
  3531. result._observers = this._observers.slice(0);
  3532. return result;
  3533. };
  3534. return Observable;
  3535. }());
  3536. BABYLON.Observable = Observable;
  3537. })(BABYLON || (BABYLON = {}));
  3538. var BABYLON;
  3539. (function (BABYLON) {
  3540. var Database = (function () {
  3541. function Database(urlToScene, callbackManifestChecked) {
  3542. // Handling various flavors of prefixed version of IndexedDB
  3543. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3544. this.callbackManifestChecked = callbackManifestChecked;
  3545. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3546. this.db = null;
  3547. this.enableSceneOffline = false;
  3548. this.enableTexturesOffline = false;
  3549. this.manifestVersionFound = 0;
  3550. this.mustUpdateRessources = false;
  3551. this.hasReachedQuota = false;
  3552. if (!Database.IDBStorageEnabled) {
  3553. this.callbackManifestChecked(true);
  3554. }
  3555. else {
  3556. this.checkManifestFile();
  3557. }
  3558. }
  3559. Database.prototype.checkManifestFile = function () {
  3560. var _this = this;
  3561. function noManifestFile() {
  3562. that.enableSceneOffline = false;
  3563. that.enableTexturesOffline = false;
  3564. that.callbackManifestChecked(false);
  3565. }
  3566. var that = this;
  3567. var timeStampUsed = false;
  3568. var manifestURL = this.currentSceneUrl + ".manifest";
  3569. var xhr = new XMLHttpRequest();
  3570. if (navigator.onLine) {
  3571. // Adding a timestamp to by-pass browsers' cache
  3572. timeStampUsed = true;
  3573. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3574. }
  3575. xhr.open("GET", manifestURL, true);
  3576. xhr.addEventListener("load", function () {
  3577. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3578. try {
  3579. var manifestFile = JSON.parse(xhr.response);
  3580. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3581. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3582. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3583. _this.manifestVersionFound = manifestFile.version;
  3584. }
  3585. if (_this.callbackManifestChecked) {
  3586. _this.callbackManifestChecked(true);
  3587. }
  3588. }
  3589. catch (ex) {
  3590. noManifestFile();
  3591. }
  3592. }
  3593. else {
  3594. noManifestFile();
  3595. }
  3596. }, false);
  3597. xhr.addEventListener("error", function (event) {
  3598. if (timeStampUsed) {
  3599. timeStampUsed = false;
  3600. // Let's retry without the timeStamp
  3601. // It could fail when coupled with HTML5 Offline API
  3602. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3603. xhr.open("GET", retryManifestURL, true);
  3604. xhr.send();
  3605. }
  3606. else {
  3607. noManifestFile();
  3608. }
  3609. }, false);
  3610. try {
  3611. xhr.send();
  3612. }
  3613. catch (ex) {
  3614. BABYLON.Tools.Error("Error on XHR send request.");
  3615. that.callbackManifestChecked(false);
  3616. }
  3617. };
  3618. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3619. var _this = this;
  3620. function handleError() {
  3621. that.isSupported = false;
  3622. if (errorCallback)
  3623. errorCallback();
  3624. }
  3625. var that = this;
  3626. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3627. // Your browser doesn't support IndexedDB
  3628. this.isSupported = false;
  3629. if (errorCallback)
  3630. errorCallback();
  3631. }
  3632. else {
  3633. // If the DB hasn't been opened or created yet
  3634. if (!this.db) {
  3635. this.hasReachedQuota = false;
  3636. this.isSupported = true;
  3637. var request = this.idbFactory.open("babylonjs", 1);
  3638. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3639. request.onerror = function (event) {
  3640. handleError();
  3641. };
  3642. // executes when a version change transaction cannot complete due to other active transactions
  3643. request.onblocked = function (event) {
  3644. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3645. handleError();
  3646. };
  3647. // DB has been opened successfully
  3648. request.onsuccess = function (event) {
  3649. _this.db = request.result;
  3650. successCallback();
  3651. };
  3652. // Initialization of the DB. Creating Scenes & Textures stores
  3653. request.onupgradeneeded = function (event) {
  3654. _this.db = (event.target).result;
  3655. try {
  3656. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3657. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3658. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3659. }
  3660. catch (ex) {
  3661. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3662. handleError();
  3663. }
  3664. };
  3665. }
  3666. else {
  3667. if (successCallback)
  3668. successCallback();
  3669. }
  3670. }
  3671. };
  3672. Database.prototype.loadImageFromDB = function (url, image) {
  3673. var _this = this;
  3674. var completeURL = Database.ReturnFullUrlLocation(url);
  3675. var saveAndLoadImage = function () {
  3676. if (!_this.hasReachedQuota && _this.db !== null) {
  3677. // the texture is not yet in the DB, let's try to save it
  3678. _this._saveImageIntoDBAsync(completeURL, image);
  3679. }
  3680. else {
  3681. image.src = url;
  3682. }
  3683. };
  3684. if (!this.mustUpdateRessources) {
  3685. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3686. }
  3687. else {
  3688. saveAndLoadImage();
  3689. }
  3690. };
  3691. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3692. if (this.isSupported && this.db !== null) {
  3693. var texture;
  3694. var transaction = this.db.transaction(["textures"]);
  3695. transaction.onabort = function (event) {
  3696. image.src = url;
  3697. };
  3698. transaction.oncomplete = function (event) {
  3699. var blobTextureURL;
  3700. if (texture) {
  3701. var URL = window.URL || window.webkitURL;
  3702. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3703. image.onerror = function () {
  3704. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3705. image.src = url;
  3706. };
  3707. image.src = blobTextureURL;
  3708. }
  3709. else {
  3710. notInDBCallback();
  3711. }
  3712. };
  3713. var getRequest = transaction.objectStore("textures").get(url);
  3714. getRequest.onsuccess = function (event) {
  3715. texture = (event.target).result;
  3716. };
  3717. getRequest.onerror = function (event) {
  3718. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3719. image.src = url;
  3720. };
  3721. }
  3722. else {
  3723. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3724. image.src = url;
  3725. }
  3726. };
  3727. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3728. var _this = this;
  3729. if (this.isSupported) {
  3730. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3731. var generateBlobUrl = function () {
  3732. var blobTextureURL;
  3733. if (blob) {
  3734. var URL = window.URL || window.webkitURL;
  3735. try {
  3736. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3737. }
  3738. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3739. catch (ex) {
  3740. blobTextureURL = URL.createObjectURL(blob);
  3741. }
  3742. }
  3743. image.src = blobTextureURL;
  3744. };
  3745. if (Database.IsUASupportingBlobStorage) {
  3746. var xhr = new XMLHttpRequest(), blob;
  3747. xhr.open("GET", url, true);
  3748. xhr.responseType = "blob";
  3749. xhr.addEventListener("load", function () {
  3750. if (xhr.status === 200) {
  3751. // Blob as response (XHR2)
  3752. blob = xhr.response;
  3753. var transaction = _this.db.transaction(["textures"], "readwrite");
  3754. // the transaction could abort because of a QuotaExceededError error
  3755. transaction.onabort = function (event) {
  3756. try {
  3757. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3758. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3759. _this.hasReachedQuota = true;
  3760. }
  3761. }
  3762. catch (ex) { }
  3763. generateBlobUrl();
  3764. };
  3765. transaction.oncomplete = function (event) {
  3766. generateBlobUrl();
  3767. };
  3768. var newTexture = { textureUrl: url, data: blob };
  3769. try {
  3770. // Put the blob into the dabase
  3771. var addRequest = transaction.objectStore("textures").put(newTexture);
  3772. addRequest.onsuccess = function (event) {
  3773. };
  3774. addRequest.onerror = function (event) {
  3775. generateBlobUrl();
  3776. };
  3777. }
  3778. catch (ex) {
  3779. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3780. if (ex.code === 25) {
  3781. Database.IsUASupportingBlobStorage = false;
  3782. }
  3783. image.src = url;
  3784. }
  3785. }
  3786. else {
  3787. image.src = url;
  3788. }
  3789. }, false);
  3790. xhr.addEventListener("error", function (event) {
  3791. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3792. image.src = url;
  3793. }, false);
  3794. xhr.send();
  3795. }
  3796. else {
  3797. image.src = url;
  3798. }
  3799. }
  3800. else {
  3801. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3802. image.src = url;
  3803. }
  3804. };
  3805. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3806. var _this = this;
  3807. var updateVersion = function (event) {
  3808. // the version is not yet in the DB or we need to update it
  3809. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3810. };
  3811. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3812. };
  3813. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3814. var _this = this;
  3815. if (this.isSupported) {
  3816. var version;
  3817. try {
  3818. var transaction = this.db.transaction(["versions"]);
  3819. transaction.oncomplete = function (event) {
  3820. if (version) {
  3821. // If the version in the JSON file is > than the version in DB
  3822. if (_this.manifestVersionFound > version.data) {
  3823. _this.mustUpdateRessources = true;
  3824. updateInDBCallback();
  3825. }
  3826. else {
  3827. callback(version.data);
  3828. }
  3829. }
  3830. else {
  3831. _this.mustUpdateRessources = true;
  3832. updateInDBCallback();
  3833. }
  3834. };
  3835. transaction.onabort = function (event) {
  3836. callback(-1);
  3837. };
  3838. var getRequest = transaction.objectStore("versions").get(url);
  3839. getRequest.onsuccess = function (event) {
  3840. version = (event.target).result;
  3841. };
  3842. getRequest.onerror = function (event) {
  3843. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3844. callback(-1);
  3845. };
  3846. }
  3847. catch (ex) {
  3848. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3849. callback(-1);
  3850. }
  3851. }
  3852. else {
  3853. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3854. callback(-1);
  3855. }
  3856. };
  3857. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3858. var _this = this;
  3859. if (this.isSupported && !this.hasReachedQuota) {
  3860. try {
  3861. // Open a transaction to the database
  3862. var transaction = this.db.transaction(["versions"], "readwrite");
  3863. // the transaction could abort because of a QuotaExceededError error
  3864. transaction.onabort = function (event) {
  3865. try {
  3866. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3867. _this.hasReachedQuota = true;
  3868. }
  3869. }
  3870. catch (ex) { }
  3871. callback(-1);
  3872. };
  3873. transaction.oncomplete = function (event) {
  3874. callback(_this.manifestVersionFound);
  3875. };
  3876. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3877. // Put the scene into the database
  3878. var addRequest = transaction.objectStore("versions").put(newVersion);
  3879. addRequest.onsuccess = function (event) {
  3880. };
  3881. addRequest.onerror = function (event) {
  3882. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3883. };
  3884. }
  3885. catch (ex) {
  3886. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3887. callback(-1);
  3888. }
  3889. }
  3890. else {
  3891. callback(-1);
  3892. }
  3893. };
  3894. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3895. var _this = this;
  3896. var completeUrl = Database.ReturnFullUrlLocation(url);
  3897. var saveAndLoadFile = function (event) {
  3898. // the scene is not yet in the DB, let's try to save it
  3899. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3900. };
  3901. this._checkVersionFromDB(completeUrl, function (version) {
  3902. if (version !== -1) {
  3903. if (!_this.mustUpdateRessources) {
  3904. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3905. }
  3906. else {
  3907. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3908. }
  3909. }
  3910. else {
  3911. errorCallback();
  3912. }
  3913. });
  3914. };
  3915. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3916. if (this.isSupported) {
  3917. var targetStore;
  3918. if (url.indexOf(".babylon") !== -1) {
  3919. targetStore = "scenes";
  3920. }
  3921. else {
  3922. targetStore = "textures";
  3923. }
  3924. var file;
  3925. var transaction = this.db.transaction([targetStore]);
  3926. transaction.oncomplete = function (event) {
  3927. if (file) {
  3928. callback(file.data);
  3929. }
  3930. else {
  3931. notInDBCallback();
  3932. }
  3933. };
  3934. transaction.onabort = function (event) {
  3935. notInDBCallback();
  3936. };
  3937. var getRequest = transaction.objectStore(targetStore).get(url);
  3938. getRequest.onsuccess = function (event) {
  3939. file = (event.target).result;
  3940. };
  3941. getRequest.onerror = function (event) {
  3942. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3943. notInDBCallback();
  3944. };
  3945. }
  3946. else {
  3947. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3948. callback();
  3949. }
  3950. };
  3951. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3952. var _this = this;
  3953. if (this.isSupported) {
  3954. var targetStore;
  3955. if (url.indexOf(".babylon") !== -1) {
  3956. targetStore = "scenes";
  3957. }
  3958. else {
  3959. targetStore = "textures";
  3960. }
  3961. // Create XHR
  3962. var xhr = new XMLHttpRequest(), fileData;
  3963. xhr.open("GET", url, true);
  3964. if (useArrayBuffer) {
  3965. xhr.responseType = "arraybuffer";
  3966. }
  3967. xhr.onprogress = progressCallback;
  3968. xhr.addEventListener("load", function () {
  3969. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3970. // Blob as response (XHR2)
  3971. //fileData = xhr.responseText;
  3972. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3973. if (!_this.hasReachedQuota) {
  3974. // Open a transaction to the database
  3975. var transaction = _this.db.transaction([targetStore], "readwrite");
  3976. // the transaction could abort because of a QuotaExceededError error
  3977. transaction.onabort = function (event) {
  3978. try {
  3979. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3980. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3981. _this.hasReachedQuota = true;
  3982. }
  3983. }
  3984. catch (ex) { }
  3985. callback(fileData);
  3986. };
  3987. transaction.oncomplete = function (event) {
  3988. callback(fileData);
  3989. };
  3990. var newFile;
  3991. if (targetStore === "scenes") {
  3992. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3993. }
  3994. else {
  3995. newFile = { textureUrl: url, data: fileData };
  3996. }
  3997. try {
  3998. // Put the scene into the database
  3999. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4000. addRequest.onsuccess = function (event) {
  4001. };
  4002. addRequest.onerror = function (event) {
  4003. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4004. };
  4005. }
  4006. catch (ex) {
  4007. callback(fileData);
  4008. }
  4009. }
  4010. else {
  4011. callback(fileData);
  4012. }
  4013. }
  4014. else {
  4015. callback();
  4016. }
  4017. }, false);
  4018. xhr.addEventListener("error", function (event) {
  4019. BABYLON.Tools.Error("error on XHR request.");
  4020. callback();
  4021. }, false);
  4022. xhr.send();
  4023. }
  4024. else {
  4025. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4026. callback();
  4027. }
  4028. };
  4029. Database.IsUASupportingBlobStorage = true;
  4030. Database.IDBStorageEnabled = true;
  4031. Database.parseURL = function (url) {
  4032. var a = document.createElement('a');
  4033. a.href = url;
  4034. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4035. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4036. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4037. return absLocation;
  4038. };
  4039. Database.ReturnFullUrlLocation = function (url) {
  4040. if (url.indexOf("http:/") === -1) {
  4041. return (Database.parseURL(window.location.href) + url);
  4042. }
  4043. else {
  4044. return url;
  4045. }
  4046. };
  4047. return Database;
  4048. }());
  4049. BABYLON.Database = Database;
  4050. })(BABYLON || (BABYLON = {}));
  4051. var BABYLON;
  4052. (function (BABYLON) {
  4053. var Internals;
  4054. (function (Internals) {
  4055. /*
  4056. * Based on jsTGALoader - Javascript loader for TGA file
  4057. * By Vincent Thibault
  4058. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4059. */
  4060. var TGATools = (function () {
  4061. function TGATools() {
  4062. }
  4063. TGATools.GetTGAHeader = function (data) {
  4064. var offset = 0;
  4065. var header = {
  4066. id_length: data[offset++],
  4067. colormap_type: data[offset++],
  4068. image_type: data[offset++],
  4069. colormap_index: data[offset++] | data[offset++] << 8,
  4070. colormap_length: data[offset++] | data[offset++] << 8,
  4071. colormap_size: data[offset++],
  4072. origin: [
  4073. data[offset++] | data[offset++] << 8,
  4074. data[offset++] | data[offset++] << 8
  4075. ],
  4076. width: data[offset++] | data[offset++] << 8,
  4077. height: data[offset++] | data[offset++] << 8,
  4078. pixel_size: data[offset++],
  4079. flags: data[offset++]
  4080. };
  4081. return header;
  4082. };
  4083. TGATools.UploadContent = function (gl, data) {
  4084. // Not enough data to contain header ?
  4085. if (data.length < 19) {
  4086. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4087. return;
  4088. }
  4089. // Read Header
  4090. var offset = 18;
  4091. var header = TGATools.GetTGAHeader(data);
  4092. // Assume it's a valid Targa file.
  4093. if (header.id_length + offset > data.length) {
  4094. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4095. return;
  4096. }
  4097. // Skip not needed data
  4098. offset += header.id_length;
  4099. var use_rle = false;
  4100. var use_pal = false;
  4101. var use_rgb = false;
  4102. var use_grey = false;
  4103. // Get some informations.
  4104. switch (header.image_type) {
  4105. case TGATools._TYPE_RLE_INDEXED:
  4106. use_rle = true;
  4107. case TGATools._TYPE_INDEXED:
  4108. use_pal = true;
  4109. break;
  4110. case TGATools._TYPE_RLE_RGB:
  4111. use_rle = true;
  4112. case TGATools._TYPE_RGB:
  4113. use_rgb = true;
  4114. break;
  4115. case TGATools._TYPE_RLE_GREY:
  4116. use_rle = true;
  4117. case TGATools._TYPE_GREY:
  4118. use_grey = true;
  4119. break;
  4120. }
  4121. var pixel_data;
  4122. var numAlphaBits = header.flags & 0xf;
  4123. var pixel_size = header.pixel_size >> 3;
  4124. var pixel_total = header.width * header.height * pixel_size;
  4125. // Read palettes
  4126. var palettes;
  4127. if (use_pal) {
  4128. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4129. }
  4130. // Read LRE
  4131. if (use_rle) {
  4132. pixel_data = new Uint8Array(pixel_total);
  4133. var c, count, i;
  4134. var localOffset = 0;
  4135. var pixels = new Uint8Array(pixel_size);
  4136. while (offset < pixel_total && localOffset < pixel_total) {
  4137. c = data[offset++];
  4138. count = (c & 0x7f) + 1;
  4139. // RLE pixels
  4140. if (c & 0x80) {
  4141. // Bind pixel tmp array
  4142. for (i = 0; i < pixel_size; ++i) {
  4143. pixels[i] = data[offset++];
  4144. }
  4145. // Copy pixel array
  4146. for (i = 0; i < count; ++i) {
  4147. pixel_data.set(pixels, localOffset + i * pixel_size);
  4148. }
  4149. localOffset += pixel_size * count;
  4150. }
  4151. else {
  4152. count *= pixel_size;
  4153. for (i = 0; i < count; ++i) {
  4154. pixel_data[localOffset + i] = data[offset++];
  4155. }
  4156. localOffset += count;
  4157. }
  4158. }
  4159. }
  4160. else {
  4161. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4162. }
  4163. // Load to texture
  4164. var x_start, y_start, x_step, y_step, y_end, x_end;
  4165. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4166. default:
  4167. case TGATools._ORIGIN_UL:
  4168. x_start = 0;
  4169. x_step = 1;
  4170. x_end = header.width;
  4171. y_start = 0;
  4172. y_step = 1;
  4173. y_end = header.height;
  4174. break;
  4175. case TGATools._ORIGIN_BL:
  4176. x_start = 0;
  4177. x_step = 1;
  4178. x_end = header.width;
  4179. y_start = header.height - 1;
  4180. y_step = -1;
  4181. y_end = -1;
  4182. break;
  4183. case TGATools._ORIGIN_UR:
  4184. x_start = header.width - 1;
  4185. x_step = -1;
  4186. x_end = -1;
  4187. y_start = 0;
  4188. y_step = 1;
  4189. y_end = header.height;
  4190. break;
  4191. case TGATools._ORIGIN_BR:
  4192. x_start = header.width - 1;
  4193. x_step = -1;
  4194. x_end = -1;
  4195. y_start = header.height - 1;
  4196. y_step = -1;
  4197. y_end = -1;
  4198. break;
  4199. }
  4200. // Load the specify method
  4201. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4202. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4203. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4204. };
  4205. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4206. var image = pixel_data, colormap = palettes;
  4207. var width = header.width, height = header.height;
  4208. var color, i = 0, x, y;
  4209. var imageData = new Uint8Array(width * height * 4);
  4210. for (y = y_start; y !== y_end; y += y_step) {
  4211. for (x = x_start; x !== x_end; x += x_step, i++) {
  4212. color = image[i];
  4213. imageData[(x + width * y) * 4 + 3] = 255;
  4214. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4215. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4216. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4217. }
  4218. }
  4219. return imageData;
  4220. };
  4221. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4222. var image = pixel_data;
  4223. var width = header.width, height = header.height;
  4224. var color, i = 0, x, y;
  4225. var imageData = new Uint8Array(width * height * 4);
  4226. for (y = y_start; y !== y_end; y += y_step) {
  4227. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4228. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4229. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4230. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4231. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4232. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4233. }
  4234. }
  4235. return imageData;
  4236. };
  4237. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4238. var image = pixel_data;
  4239. var width = header.width, height = header.height;
  4240. var i = 0, x, y;
  4241. var imageData = new Uint8Array(width * height * 4);
  4242. for (y = y_start; y !== y_end; y += y_step) {
  4243. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4244. imageData[(x + width * y) * 4 + 3] = 255;
  4245. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4246. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4247. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4248. }
  4249. }
  4250. return imageData;
  4251. };
  4252. TGATools._getImageData32bits = 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 += 4) {
  4259. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4260. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4261. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4262. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4263. }
  4264. }
  4265. return imageData;
  4266. };
  4267. TGATools._getImageDataGrey8bits = 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 color, 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++) {
  4274. color = image[i];
  4275. imageData[(x + width * y) * 4 + 0] = color;
  4276. imageData[(x + width * y) * 4 + 1] = color;
  4277. imageData[(x + width * y) * 4 + 2] = color;
  4278. imageData[(x + width * y) * 4 + 3] = 255;
  4279. }
  4280. }
  4281. return imageData;
  4282. };
  4283. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4284. var image = pixel_data;
  4285. var width = header.width, height = header.height;
  4286. var i = 0, x, y;
  4287. var imageData = new Uint8Array(width * height * 4);
  4288. for (y = y_start; y !== y_end; y += y_step) {
  4289. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4290. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4291. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4292. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4293. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4294. }
  4295. }
  4296. return imageData;
  4297. };
  4298. TGATools._TYPE_NO_DATA = 0;
  4299. TGATools._TYPE_INDEXED = 1;
  4300. TGATools._TYPE_RGB = 2;
  4301. TGATools._TYPE_GREY = 3;
  4302. TGATools._TYPE_RLE_INDEXED = 9;
  4303. TGATools._TYPE_RLE_RGB = 10;
  4304. TGATools._TYPE_RLE_GREY = 11;
  4305. TGATools._ORIGIN_MASK = 0x30;
  4306. TGATools._ORIGIN_SHIFT = 0x04;
  4307. TGATools._ORIGIN_BL = 0x00;
  4308. TGATools._ORIGIN_BR = 0x01;
  4309. TGATools._ORIGIN_UL = 0x02;
  4310. TGATools._ORIGIN_UR = 0x03;
  4311. return TGATools;
  4312. }());
  4313. Internals.TGATools = TGATools;
  4314. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4315. })(BABYLON || (BABYLON = {}));
  4316. var BABYLON;
  4317. (function (BABYLON) {
  4318. var SmartArray = (function () {
  4319. function SmartArray(capacity) {
  4320. this.length = 0;
  4321. this._duplicateId = 0;
  4322. this.data = new Array(capacity);
  4323. this._id = SmartArray._GlobalId++;
  4324. }
  4325. SmartArray.prototype.push = function (value) {
  4326. this.data[this.length++] = value;
  4327. if (this.length > this.data.length) {
  4328. this.data.length *= 2;
  4329. }
  4330. if (!value.__smartArrayFlags) {
  4331. value.__smartArrayFlags = {};
  4332. }
  4333. value.__smartArrayFlags[this._id] = this._duplicateId;
  4334. };
  4335. SmartArray.prototype.pushNoDuplicate = function (value) {
  4336. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4337. return false;
  4338. }
  4339. this.push(value);
  4340. return true;
  4341. };
  4342. SmartArray.prototype.sort = function (compareFn) {
  4343. this.data.sort(compareFn);
  4344. };
  4345. SmartArray.prototype.reset = function () {
  4346. this.length = 0;
  4347. this._duplicateId++;
  4348. };
  4349. SmartArray.prototype.concat = function (array) {
  4350. if (array.length === 0) {
  4351. return;
  4352. }
  4353. if (this.length + array.length > this.data.length) {
  4354. this.data.length = (this.length + array.length) * 2;
  4355. }
  4356. for (var index = 0; index < array.length; index++) {
  4357. this.data[this.length++] = (array.data || array)[index];
  4358. }
  4359. };
  4360. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4361. if (array.length === 0) {
  4362. return;
  4363. }
  4364. if (this.length + array.length > this.data.length) {
  4365. this.data.length = (this.length + array.length) * 2;
  4366. }
  4367. for (var index = 0; index < array.length; index++) {
  4368. var item = (array.data || array)[index];
  4369. this.pushNoDuplicate(item);
  4370. }
  4371. };
  4372. SmartArray.prototype.indexOf = function (value) {
  4373. var position = this.data.indexOf(value);
  4374. if (position >= this.length) {
  4375. return -1;
  4376. }
  4377. return position;
  4378. };
  4379. // Statics
  4380. SmartArray._GlobalId = 0;
  4381. return SmartArray;
  4382. }());
  4383. BABYLON.SmartArray = SmartArray;
  4384. })(BABYLON || (BABYLON = {}));
  4385. var BABYLON;
  4386. (function (BABYLON) {
  4387. /**
  4388. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4389. * The underlying implementation relies on an associative array to ensure the best performances.
  4390. * The value can be anything including 'null' but except 'undefined'
  4391. */
  4392. var StringDictionary = (function () {
  4393. function StringDictionary() {
  4394. this._count = 0;
  4395. this._data = {};
  4396. }
  4397. /**
  4398. * This will clear this dictionary and copy the content from the 'source' one.
  4399. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4400. * @param source the dictionary to take the content from and copy to this dictionary
  4401. */
  4402. StringDictionary.prototype.copyFrom = function (source) {
  4403. var _this = this;
  4404. this.clear();
  4405. source.forEach(function (t, v) { return _this.add(t, v); });
  4406. };
  4407. /**
  4408. * Get a value based from its key
  4409. * @param key the given key to get the matching value from
  4410. * @return the value if found, otherwise undefined is returned
  4411. */
  4412. StringDictionary.prototype.get = function (key) {
  4413. var val = this._data[key];
  4414. if (val !== undefined) {
  4415. return val;
  4416. }
  4417. return undefined;
  4418. };
  4419. /**
  4420. * Get a value from its key or add it if it doesn't exist.
  4421. * This method will ensure you that a given key/data will be present in the dictionary.
  4422. * @param key the given key to get the matching value from
  4423. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4424. * The factory will only be invoked if there's no data for the given key.
  4425. * @return the value corresponding to the key.
  4426. */
  4427. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4428. var val = this.get(key);
  4429. if (val !== undefined) {
  4430. return val;
  4431. }
  4432. val = factory(key);
  4433. if (val) {
  4434. this.add(key, val);
  4435. }
  4436. return val;
  4437. };
  4438. /**
  4439. * Get a value from its key if present in the dictionary otherwise add it
  4440. * @param key the key to get the value from
  4441. * @param val if there's no such key/value pair in the dictionary add it with this value
  4442. * @return the value corresponding to the key
  4443. */
  4444. StringDictionary.prototype.getOrAdd = function (key, val) {
  4445. var curVal = this.get(key);
  4446. if (curVal !== undefined) {
  4447. return curVal;
  4448. }
  4449. this.add(key, val);
  4450. return val;
  4451. };
  4452. /**
  4453. * Check if there's a given key in the dictionary
  4454. * @param key the key to check for
  4455. * @return true if the key is present, false otherwise
  4456. */
  4457. StringDictionary.prototype.contains = function (key) {
  4458. return this._data[key] !== undefined;
  4459. };
  4460. /**
  4461. * Add a new key and its corresponding value
  4462. * @param key the key to add
  4463. * @param value the value corresponding to the key
  4464. * @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
  4465. */
  4466. StringDictionary.prototype.add = function (key, value) {
  4467. if (this._data[key] !== undefined) {
  4468. return false;
  4469. }
  4470. this._data[key] = value;
  4471. ++this._count;
  4472. return true;
  4473. };
  4474. StringDictionary.prototype.set = function (key, value) {
  4475. if (this._data[key] === undefined) {
  4476. return false;
  4477. }
  4478. this._data[key] = value;
  4479. return true;
  4480. };
  4481. /**
  4482. * Get the element of the given key and remove it from the dictionary
  4483. * @param key
  4484. */
  4485. StringDictionary.prototype.getAndRemove = function (key) {
  4486. var val = this.get(key);
  4487. if (val !== undefined) {
  4488. delete this._data[key];
  4489. --this._count;
  4490. return val;
  4491. }
  4492. return null;
  4493. };
  4494. /**
  4495. * Remove a key/value from the dictionary.
  4496. * @param key the key to remove
  4497. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4498. */
  4499. StringDictionary.prototype.remove = function (key) {
  4500. if (this.contains(key)) {
  4501. delete this._data[key];
  4502. --this._count;
  4503. return true;
  4504. }
  4505. return false;
  4506. };
  4507. /**
  4508. * Clear the whole content of the dictionary
  4509. */
  4510. StringDictionary.prototype.clear = function () {
  4511. this._data = {};
  4512. this._count = 0;
  4513. };
  4514. Object.defineProperty(StringDictionary.prototype, "count", {
  4515. get: function () {
  4516. return this._count;
  4517. },
  4518. enumerable: true,
  4519. configurable: true
  4520. });
  4521. /**
  4522. * Execute a callback on each key/val of the dictionary.
  4523. * Note that you can remove any element in this dictionary in the callback implementation
  4524. * @param callback the callback to execute on a given key/value pair
  4525. */
  4526. StringDictionary.prototype.forEach = function (callback) {
  4527. for (var cur in this._data) {
  4528. var val = this._data[cur];
  4529. callback(cur, val);
  4530. }
  4531. };
  4532. /**
  4533. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4534. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4535. * Note that you can remove any element in this dictionary in the callback implementation
  4536. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4537. */
  4538. StringDictionary.prototype.first = function (callback) {
  4539. for (var cur in this._data) {
  4540. var val = this._data[cur];
  4541. var res = callback(cur, val);
  4542. if (res) {
  4543. return res;
  4544. }
  4545. }
  4546. return null;
  4547. };
  4548. return StringDictionary;
  4549. }());
  4550. BABYLON.StringDictionary = StringDictionary;
  4551. })(BABYLON || (BABYLON = {}));
  4552. var BABYLON;
  4553. (function (BABYLON) {
  4554. // Screenshots
  4555. var screenshotCanvas;
  4556. var cloneValue = function (source, destinationObject) {
  4557. if (!source)
  4558. return null;
  4559. if (source instanceof BABYLON.Mesh) {
  4560. return null;
  4561. }
  4562. if (source instanceof BABYLON.SubMesh) {
  4563. return source.clone(destinationObject);
  4564. }
  4565. else if (source.clone) {
  4566. return source.clone();
  4567. }
  4568. return null;
  4569. };
  4570. var Tools = (function () {
  4571. function Tools() {
  4572. }
  4573. Tools.Instantiate = function (className) {
  4574. var arr = className.split(".");
  4575. var fn = (window || this);
  4576. for (var i = 0, len = arr.length; i < len; i++) {
  4577. fn = fn[arr[i]];
  4578. }
  4579. if (typeof fn !== "function") {
  4580. return null;
  4581. }
  4582. return fn;
  4583. };
  4584. Tools.SetImmediate = function (action) {
  4585. if (window.setImmediate) {
  4586. window.setImmediate(action);
  4587. }
  4588. else {
  4589. setTimeout(action, 1);
  4590. }
  4591. };
  4592. Tools.IsExponentOfTwo = function (value) {
  4593. var count = 1;
  4594. do {
  4595. count *= 2;
  4596. } while (count < value);
  4597. return count === value;
  4598. };
  4599. Tools.GetExponentOfTwo = function (value, max) {
  4600. var count = 1;
  4601. do {
  4602. count *= 2;
  4603. } while (count < value);
  4604. if (count > max)
  4605. count = max;
  4606. return count;
  4607. };
  4608. Tools.GetFilename = function (path) {
  4609. var index = path.lastIndexOf("/");
  4610. if (index < 0)
  4611. return path;
  4612. return path.substring(index + 1);
  4613. };
  4614. Tools.GetDOMTextContent = function (element) {
  4615. var result = "";
  4616. var child = element.firstChild;
  4617. while (child) {
  4618. if (child.nodeType === 3) {
  4619. result += child.textContent;
  4620. }
  4621. child = child.nextSibling;
  4622. }
  4623. return result;
  4624. };
  4625. Tools.ToDegrees = function (angle) {
  4626. return angle * 180 / Math.PI;
  4627. };
  4628. Tools.ToRadians = function (angle) {
  4629. return angle * Math.PI / 180;
  4630. };
  4631. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4632. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4633. var output = "";
  4634. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4635. var i = 0;
  4636. var bytes = new Uint8Array(buffer);
  4637. while (i < bytes.length) {
  4638. chr1 = bytes[i++];
  4639. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4640. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4641. enc1 = chr1 >> 2;
  4642. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4643. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4644. enc4 = chr3 & 63;
  4645. if (isNaN(chr2)) {
  4646. enc3 = enc4 = 64;
  4647. }
  4648. else if (isNaN(chr3)) {
  4649. enc4 = 64;
  4650. }
  4651. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4652. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4653. }
  4654. return "data:image/png;base64," + output;
  4655. };
  4656. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4657. if (bias === void 0) { bias = null; }
  4658. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4659. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4660. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4661. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4662. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4663. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4664. }
  4665. if (bias) {
  4666. minimum.x -= minimum.x * bias.x + bias.y;
  4667. minimum.y -= minimum.y * bias.x + bias.y;
  4668. minimum.z -= minimum.z * bias.x + bias.y;
  4669. maximum.x += maximum.x * bias.x + bias.y;
  4670. maximum.y += maximum.y * bias.x + bias.y;
  4671. maximum.z += maximum.z * bias.x + bias.y;
  4672. }
  4673. return {
  4674. minimum: minimum,
  4675. maximum: maximum
  4676. };
  4677. };
  4678. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4679. if (bias === void 0) { bias = null; }
  4680. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4681. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4682. if (!stride) {
  4683. stride = 3;
  4684. }
  4685. for (var index = start; index < start + count; index++) {
  4686. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4687. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4688. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4689. }
  4690. if (bias) {
  4691. minimum.x -= minimum.x * bias.x + bias.y;
  4692. minimum.y -= minimum.y * bias.x + bias.y;
  4693. minimum.z -= minimum.z * bias.x + bias.y;
  4694. maximum.x += maximum.x * bias.x + bias.y;
  4695. maximum.y += maximum.y * bias.x + bias.y;
  4696. maximum.z += maximum.z * bias.x + bias.y;
  4697. }
  4698. return {
  4699. minimum: minimum,
  4700. maximum: maximum
  4701. };
  4702. };
  4703. Tools.Vector2ArrayFeeder = function (array) {
  4704. return function (index) {
  4705. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4706. var length = isFloatArray ? array.length / 2 : array.length;
  4707. if (index >= length) {
  4708. return null;
  4709. }
  4710. if (isFloatArray) {
  4711. var fa = array;
  4712. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4713. }
  4714. var a = array;
  4715. return a[index];
  4716. };
  4717. };
  4718. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4719. if (bias === void 0) { bias = null; }
  4720. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4721. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4722. var i = 0;
  4723. var cur = feeder(i++);
  4724. while (cur) {
  4725. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4726. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4727. cur = feeder(i++);
  4728. }
  4729. if (bias) {
  4730. minimum.x -= minimum.x * bias.x + bias.y;
  4731. minimum.y -= minimum.y * bias.x + bias.y;
  4732. maximum.x += maximum.x * bias.x + bias.y;
  4733. maximum.y += maximum.y * bias.x + bias.y;
  4734. }
  4735. return {
  4736. minimum: minimum,
  4737. maximum: maximum
  4738. };
  4739. };
  4740. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4741. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4742. return undefined;
  4743. return Array.isArray(obj) ? obj : [obj];
  4744. };
  4745. // Misc.
  4746. Tools.GetPointerPrefix = function () {
  4747. var eventPrefix = "pointer";
  4748. // Check if pointer events are supported
  4749. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4750. eventPrefix = "mouse";
  4751. }
  4752. return eventPrefix;
  4753. };
  4754. /**
  4755. * @param func - the function to be called
  4756. * @param requester - the object that will request the next frame. Falls back to window.
  4757. */
  4758. Tools.QueueNewFrame = function (func, requester) {
  4759. if (requester === void 0) { requester = window; }
  4760. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4761. /*if(requester.isPresenting) {
  4762. return;
  4763. } else*/ if (requester.requestAnimationFrame)
  4764. requester.requestAnimationFrame(func);
  4765. else if (requester.msRequestAnimationFrame)
  4766. requester.msRequestAnimationFrame(func);
  4767. else if (requester.webkitRequestAnimationFrame)
  4768. requester.webkitRequestAnimationFrame(func);
  4769. else if (requester.mozRequestAnimationFrame)
  4770. requester.mozRequestAnimationFrame(func);
  4771. else if (requester.oRequestAnimationFrame)
  4772. requester.oRequestAnimationFrame(func);
  4773. else {
  4774. window.setTimeout(func, 16);
  4775. }
  4776. };
  4777. Tools.RequestFullscreen = function (element) {
  4778. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4779. if (!requestFunction)
  4780. return;
  4781. requestFunction.call(element);
  4782. };
  4783. Tools.ExitFullscreen = function () {
  4784. if (document.exitFullscreen) {
  4785. document.exitFullscreen();
  4786. }
  4787. else if (document.mozCancelFullScreen) {
  4788. document.mozCancelFullScreen();
  4789. }
  4790. else if (document.webkitCancelFullScreen) {
  4791. document.webkitCancelFullScreen();
  4792. }
  4793. else if (document.msCancelFullScreen) {
  4794. document.msCancelFullScreen();
  4795. }
  4796. };
  4797. Tools.SetCorsBehavior = function (url, img) {
  4798. if (Tools.CorsBehavior) {
  4799. switch (typeof (Tools.CorsBehavior)) {
  4800. case "function":
  4801. var result = Tools.CorsBehavior(url);
  4802. if (result) {
  4803. return result;
  4804. }
  4805. break;
  4806. case "string":
  4807. default:
  4808. img.crossOrigin = Tools.CorsBehavior;
  4809. break;
  4810. }
  4811. }
  4812. };
  4813. // External files
  4814. Tools.CleanUrl = function (url) {
  4815. url = url.replace(/#/mg, "%23");
  4816. return url;
  4817. };
  4818. Tools.LoadImage = function (url, onload, onerror, database) {
  4819. if (url instanceof ArrayBuffer) {
  4820. url = Tools.EncodeArrayBufferTobase64(url);
  4821. }
  4822. url = Tools.CleanUrl(url);
  4823. var img = new Image();
  4824. if (url.substr(0, 5) !== "data:") {
  4825. Tools.SetCorsBehavior(url, img);
  4826. }
  4827. img.onload = function () {
  4828. onload(img);
  4829. };
  4830. img.onerror = function (err) {
  4831. Tools.Error("Error while trying to load texture: " + url);
  4832. if (Tools.UseFallbackTexture) {
  4833. 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";
  4834. onload(img);
  4835. }
  4836. else {
  4837. onerror();
  4838. }
  4839. };
  4840. var noIndexedDB = function () {
  4841. img.src = url;
  4842. };
  4843. var loadFromIndexedDB = function () {
  4844. database.loadImageFromDB(url, img);
  4845. };
  4846. //ANY database to do!
  4847. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4848. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4849. }
  4850. else {
  4851. if (url.indexOf("file:") === -1) {
  4852. noIndexedDB();
  4853. }
  4854. else {
  4855. try {
  4856. var textureName = url.substring(5).toLowerCase();
  4857. var blobURL;
  4858. try {
  4859. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4860. }
  4861. catch (ex) {
  4862. // Chrome doesn't support oneTimeOnly parameter
  4863. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4864. }
  4865. img.src = blobURL;
  4866. }
  4867. catch (e) {
  4868. img.src = null;
  4869. }
  4870. }
  4871. }
  4872. return img;
  4873. };
  4874. //ANY
  4875. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4876. url = Tools.CleanUrl(url);
  4877. var noIndexedDB = function () {
  4878. var request = new XMLHttpRequest();
  4879. var loadUrl = Tools.BaseUrl + url;
  4880. request.open('GET', loadUrl, true);
  4881. if (useArrayBuffer) {
  4882. request.responseType = "arraybuffer";
  4883. }
  4884. request.onprogress = progressCallBack;
  4885. request.onreadystatechange = function () {
  4886. if (request.readyState === 4) {
  4887. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4888. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4889. callback(!useArrayBuffer ? request.responseText : request.response);
  4890. }
  4891. else {
  4892. if (onError) {
  4893. onError();
  4894. }
  4895. else {
  4896. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4897. }
  4898. }
  4899. }
  4900. };
  4901. request.send(null);
  4902. };
  4903. var loadFromIndexedDB = function () {
  4904. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4905. };
  4906. if (url.indexOf("file:") !== -1) {
  4907. var fileName = url.substring(5).toLowerCase();
  4908. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4909. }
  4910. else {
  4911. // Caching all files
  4912. if (database && database.enableSceneOffline) {
  4913. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4914. }
  4915. else {
  4916. noIndexedDB();
  4917. }
  4918. }
  4919. };
  4920. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4921. var reader = new FileReader();
  4922. reader.onload = function (e) {
  4923. //target doesn't have result from ts 1.3
  4924. callback(e.target['result']);
  4925. };
  4926. reader.onprogress = progressCallback;
  4927. reader.readAsDataURL(fileToLoad);
  4928. };
  4929. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4930. var reader = new FileReader();
  4931. reader.onerror = function (e) {
  4932. Tools.Log("Error while reading file: " + fileToLoad.name);
  4933. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4934. };
  4935. reader.onload = function (e) {
  4936. //target doesn't have result from ts 1.3
  4937. callback(e.target['result']);
  4938. };
  4939. reader.onprogress = progressCallBack;
  4940. if (!useArrayBuffer) {
  4941. // Asynchronous read
  4942. reader.readAsText(fileToLoad);
  4943. }
  4944. else {
  4945. reader.readAsArrayBuffer(fileToLoad);
  4946. }
  4947. };
  4948. //returns a downloadable url to a file content.
  4949. Tools.FileAsURL = function (content) {
  4950. var fileBlob = new Blob([content]);
  4951. var url = window.URL || window.webkitURL;
  4952. var link = url.createObjectURL(fileBlob);
  4953. return link;
  4954. };
  4955. // Misc.
  4956. Tools.Format = function (value, decimals) {
  4957. if (decimals === void 0) { decimals = 2; }
  4958. return value.toFixed(decimals);
  4959. };
  4960. Tools.CheckExtends = function (v, min, max) {
  4961. if (v.x < min.x)
  4962. min.x = v.x;
  4963. if (v.y < min.y)
  4964. min.y = v.y;
  4965. if (v.z < min.z)
  4966. min.z = v.z;
  4967. if (v.x > max.x)
  4968. max.x = v.x;
  4969. if (v.y > max.y)
  4970. max.y = v.y;
  4971. if (v.z > max.z)
  4972. max.z = v.z;
  4973. };
  4974. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4975. for (var prop in source) {
  4976. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4977. continue;
  4978. }
  4979. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4980. continue;
  4981. }
  4982. var sourceValue = source[prop];
  4983. var typeOfSourceValue = typeof sourceValue;
  4984. if (typeOfSourceValue === "function") {
  4985. continue;
  4986. }
  4987. if (typeOfSourceValue === "object") {
  4988. if (sourceValue instanceof Array) {
  4989. destination[prop] = [];
  4990. if (sourceValue.length > 0) {
  4991. if (typeof sourceValue[0] == "object") {
  4992. for (var index = 0; index < sourceValue.length; index++) {
  4993. var clonedValue = cloneValue(sourceValue[index], destination);
  4994. if (destination[prop].indexOf(clonedValue) === -1) {
  4995. destination[prop].push(clonedValue);
  4996. }
  4997. }
  4998. }
  4999. else {
  5000. destination[prop] = sourceValue.slice(0);
  5001. }
  5002. }
  5003. }
  5004. else {
  5005. destination[prop] = cloneValue(sourceValue, destination);
  5006. }
  5007. }
  5008. else {
  5009. destination[prop] = sourceValue;
  5010. }
  5011. }
  5012. };
  5013. Tools.IsEmpty = function (obj) {
  5014. for (var i in obj) {
  5015. return false;
  5016. }
  5017. return true;
  5018. };
  5019. Tools.RegisterTopRootEvents = function (events) {
  5020. for (var index = 0; index < events.length; index++) {
  5021. var event = events[index];
  5022. window.addEventListener(event.name, event.handler, false);
  5023. try {
  5024. if (window.parent) {
  5025. window.parent.addEventListener(event.name, event.handler, false);
  5026. }
  5027. }
  5028. catch (e) {
  5029. }
  5030. }
  5031. };
  5032. Tools.UnregisterTopRootEvents = function (events) {
  5033. for (var index = 0; index < events.length; index++) {
  5034. var event = events[index];
  5035. window.removeEventListener(event.name, event.handler);
  5036. try {
  5037. if (window.parent) {
  5038. window.parent.removeEventListener(event.name, event.handler);
  5039. }
  5040. }
  5041. catch (e) {
  5042. }
  5043. }
  5044. };
  5045. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5046. if (mimeType === void 0) { mimeType = "image/png"; }
  5047. // Read the contents of the framebuffer
  5048. var numberOfChannelsByLine = width * 4;
  5049. var halfHeight = height / 2;
  5050. //Reading datas from WebGL
  5051. var data = engine.readPixels(0, 0, width, height);
  5052. //To flip image on Y axis.
  5053. for (var i = 0; i < halfHeight; i++) {
  5054. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5055. var currentCell = j + i * numberOfChannelsByLine;
  5056. var targetLine = height - i - 1;
  5057. var targetCell = j + targetLine * numberOfChannelsByLine;
  5058. var temp = data[currentCell];
  5059. data[currentCell] = data[targetCell];
  5060. data[targetCell] = temp;
  5061. }
  5062. }
  5063. // Create a 2D canvas to store the result
  5064. if (!screenshotCanvas) {
  5065. screenshotCanvas = document.createElement('canvas');
  5066. }
  5067. screenshotCanvas.width = width;
  5068. screenshotCanvas.height = height;
  5069. var context = screenshotCanvas.getContext('2d');
  5070. // Copy the pixels to a 2D canvas
  5071. var imageData = context.createImageData(width, height);
  5072. var castData = (imageData.data);
  5073. castData.set(data);
  5074. context.putImageData(imageData, 0, 0);
  5075. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5076. };
  5077. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5078. if (mimeType === void 0) { mimeType = "image/png"; }
  5079. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5080. if (successCallback) {
  5081. successCallback(base64Image);
  5082. }
  5083. else {
  5084. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5085. if (("download" in document.createElement("a"))) {
  5086. var a = window.document.createElement("a");
  5087. a.href = base64Image;
  5088. var date = new Date();
  5089. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5090. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5091. window.document.body.appendChild(a);
  5092. a.addEventListener("click", function () {
  5093. a.parentElement.removeChild(a);
  5094. });
  5095. a.click();
  5096. }
  5097. else {
  5098. var newWindow = window.open("");
  5099. var img = newWindow.document.createElement("img");
  5100. img.src = base64Image;
  5101. newWindow.document.body.appendChild(img);
  5102. }
  5103. }
  5104. };
  5105. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5106. if (mimeType === void 0) { mimeType = "image/png"; }
  5107. var width;
  5108. var height;
  5109. // If a precision value is specified
  5110. if (size.precision) {
  5111. width = Math.round(engine.getRenderWidth() * size.precision);
  5112. height = Math.round(width / engine.getAspectRatio(camera));
  5113. }
  5114. else if (size.width && size.height) {
  5115. width = size.width;
  5116. height = size.height;
  5117. }
  5118. else if (size.width && !size.height) {
  5119. width = size.width;
  5120. height = Math.round(width / engine.getAspectRatio(camera));
  5121. }
  5122. else if (size.height && !size.width) {
  5123. height = size.height;
  5124. width = Math.round(height * engine.getAspectRatio(camera));
  5125. }
  5126. else if (!isNaN(size)) {
  5127. height = size;
  5128. width = size;
  5129. }
  5130. else {
  5131. Tools.Error("Invalid 'size' parameter !");
  5132. return;
  5133. }
  5134. if (!screenshotCanvas) {
  5135. screenshotCanvas = document.createElement('canvas');
  5136. }
  5137. screenshotCanvas.width = width;
  5138. screenshotCanvas.height = height;
  5139. var renderContext = screenshotCanvas.getContext("2d");
  5140. renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
  5141. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5142. };
  5143. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5144. if (mimeType === void 0) { mimeType = "image/png"; }
  5145. var width;
  5146. var height;
  5147. //If a precision value is specified
  5148. if (size.precision) {
  5149. width = Math.round(engine.getRenderWidth() * size.precision);
  5150. height = Math.round(width / engine.getAspectRatio(camera));
  5151. size = { width: width, height: height };
  5152. }
  5153. else if (size.width && size.height) {
  5154. width = size.width;
  5155. height = size.height;
  5156. }
  5157. else if (size.width && !size.height) {
  5158. width = size.width;
  5159. height = Math.round(width / engine.getAspectRatio(camera));
  5160. size = { width: width, height: height };
  5161. }
  5162. else if (size.height && !size.width) {
  5163. height = size.height;
  5164. width = Math.round(height * engine.getAspectRatio(camera));
  5165. size = { width: width, height: height };
  5166. }
  5167. else if (!isNaN(size)) {
  5168. height = size;
  5169. width = size;
  5170. }
  5171. else {
  5172. Tools.Error("Invalid 'size' parameter !");
  5173. return;
  5174. }
  5175. var scene = camera.getScene();
  5176. var previousCamera = null;
  5177. if (scene.activeCamera !== camera) {
  5178. previousCamera = scene.activeCamera;
  5179. scene.activeCamera = camera;
  5180. }
  5181. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5182. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5183. texture.renderList = scene.meshes;
  5184. texture.onAfterRenderObservable.add(function () {
  5185. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5186. });
  5187. scene.incrementRenderId();
  5188. scene.resetCachedMaterial();
  5189. texture.render(true);
  5190. texture.dispose();
  5191. if (previousCamera) {
  5192. scene.activeCamera = previousCamera;
  5193. }
  5194. camera.getProjectionMatrix(true); // Force cache refresh;
  5195. };
  5196. // XHR response validator for local file scenario
  5197. Tools.ValidateXHRData = function (xhr, dataType) {
  5198. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5199. if (dataType === void 0) { dataType = 7; }
  5200. try {
  5201. if (dataType & 1) {
  5202. if (xhr.responseText && xhr.responseText.length > 0) {
  5203. return true;
  5204. }
  5205. else if (dataType === 1) {
  5206. return false;
  5207. }
  5208. }
  5209. if (dataType & 2) {
  5210. // Check header width and height since there is no "TGA" magic number
  5211. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5212. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5213. return true;
  5214. }
  5215. else if (dataType === 2) {
  5216. return false;
  5217. }
  5218. }
  5219. if (dataType & 4) {
  5220. // Check for the "DDS" magic number
  5221. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5222. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5223. return true;
  5224. }
  5225. else {
  5226. return false;
  5227. }
  5228. }
  5229. }
  5230. catch (e) {
  5231. }
  5232. return false;
  5233. };
  5234. /**
  5235. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5236. * Be aware Math.random() could cause collisions, but:
  5237. * "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"
  5238. */
  5239. Tools.RandomId = function () {
  5240. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5241. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5242. return v.toString(16);
  5243. });
  5244. };
  5245. Object.defineProperty(Tools, "NoneLogLevel", {
  5246. get: function () {
  5247. return Tools._NoneLogLevel;
  5248. },
  5249. enumerable: true,
  5250. configurable: true
  5251. });
  5252. Object.defineProperty(Tools, "MessageLogLevel", {
  5253. get: function () {
  5254. return Tools._MessageLogLevel;
  5255. },
  5256. enumerable: true,
  5257. configurable: true
  5258. });
  5259. Object.defineProperty(Tools, "WarningLogLevel", {
  5260. get: function () {
  5261. return Tools._WarningLogLevel;
  5262. },
  5263. enumerable: true,
  5264. configurable: true
  5265. });
  5266. Object.defineProperty(Tools, "ErrorLogLevel", {
  5267. get: function () {
  5268. return Tools._ErrorLogLevel;
  5269. },
  5270. enumerable: true,
  5271. configurable: true
  5272. });
  5273. Object.defineProperty(Tools, "AllLogLevel", {
  5274. get: function () {
  5275. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5276. },
  5277. enumerable: true,
  5278. configurable: true
  5279. });
  5280. Tools._AddLogEntry = function (entry) {
  5281. Tools._LogCache = entry + Tools._LogCache;
  5282. if (Tools.OnNewCacheEntry) {
  5283. Tools.OnNewCacheEntry(entry);
  5284. }
  5285. };
  5286. Tools._FormatMessage = function (message) {
  5287. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5288. var date = new Date();
  5289. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5290. };
  5291. Tools._LogDisabled = function (message) {
  5292. // nothing to do
  5293. };
  5294. Tools._LogEnabled = function (message) {
  5295. var formattedMessage = Tools._FormatMessage(message);
  5296. console.log("BJS - " + formattedMessage);
  5297. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5298. Tools._AddLogEntry(entry);
  5299. };
  5300. Tools._WarnDisabled = function (message) {
  5301. // nothing to do
  5302. };
  5303. Tools._WarnEnabled = function (message) {
  5304. var formattedMessage = Tools._FormatMessage(message);
  5305. console.warn("BJS - " + formattedMessage);
  5306. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5307. Tools._AddLogEntry(entry);
  5308. };
  5309. Tools._ErrorDisabled = function (message) {
  5310. // nothing to do
  5311. };
  5312. Tools._ErrorEnabled = function (message) {
  5313. Tools.errorsCount++;
  5314. var formattedMessage = Tools._FormatMessage(message);
  5315. console.error("BJS - " + formattedMessage);
  5316. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5317. Tools._AddLogEntry(entry);
  5318. };
  5319. Object.defineProperty(Tools, "LogCache", {
  5320. get: function () {
  5321. return Tools._LogCache;
  5322. },
  5323. enumerable: true,
  5324. configurable: true
  5325. });
  5326. Tools.ClearLogCache = function () {
  5327. Tools._LogCache = "";
  5328. Tools.errorsCount = 0;
  5329. };
  5330. Object.defineProperty(Tools, "LogLevels", {
  5331. set: function (level) {
  5332. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5333. Tools.Log = Tools._LogEnabled;
  5334. }
  5335. else {
  5336. Tools.Log = Tools._LogDisabled;
  5337. }
  5338. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5339. Tools.Warn = Tools._WarnEnabled;
  5340. }
  5341. else {
  5342. Tools.Warn = Tools._WarnDisabled;
  5343. }
  5344. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5345. Tools.Error = Tools._ErrorEnabled;
  5346. }
  5347. else {
  5348. Tools.Error = Tools._ErrorDisabled;
  5349. }
  5350. },
  5351. enumerable: true,
  5352. configurable: true
  5353. });
  5354. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5355. get: function () {
  5356. return Tools._PerformanceNoneLogLevel;
  5357. },
  5358. enumerable: true,
  5359. configurable: true
  5360. });
  5361. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5362. get: function () {
  5363. return Tools._PerformanceUserMarkLogLevel;
  5364. },
  5365. enumerable: true,
  5366. configurable: true
  5367. });
  5368. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5369. get: function () {
  5370. return Tools._PerformanceConsoleLogLevel;
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5376. set: function (level) {
  5377. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5378. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5379. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5380. return;
  5381. }
  5382. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5383. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5384. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5385. return;
  5386. }
  5387. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5388. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5389. },
  5390. enumerable: true,
  5391. configurable: true
  5392. });
  5393. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5394. };
  5395. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5396. };
  5397. Tools._StartUserMark = function (counterName, condition) {
  5398. if (condition === void 0) { condition = true; }
  5399. if (!condition || !Tools._performance.mark) {
  5400. return;
  5401. }
  5402. Tools._performance.mark(counterName + "-Begin");
  5403. };
  5404. Tools._EndUserMark = function (counterName, condition) {
  5405. if (condition === void 0) { condition = true; }
  5406. if (!condition || !Tools._performance.mark) {
  5407. return;
  5408. }
  5409. Tools._performance.mark(counterName + "-End");
  5410. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5411. };
  5412. Tools._StartPerformanceConsole = function (counterName, condition) {
  5413. if (condition === void 0) { condition = true; }
  5414. if (!condition) {
  5415. return;
  5416. }
  5417. Tools._StartUserMark(counterName, condition);
  5418. if (console.time) {
  5419. console.time(counterName);
  5420. }
  5421. };
  5422. Tools._EndPerformanceConsole = function (counterName, condition) {
  5423. if (condition === void 0) { condition = true; }
  5424. if (!condition) {
  5425. return;
  5426. }
  5427. Tools._EndUserMark(counterName, condition);
  5428. if (console.time) {
  5429. console.timeEnd(counterName);
  5430. }
  5431. };
  5432. Object.defineProperty(Tools, "Now", {
  5433. get: function () {
  5434. if (window.performance && window.performance.now) {
  5435. return window.performance.now();
  5436. }
  5437. return new Date().getTime();
  5438. },
  5439. enumerable: true,
  5440. configurable: true
  5441. });
  5442. /**
  5443. * This method will return the name of the class used to create the instance of the given object.
  5444. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5445. * @param object the object to get the class name from
  5446. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5447. */
  5448. Tools.getClassName = function (object, isType) {
  5449. if (isType === void 0) { isType = false; }
  5450. var name = null;
  5451. if (!isType && object.getClassName) {
  5452. name = object.getClassName();
  5453. }
  5454. else {
  5455. if (object instanceof Object) {
  5456. var classObj = isType ? object : Object.getPrototypeOf(object);
  5457. name = classObj.constructor["__bjsclassName__"];
  5458. }
  5459. if (!name) {
  5460. name = typeof object;
  5461. }
  5462. }
  5463. return name;
  5464. };
  5465. Tools.first = function (array, predicate) {
  5466. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5467. var el = array_1[_i];
  5468. if (predicate(el)) {
  5469. return el;
  5470. }
  5471. }
  5472. };
  5473. /**
  5474. * This method will return the name of the full name of the class, including its owning module (if any).
  5475. * 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).
  5476. * @param object the object to get the class name from
  5477. * @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.
  5478. */
  5479. Tools.getFullClassName = function (object, isType) {
  5480. if (isType === void 0) { isType = false; }
  5481. var className = null;
  5482. var moduleName = null;
  5483. if (!isType && object.getClassName) {
  5484. className = object.getClassName();
  5485. }
  5486. else {
  5487. if (object instanceof Object) {
  5488. var classObj = isType ? object : Object.getPrototypeOf(object);
  5489. className = classObj.constructor["__bjsclassName__"];
  5490. moduleName = classObj.constructor["__bjsmoduleName__"];
  5491. }
  5492. if (!className) {
  5493. className = typeof object;
  5494. }
  5495. }
  5496. if (!className) {
  5497. return null;
  5498. }
  5499. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5500. };
  5501. /**
  5502. * 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.
  5503. * @param array
  5504. */
  5505. Tools.arrayOrStringFeeder = function (array) {
  5506. return function (index) {
  5507. if (index >= array.length) {
  5508. return null;
  5509. }
  5510. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5511. if (val && val.getHashCode) {
  5512. val = val.getHashCode();
  5513. }
  5514. if (typeof val === "string") {
  5515. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5516. }
  5517. return val;
  5518. };
  5519. };
  5520. /**
  5521. * Compute the hashCode of a stream of number
  5522. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5523. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5524. * @return the hash code computed
  5525. */
  5526. Tools.hashCodeFromStream = function (feeder) {
  5527. // Based from here: http://stackoverflow.com/a/7616484/802124
  5528. var hash = 0;
  5529. var index = 0;
  5530. var chr = feeder(index++);
  5531. while (chr != null) {
  5532. hash = ((hash << 5) - hash) + chr;
  5533. hash |= 0; // Convert to 32bit integer
  5534. chr = feeder(index++);
  5535. }
  5536. return hash;
  5537. };
  5538. Tools.BaseUrl = "";
  5539. Tools.CorsBehavior = "anonymous";
  5540. Tools.UseFallbackTexture = true;
  5541. // Logs
  5542. Tools._NoneLogLevel = 0;
  5543. Tools._MessageLogLevel = 1;
  5544. Tools._WarningLogLevel = 2;
  5545. Tools._ErrorLogLevel = 4;
  5546. Tools._LogCache = "";
  5547. Tools.errorsCount = 0;
  5548. Tools.Log = Tools._LogEnabled;
  5549. Tools.Warn = Tools._WarnEnabled;
  5550. Tools.Error = Tools._ErrorEnabled;
  5551. // Performances
  5552. Tools._PerformanceNoneLogLevel = 0;
  5553. Tools._PerformanceUserMarkLogLevel = 1;
  5554. Tools._PerformanceConsoleLogLevel = 2;
  5555. Tools._performance = window.performance;
  5556. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5557. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5558. return Tools;
  5559. }());
  5560. BABYLON.Tools = Tools;
  5561. /**
  5562. * This class is used to track a performance counter which is number based.
  5563. * The user has access to many properties which give statistics of different nature
  5564. *
  5565. * The implementer can track two kinds of Performance Counter: time and count
  5566. * 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.
  5567. * 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.
  5568. */
  5569. var PerfCounter = (function () {
  5570. function PerfCounter() {
  5571. this._startMonitoringTime = 0;
  5572. this._min = 0;
  5573. this._max = 0;
  5574. this._average = 0;
  5575. this._lastSecAverage = 0;
  5576. this._current = 0;
  5577. this._totalValueCount = 0;
  5578. this._totalAccumulated = 0;
  5579. this._lastSecAccumulated = 0;
  5580. this._lastSecTime = 0;
  5581. this._lastSecValueCount = 0;
  5582. }
  5583. Object.defineProperty(PerfCounter.prototype, "min", {
  5584. /**
  5585. * Returns the smallest value ever
  5586. */
  5587. get: function () {
  5588. return this._min;
  5589. },
  5590. enumerable: true,
  5591. configurable: true
  5592. });
  5593. Object.defineProperty(PerfCounter.prototype, "max", {
  5594. /**
  5595. * Returns the biggest value ever
  5596. */
  5597. get: function () {
  5598. return this._max;
  5599. },
  5600. enumerable: true,
  5601. configurable: true
  5602. });
  5603. Object.defineProperty(PerfCounter.prototype, "average", {
  5604. /**
  5605. * Returns the average value since the performance counter is running
  5606. */
  5607. get: function () {
  5608. return this._average;
  5609. },
  5610. enumerable: true,
  5611. configurable: true
  5612. });
  5613. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5614. /**
  5615. * Returns the average value of the last second the counter was monitored
  5616. */
  5617. get: function () {
  5618. return this._lastSecAverage;
  5619. },
  5620. enumerable: true,
  5621. configurable: true
  5622. });
  5623. Object.defineProperty(PerfCounter.prototype, "current", {
  5624. /**
  5625. * Returns the current value
  5626. */
  5627. get: function () {
  5628. return this._current;
  5629. },
  5630. enumerable: true,
  5631. configurable: true
  5632. });
  5633. Object.defineProperty(PerfCounter.prototype, "total", {
  5634. get: function () {
  5635. return this._totalAccumulated;
  5636. },
  5637. enumerable: true,
  5638. configurable: true
  5639. });
  5640. /**
  5641. * Call this method to start monitoring a new frame.
  5642. * 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.
  5643. */
  5644. PerfCounter.prototype.fetchNewFrame = function () {
  5645. this._totalValueCount++;
  5646. this._current = 0;
  5647. this._lastSecValueCount++;
  5648. };
  5649. /**
  5650. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5651. * @param newCount the count value to add to the monitored count
  5652. * @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.
  5653. */
  5654. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5655. this._current += newCount;
  5656. if (fetchResult) {
  5657. this._fetchResult();
  5658. }
  5659. };
  5660. /**
  5661. * Start monitoring this performance counter
  5662. */
  5663. PerfCounter.prototype.beginMonitoring = function () {
  5664. this._startMonitoringTime = Tools.Now;
  5665. };
  5666. /**
  5667. * Compute the time lapsed since the previous beginMonitoring() call.
  5668. * @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
  5669. */
  5670. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5671. if (newFrame === void 0) { newFrame = true; }
  5672. if (newFrame) {
  5673. this.fetchNewFrame();
  5674. }
  5675. var currentTime = Tools.Now;
  5676. this._current = currentTime - this._startMonitoringTime;
  5677. if (newFrame) {
  5678. this._fetchResult();
  5679. }
  5680. };
  5681. PerfCounter.prototype._fetchResult = function () {
  5682. this._totalAccumulated += this._current;
  5683. this._lastSecAccumulated += this._current;
  5684. // Min/Max update
  5685. this._min = Math.min(this._min, this._current);
  5686. this._max = Math.max(this._max, this._current);
  5687. this._average = this._totalAccumulated / this._totalValueCount;
  5688. // Reset last sec?
  5689. var now = Tools.Now;
  5690. if ((now - this._lastSecTime) > 1000) {
  5691. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5692. this._lastSecTime = now;
  5693. this._lastSecAccumulated = 0;
  5694. this._lastSecValueCount = 0;
  5695. }
  5696. };
  5697. return PerfCounter;
  5698. }());
  5699. BABYLON.PerfCounter = PerfCounter;
  5700. /**
  5701. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5702. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5703. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5704. * @param name The name of the class, case should be preserved
  5705. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5706. */
  5707. function className(name, module) {
  5708. return function (target) {
  5709. target["__bjsclassName__"] = name;
  5710. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5711. };
  5712. }
  5713. BABYLON.className = className;
  5714. /**
  5715. * An implementation of a loop for asynchronous functions.
  5716. */
  5717. var AsyncLoop = (function () {
  5718. /**
  5719. * Constroctor.
  5720. * @param iterations the number of iterations.
  5721. * @param _fn the function to run each iteration
  5722. * @param _successCallback the callback that will be called upon succesful execution
  5723. * @param offset starting offset.
  5724. */
  5725. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5726. if (offset === void 0) { offset = 0; }
  5727. this.iterations = iterations;
  5728. this._fn = _fn;
  5729. this._successCallback = _successCallback;
  5730. this.index = offset - 1;
  5731. this._done = false;
  5732. }
  5733. /**
  5734. * Execute the next iteration. Must be called after the last iteration was finished.
  5735. */
  5736. AsyncLoop.prototype.executeNext = function () {
  5737. if (!this._done) {
  5738. if (this.index + 1 < this.iterations) {
  5739. ++this.index;
  5740. this._fn(this);
  5741. }
  5742. else {
  5743. this.breakLoop();
  5744. }
  5745. }
  5746. };
  5747. /**
  5748. * Break the loop and run the success callback.
  5749. */
  5750. AsyncLoop.prototype.breakLoop = function () {
  5751. this._done = true;
  5752. this._successCallback();
  5753. };
  5754. /**
  5755. * Helper function
  5756. */
  5757. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5758. if (offset === void 0) { offset = 0; }
  5759. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5760. loop.executeNext();
  5761. return loop;
  5762. };
  5763. /**
  5764. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5765. * @param iterations total number of iterations
  5766. * @param syncedIterations number of synchronous iterations in each async iteration.
  5767. * @param fn the function to call each iteration.
  5768. * @param callback a success call back that will be called when iterating stops.
  5769. * @param breakFunction a break condition (optional)
  5770. * @param timeout timeout settings for the setTimeout function. default - 0.
  5771. * @constructor
  5772. */
  5773. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5774. if (timeout === void 0) { timeout = 0; }
  5775. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5776. if (breakFunction && breakFunction())
  5777. loop.breakLoop();
  5778. else {
  5779. setTimeout(function () {
  5780. for (var i = 0; i < syncedIterations; ++i) {
  5781. var iteration = (loop.index * syncedIterations) + i;
  5782. if (iteration >= iterations)
  5783. break;
  5784. fn(iteration);
  5785. if (breakFunction && breakFunction()) {
  5786. loop.breakLoop();
  5787. break;
  5788. }
  5789. }
  5790. loop.executeNext();
  5791. }, timeout);
  5792. }
  5793. }, callback);
  5794. };
  5795. return AsyncLoop;
  5796. }());
  5797. BABYLON.AsyncLoop = AsyncLoop;
  5798. })(BABYLON || (BABYLON = {}));
  5799. var BABYLON;
  5800. (function (BABYLON) {
  5801. var Internals;
  5802. (function (Internals) {
  5803. var _AlphaState = (function () {
  5804. function _AlphaState() {
  5805. this._isAlphaBlendDirty = false;
  5806. this._isBlendFunctionParametersDirty = false;
  5807. this._alphaBlend = false;
  5808. this._blendFunctionParameters = new Array(4);
  5809. }
  5810. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5811. get: function () {
  5812. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5813. },
  5814. enumerable: true,
  5815. configurable: true
  5816. });
  5817. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5818. get: function () {
  5819. return this._alphaBlend;
  5820. },
  5821. set: function (value) {
  5822. if (this._alphaBlend === value) {
  5823. return;
  5824. }
  5825. this._alphaBlend = value;
  5826. this._isAlphaBlendDirty = true;
  5827. },
  5828. enumerable: true,
  5829. configurable: true
  5830. });
  5831. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5832. if (this._blendFunctionParameters[0] === value0 &&
  5833. this._blendFunctionParameters[1] === value1 &&
  5834. this._blendFunctionParameters[2] === value2 &&
  5835. this._blendFunctionParameters[3] === value3) {
  5836. return;
  5837. }
  5838. this._blendFunctionParameters[0] = value0;
  5839. this._blendFunctionParameters[1] = value1;
  5840. this._blendFunctionParameters[2] = value2;
  5841. this._blendFunctionParameters[3] = value3;
  5842. this._isBlendFunctionParametersDirty = true;
  5843. };
  5844. _AlphaState.prototype.reset = function () {
  5845. this._alphaBlend = false;
  5846. this._blendFunctionParameters[0] = null;
  5847. this._blendFunctionParameters[1] = null;
  5848. this._blendFunctionParameters[2] = null;
  5849. this._blendFunctionParameters[3] = null;
  5850. this._isAlphaBlendDirty = true;
  5851. this._isBlendFunctionParametersDirty = false;
  5852. };
  5853. _AlphaState.prototype.apply = function (gl) {
  5854. if (!this.isDirty) {
  5855. return;
  5856. }
  5857. // Alpha blend
  5858. if (this._isAlphaBlendDirty) {
  5859. if (this._alphaBlend) {
  5860. gl.enable(gl.BLEND);
  5861. }
  5862. else {
  5863. gl.disable(gl.BLEND);
  5864. }
  5865. this._isAlphaBlendDirty = false;
  5866. }
  5867. // Alpha function
  5868. if (this._isBlendFunctionParametersDirty) {
  5869. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5870. this._isBlendFunctionParametersDirty = false;
  5871. }
  5872. };
  5873. return _AlphaState;
  5874. }());
  5875. Internals._AlphaState = _AlphaState;
  5876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5877. })(BABYLON || (BABYLON = {}));
  5878. var BABYLON;
  5879. (function (BABYLON) {
  5880. var Internals;
  5881. (function (Internals) {
  5882. var _DepthCullingState = (function () {
  5883. function _DepthCullingState() {
  5884. this._isDepthTestDirty = false;
  5885. this._isDepthMaskDirty = false;
  5886. this._isDepthFuncDirty = false;
  5887. this._isCullFaceDirty = false;
  5888. this._isCullDirty = false;
  5889. this._isZOffsetDirty = false;
  5890. }
  5891. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5892. get: function () {
  5893. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5894. },
  5895. enumerable: true,
  5896. configurable: true
  5897. });
  5898. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5899. get: function () {
  5900. return this._zOffset;
  5901. },
  5902. set: function (value) {
  5903. if (this._zOffset === value) {
  5904. return;
  5905. }
  5906. this._zOffset = value;
  5907. this._isZOffsetDirty = true;
  5908. },
  5909. enumerable: true,
  5910. configurable: true
  5911. });
  5912. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5913. get: function () {
  5914. return this._cullFace;
  5915. },
  5916. set: function (value) {
  5917. if (this._cullFace === value) {
  5918. return;
  5919. }
  5920. this._cullFace = value;
  5921. this._isCullFaceDirty = true;
  5922. },
  5923. enumerable: true,
  5924. configurable: true
  5925. });
  5926. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5927. get: function () {
  5928. return this._cull;
  5929. },
  5930. set: function (value) {
  5931. if (this._cull === value) {
  5932. return;
  5933. }
  5934. this._cull = value;
  5935. this._isCullDirty = true;
  5936. },
  5937. enumerable: true,
  5938. configurable: true
  5939. });
  5940. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5941. get: function () {
  5942. return this._depthFunc;
  5943. },
  5944. set: function (value) {
  5945. if (this._depthFunc === value) {
  5946. return;
  5947. }
  5948. this._depthFunc = value;
  5949. this._isDepthFuncDirty = true;
  5950. },
  5951. enumerable: true,
  5952. configurable: true
  5953. });
  5954. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5955. get: function () {
  5956. return this._depthMask;
  5957. },
  5958. set: function (value) {
  5959. if (this._depthMask === value) {
  5960. return;
  5961. }
  5962. this._depthMask = value;
  5963. this._isDepthMaskDirty = true;
  5964. },
  5965. enumerable: true,
  5966. configurable: true
  5967. });
  5968. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5969. get: function () {
  5970. return this._depthTest;
  5971. },
  5972. set: function (value) {
  5973. if (this._depthTest === value) {
  5974. return;
  5975. }
  5976. this._depthTest = value;
  5977. this._isDepthTestDirty = true;
  5978. },
  5979. enumerable: true,
  5980. configurable: true
  5981. });
  5982. _DepthCullingState.prototype.reset = function () {
  5983. this._depthMask = true;
  5984. this._depthTest = true;
  5985. this._depthFunc = null;
  5986. this._cullFace = null;
  5987. this._cull = null;
  5988. this._zOffset = 0;
  5989. this._isDepthTestDirty = true;
  5990. this._isDepthMaskDirty = true;
  5991. this._isDepthFuncDirty = false;
  5992. this._isCullFaceDirty = false;
  5993. this._isCullDirty = false;
  5994. this._isZOffsetDirty = false;
  5995. };
  5996. _DepthCullingState.prototype.apply = function (gl) {
  5997. if (!this.isDirty) {
  5998. return;
  5999. }
  6000. // Cull
  6001. if (this._isCullDirty) {
  6002. if (this.cull) {
  6003. gl.enable(gl.CULL_FACE);
  6004. }
  6005. else {
  6006. gl.disable(gl.CULL_FACE);
  6007. }
  6008. this._isCullDirty = false;
  6009. }
  6010. // Cull face
  6011. if (this._isCullFaceDirty) {
  6012. gl.cullFace(this.cullFace);
  6013. this._isCullFaceDirty = false;
  6014. }
  6015. // Depth mask
  6016. if (this._isDepthMaskDirty) {
  6017. gl.depthMask(this.depthMask);
  6018. this._isDepthMaskDirty = false;
  6019. }
  6020. // Depth test
  6021. if (this._isDepthTestDirty) {
  6022. if (this.depthTest) {
  6023. gl.enable(gl.DEPTH_TEST);
  6024. }
  6025. else {
  6026. gl.disable(gl.DEPTH_TEST);
  6027. }
  6028. this._isDepthTestDirty = false;
  6029. }
  6030. // Depth func
  6031. if (this._isDepthFuncDirty) {
  6032. gl.depthFunc(this.depthFunc);
  6033. this._isDepthFuncDirty = false;
  6034. }
  6035. // zOffset
  6036. if (this._isZOffsetDirty) {
  6037. if (this.zOffset) {
  6038. gl.enable(gl.POLYGON_OFFSET_FILL);
  6039. gl.polygonOffset(this.zOffset, 0);
  6040. }
  6041. else {
  6042. gl.disable(gl.POLYGON_OFFSET_FILL);
  6043. }
  6044. this._isZOffsetDirty = false;
  6045. }
  6046. };
  6047. return _DepthCullingState;
  6048. }());
  6049. Internals._DepthCullingState = _DepthCullingState;
  6050. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6051. })(BABYLON || (BABYLON = {}));
  6052. var BABYLON;
  6053. (function (BABYLON) {
  6054. var Internals;
  6055. (function (Internals) {
  6056. var _StencilState = (function () {
  6057. function _StencilState() {
  6058. this._isStencilTestDirty = false;
  6059. this._isStencilMaskDirty = false;
  6060. this._isStencilFuncDirty = false;
  6061. this._isStencilOpDirty = false;
  6062. this.reset();
  6063. }
  6064. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6065. get: function () {
  6066. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6067. },
  6068. enumerable: true,
  6069. configurable: true
  6070. });
  6071. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6072. get: function () {
  6073. return this._stencilFunc;
  6074. },
  6075. set: function (value) {
  6076. if (this._stencilFunc === value) {
  6077. return;
  6078. }
  6079. this._stencilFunc = value;
  6080. this._isStencilFuncDirty = true;
  6081. },
  6082. enumerable: true,
  6083. configurable: true
  6084. });
  6085. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6086. get: function () {
  6087. return this._stencilFuncRef;
  6088. },
  6089. set: function (value) {
  6090. if (this._stencilFuncRef === value) {
  6091. return;
  6092. }
  6093. this._stencilFuncRef = value;
  6094. this._isStencilFuncDirty = true;
  6095. },
  6096. enumerable: true,
  6097. configurable: true
  6098. });
  6099. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6100. get: function () {
  6101. return this._stencilFuncMask;
  6102. },
  6103. set: function (value) {
  6104. if (this._stencilFuncMask === value) {
  6105. return;
  6106. }
  6107. this._stencilFuncMask = value;
  6108. this._isStencilFuncDirty = true;
  6109. },
  6110. enumerable: true,
  6111. configurable: true
  6112. });
  6113. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6114. get: function () {
  6115. return this._stencilOpStencilFail;
  6116. },
  6117. set: function (value) {
  6118. if (this._stencilOpStencilFail === value) {
  6119. return;
  6120. }
  6121. this._stencilOpStencilFail = value;
  6122. this._isStencilOpDirty = true;
  6123. },
  6124. enumerable: true,
  6125. configurable: true
  6126. });
  6127. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6128. get: function () {
  6129. return this._stencilOpDepthFail;
  6130. },
  6131. set: function (value) {
  6132. if (this._stencilOpDepthFail === value) {
  6133. return;
  6134. }
  6135. this._stencilOpDepthFail = value;
  6136. this._isStencilOpDirty = true;
  6137. },
  6138. enumerable: true,
  6139. configurable: true
  6140. });
  6141. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6142. get: function () {
  6143. return this._stencilOpStencilDepthPass;
  6144. },
  6145. set: function (value) {
  6146. if (this._stencilOpStencilDepthPass === value) {
  6147. return;
  6148. }
  6149. this._stencilOpStencilDepthPass = value;
  6150. this._isStencilOpDirty = true;
  6151. },
  6152. enumerable: true,
  6153. configurable: true
  6154. });
  6155. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6156. get: function () {
  6157. return this._stencilMask;
  6158. },
  6159. set: function (value) {
  6160. if (this._stencilMask === value) {
  6161. return;
  6162. }
  6163. this._stencilMask = value;
  6164. this._isStencilMaskDirty = true;
  6165. },
  6166. enumerable: true,
  6167. configurable: true
  6168. });
  6169. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6170. get: function () {
  6171. return this._stencilTest;
  6172. },
  6173. set: function (value) {
  6174. if (this._stencilTest === value) {
  6175. return;
  6176. }
  6177. this._stencilTest = value;
  6178. this._isStencilTestDirty = true;
  6179. },
  6180. enumerable: true,
  6181. configurable: true
  6182. });
  6183. _StencilState.prototype.reset = function () {
  6184. this._stencilTest = false;
  6185. this._stencilMask = 0xFF;
  6186. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6187. this._stencilFuncRef = 1;
  6188. this._stencilFuncMask = 0xFF;
  6189. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6190. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6191. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6192. this._isStencilTestDirty = true;
  6193. this._isStencilMaskDirty = true;
  6194. this._isStencilFuncDirty = true;
  6195. this._isStencilOpDirty = true;
  6196. };
  6197. _StencilState.prototype.apply = function (gl) {
  6198. if (!this.isDirty) {
  6199. return;
  6200. }
  6201. // Stencil test
  6202. if (this._isStencilTestDirty) {
  6203. if (this.stencilTest) {
  6204. gl.enable(gl.STENCIL_TEST);
  6205. }
  6206. else {
  6207. gl.disable(gl.STENCIL_TEST);
  6208. }
  6209. this._isStencilTestDirty = false;
  6210. }
  6211. // Stencil mask
  6212. if (this._isStencilMaskDirty) {
  6213. gl.stencilMask(this.stencilMask);
  6214. this._isStencilMaskDirty = false;
  6215. }
  6216. // Stencil func
  6217. if (this._isStencilFuncDirty) {
  6218. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6219. this._isStencilFuncDirty = false;
  6220. }
  6221. // Stencil op
  6222. if (this._isStencilOpDirty) {
  6223. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6224. this._isStencilOpDirty = false;
  6225. }
  6226. };
  6227. return _StencilState;
  6228. }());
  6229. Internals._StencilState = _StencilState;
  6230. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6231. })(BABYLON || (BABYLON = {}));
  6232. var BABYLON;
  6233. (function (BABYLON) {
  6234. var compileShader = function (gl, source, type, defines) {
  6235. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6236. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6237. gl.compileShader(shader);
  6238. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6239. throw new Error(gl.getShaderInfoLog(shader));
  6240. }
  6241. return shader;
  6242. };
  6243. var HALF_FLOAT_OES = 0x8D61;
  6244. var getWebGLTextureType = function (gl, type) {
  6245. if (type === Engine.TEXTURETYPE_FLOAT) {
  6246. return gl.FLOAT;
  6247. }
  6248. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6249. // Add Half Float Constant.
  6250. return HALF_FLOAT_OES;
  6251. }
  6252. return gl.UNSIGNED_BYTE;
  6253. };
  6254. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6255. var magFilter = gl.NEAREST;
  6256. var minFilter = gl.NEAREST;
  6257. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6258. magFilter = gl.LINEAR;
  6259. if (generateMipMaps) {
  6260. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6261. }
  6262. else {
  6263. minFilter = gl.LINEAR;
  6264. }
  6265. }
  6266. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6267. magFilter = gl.LINEAR;
  6268. if (generateMipMaps) {
  6269. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6270. }
  6271. else {
  6272. minFilter = gl.LINEAR;
  6273. }
  6274. }
  6275. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6276. magFilter = gl.NEAREST;
  6277. if (generateMipMaps) {
  6278. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6279. }
  6280. else {
  6281. minFilter = gl.NEAREST;
  6282. }
  6283. }
  6284. return {
  6285. min: minFilter,
  6286. mag: magFilter
  6287. };
  6288. };
  6289. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6290. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6291. var engine = scene.getEngine();
  6292. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6293. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6294. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6295. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6296. texture._baseWidth = width;
  6297. texture._baseHeight = height;
  6298. texture._width = potWidth;
  6299. texture._height = potHeight;
  6300. texture.isReady = true;
  6301. processFunction(potWidth, potHeight);
  6302. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6303. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6304. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6305. if (!noMipmap && !isCompressed) {
  6306. gl.generateMipmap(gl.TEXTURE_2D);
  6307. }
  6308. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6309. engine.resetTextureCache();
  6310. scene._removePendingData(texture);
  6311. texture.onLoadedCallbacks.forEach(function (callback) {
  6312. callback();
  6313. });
  6314. texture.onLoadedCallbacks = [];
  6315. };
  6316. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6317. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6318. var img;
  6319. var onload = function () {
  6320. loadedImages[index] = img;
  6321. loadedImages._internalCount++;
  6322. scene._removePendingData(img);
  6323. if (loadedImages._internalCount === 6) {
  6324. onfinish(loadedImages);
  6325. }
  6326. };
  6327. var onerror = function () {
  6328. scene._removePendingData(img);
  6329. if (onErrorCallBack) {
  6330. onErrorCallBack();
  6331. }
  6332. };
  6333. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6334. scene._addPendingData(img);
  6335. };
  6336. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6337. if (onError === void 0) { onError = null; }
  6338. var loadedImages = [];
  6339. loadedImages._internalCount = 0;
  6340. for (var index = 0; index < 6; index++) {
  6341. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6342. }
  6343. };
  6344. var InstancingAttributeInfo = (function () {
  6345. function InstancingAttributeInfo() {
  6346. }
  6347. return InstancingAttributeInfo;
  6348. }());
  6349. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6350. var EngineCapabilities = (function () {
  6351. function EngineCapabilities() {
  6352. }
  6353. return EngineCapabilities;
  6354. }());
  6355. BABYLON.EngineCapabilities = EngineCapabilities;
  6356. /**
  6357. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6358. */
  6359. var Engine = (function () {
  6360. /**
  6361. * @constructor
  6362. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6363. * @param {boolean} [antialias] - enable antialias
  6364. * @param options - further options to be sent to the getContext function
  6365. */
  6366. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6367. var _this = this;
  6368. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6369. // Public members
  6370. this.isFullscreen = false;
  6371. this.isPointerLock = false;
  6372. this.cullBackFaces = true;
  6373. this.renderEvenInBackground = true;
  6374. // To enable/disable IDB support and avoid XHR on .manifest
  6375. this.enableOfflineSupport = true;
  6376. this.scenes = new Array();
  6377. this._windowIsBackground = false;
  6378. this._webGLVersion = "1.0";
  6379. this._badOS = false;
  6380. this._drawCalls = new BABYLON.PerfCounter();
  6381. this._renderingQueueLaunched = false;
  6382. this._activeRenderLoops = [];
  6383. // FPS
  6384. this.fpsRange = 60;
  6385. this.previousFramesDuration = [];
  6386. this.fps = 60;
  6387. this.deltaTime = 0;
  6388. // States
  6389. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6390. this._stencilState = new BABYLON.Internals._StencilState();
  6391. this._alphaState = new BABYLON.Internals._AlphaState();
  6392. this._alphaMode = Engine.ALPHA_DISABLE;
  6393. // Cache
  6394. this._loadedTexturesCache = new Array();
  6395. this._maxTextureChannels = 16;
  6396. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6397. this._compiledEffects = {};
  6398. this._vertexAttribArraysEnabled = [];
  6399. this._uintIndicesCurrentlySet = false;
  6400. this._currentBoundBuffer = new Array();
  6401. this._currentBufferPointers = [];
  6402. this._currentInstanceLocations = new Array();
  6403. this._currentInstanceBuffers = new Array();
  6404. this._onVRFullScreenTriggered = function () {
  6405. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6406. //get the old size before we change
  6407. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6408. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6409. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6410. //But actually, no browser follow the specs...
  6411. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6412. //get the width and height, change the render size
  6413. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6414. var width, height;
  6415. _this.setHardwareScalingLevel(1);
  6416. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6417. }
  6418. else {
  6419. //When the specs are implemented, need to uncomment this.
  6420. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6421. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6422. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6423. _this._vrDisplayEnabled = undefined;
  6424. }
  6425. };
  6426. this._renderingCanvas = canvas;
  6427. this._externalData = new BABYLON.StringDictionary();
  6428. options = options || {};
  6429. if (antialias != null) {
  6430. options.antialias = antialias;
  6431. }
  6432. if (options.preserveDrawingBuffer === undefined) {
  6433. options.preserveDrawingBuffer = false;
  6434. }
  6435. // Checks if some of the format renders first to allow the use of webgl inspector.
  6436. var renderToFullFloat = this._canRenderToFloatTexture();
  6437. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6438. // GL
  6439. //try {
  6440. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6441. // if (this._gl) {
  6442. // this._webGLVersion = "2.0";
  6443. // }
  6444. //} catch (e) {
  6445. // // Do nothing
  6446. //}
  6447. if (!this._gl) {
  6448. try {
  6449. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6450. }
  6451. catch (e) {
  6452. throw new Error("WebGL not supported");
  6453. }
  6454. }
  6455. if (!this._gl) {
  6456. throw new Error("WebGL not supported");
  6457. }
  6458. this._onBlur = function () {
  6459. _this._windowIsBackground = true;
  6460. };
  6461. this._onFocus = function () {
  6462. _this._windowIsBackground = false;
  6463. };
  6464. window.addEventListener("blur", this._onBlur);
  6465. window.addEventListener("focus", this._onFocus);
  6466. // Viewport
  6467. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6468. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6469. this.resize();
  6470. // Caps
  6471. this._isStencilEnable = options.stencil;
  6472. this._caps = new EngineCapabilities();
  6473. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6474. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6475. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6476. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6477. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6478. // Infos
  6479. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6480. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6481. if (rendererInfo != null) {
  6482. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6483. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6484. }
  6485. if (!this._glVendor) {
  6486. this._glVendor = "Unknown vendor";
  6487. }
  6488. if (!this._glRenderer) {
  6489. this._glRenderer = "Unknown renderer";
  6490. }
  6491. // Extensions
  6492. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6493. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6494. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6495. 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');
  6496. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6497. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6498. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6499. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6500. this._caps.highPrecisionShaderSupported = true;
  6501. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6502. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6503. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6504. this._caps.textureFloatRender = renderToFullFloat;
  6505. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6506. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6507. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6508. if (this._gl.getShaderPrecisionFormat) {
  6509. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6510. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6511. }
  6512. // Depth buffer
  6513. this.setDepthBuffer(true);
  6514. this.setDepthFunctionToLessOrEqual();
  6515. this.setDepthWrite(true);
  6516. // Fullscreen
  6517. this._onFullscreenChange = function () {
  6518. if (document.fullscreen !== undefined) {
  6519. _this.isFullscreen = document.fullscreen;
  6520. }
  6521. else if (document.mozFullScreen !== undefined) {
  6522. _this.isFullscreen = document.mozFullScreen;
  6523. }
  6524. else if (document.webkitIsFullScreen !== undefined) {
  6525. _this.isFullscreen = document.webkitIsFullScreen;
  6526. }
  6527. else if (document.msIsFullScreen !== undefined) {
  6528. _this.isFullscreen = document.msIsFullScreen;
  6529. }
  6530. // Pointer lock
  6531. if (_this.isFullscreen && _this._pointerLockRequested) {
  6532. canvas.requestPointerLock = canvas.requestPointerLock ||
  6533. canvas.msRequestPointerLock ||
  6534. canvas.mozRequestPointerLock ||
  6535. canvas.webkitRequestPointerLock;
  6536. if (canvas.requestPointerLock) {
  6537. canvas.requestPointerLock();
  6538. }
  6539. }
  6540. };
  6541. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6542. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6543. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6544. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6545. // Pointer lock
  6546. this._onPointerLockChange = function () {
  6547. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6548. document.webkitPointerLockElement === canvas ||
  6549. document.msPointerLockElement === canvas ||
  6550. document.pointerLockElement === canvas);
  6551. };
  6552. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6553. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6554. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6555. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6556. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6557. Engine.audioEngine = new BABYLON.AudioEngine();
  6558. }
  6559. //default loading screen
  6560. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6561. //Load WebVR Devices
  6562. if (options.autoEnableWebVR) {
  6563. this.initWebVR();
  6564. }
  6565. //Detect if we are running on a faulty buggy OS.
  6566. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6567. //ua sniffing is the tool of the devil.
  6568. this._badOS = regexp.test(navigator.userAgent);
  6569. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6570. }
  6571. Object.defineProperty(Engine, "NEVER", {
  6572. get: function () {
  6573. return Engine._NEVER;
  6574. },
  6575. enumerable: true,
  6576. configurable: true
  6577. });
  6578. Object.defineProperty(Engine, "ALWAYS", {
  6579. get: function () {
  6580. return Engine._ALWAYS;
  6581. },
  6582. enumerable: true,
  6583. configurable: true
  6584. });
  6585. Object.defineProperty(Engine, "LESS", {
  6586. get: function () {
  6587. return Engine._LESS;
  6588. },
  6589. enumerable: true,
  6590. configurable: true
  6591. });
  6592. Object.defineProperty(Engine, "EQUAL", {
  6593. get: function () {
  6594. return Engine._EQUAL;
  6595. },
  6596. enumerable: true,
  6597. configurable: true
  6598. });
  6599. Object.defineProperty(Engine, "LEQUAL", {
  6600. get: function () {
  6601. return Engine._LEQUAL;
  6602. },
  6603. enumerable: true,
  6604. configurable: true
  6605. });
  6606. Object.defineProperty(Engine, "GREATER", {
  6607. get: function () {
  6608. return Engine._GREATER;
  6609. },
  6610. enumerable: true,
  6611. configurable: true
  6612. });
  6613. Object.defineProperty(Engine, "GEQUAL", {
  6614. get: function () {
  6615. return Engine._GEQUAL;
  6616. },
  6617. enumerable: true,
  6618. configurable: true
  6619. });
  6620. Object.defineProperty(Engine, "NOTEQUAL", {
  6621. get: function () {
  6622. return Engine._NOTEQUAL;
  6623. },
  6624. enumerable: true,
  6625. configurable: true
  6626. });
  6627. Object.defineProperty(Engine, "KEEP", {
  6628. get: function () {
  6629. return Engine._KEEP;
  6630. },
  6631. enumerable: true,
  6632. configurable: true
  6633. });
  6634. Object.defineProperty(Engine, "REPLACE", {
  6635. get: function () {
  6636. return Engine._REPLACE;
  6637. },
  6638. enumerable: true,
  6639. configurable: true
  6640. });
  6641. Object.defineProperty(Engine, "INCR", {
  6642. get: function () {
  6643. return Engine._INCR;
  6644. },
  6645. enumerable: true,
  6646. configurable: true
  6647. });
  6648. Object.defineProperty(Engine, "DECR", {
  6649. get: function () {
  6650. return Engine._DECR;
  6651. },
  6652. enumerable: true,
  6653. configurable: true
  6654. });
  6655. Object.defineProperty(Engine, "INVERT", {
  6656. get: function () {
  6657. return Engine._INVERT;
  6658. },
  6659. enumerable: true,
  6660. configurable: true
  6661. });
  6662. Object.defineProperty(Engine, "INCR_WRAP", {
  6663. get: function () {
  6664. return Engine._INCR_WRAP;
  6665. },
  6666. enumerable: true,
  6667. configurable: true
  6668. });
  6669. Object.defineProperty(Engine, "DECR_WRAP", {
  6670. get: function () {
  6671. return Engine._DECR_WRAP;
  6672. },
  6673. enumerable: true,
  6674. configurable: true
  6675. });
  6676. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6677. get: function () {
  6678. return Engine._ALPHA_DISABLE;
  6679. },
  6680. enumerable: true,
  6681. configurable: true
  6682. });
  6683. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6684. get: function () {
  6685. return Engine._ALPHA_ONEONE;
  6686. },
  6687. enumerable: true,
  6688. configurable: true
  6689. });
  6690. Object.defineProperty(Engine, "ALPHA_ADD", {
  6691. get: function () {
  6692. return Engine._ALPHA_ADD;
  6693. },
  6694. enumerable: true,
  6695. configurable: true
  6696. });
  6697. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6698. get: function () {
  6699. return Engine._ALPHA_COMBINE;
  6700. },
  6701. enumerable: true,
  6702. configurable: true
  6703. });
  6704. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6705. get: function () {
  6706. return Engine._ALPHA_SUBTRACT;
  6707. },
  6708. enumerable: true,
  6709. configurable: true
  6710. });
  6711. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6712. get: function () {
  6713. return Engine._ALPHA_MULTIPLY;
  6714. },
  6715. enumerable: true,
  6716. configurable: true
  6717. });
  6718. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6719. get: function () {
  6720. return Engine._ALPHA_MAXIMIZED;
  6721. },
  6722. enumerable: true,
  6723. configurable: true
  6724. });
  6725. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6726. get: function () {
  6727. return Engine._DELAYLOADSTATE_NONE;
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6733. get: function () {
  6734. return Engine._DELAYLOADSTATE_LOADED;
  6735. },
  6736. enumerable: true,
  6737. configurable: true
  6738. });
  6739. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6740. get: function () {
  6741. return Engine._DELAYLOADSTATE_LOADING;
  6742. },
  6743. enumerable: true,
  6744. configurable: true
  6745. });
  6746. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6747. get: function () {
  6748. return Engine._DELAYLOADSTATE_NOTLOADED;
  6749. },
  6750. enumerable: true,
  6751. configurable: true
  6752. });
  6753. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6754. get: function () {
  6755. return Engine._TEXTUREFORMAT_ALPHA;
  6756. },
  6757. enumerable: true,
  6758. configurable: true
  6759. });
  6760. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6761. get: function () {
  6762. return Engine._TEXTUREFORMAT_LUMINANCE;
  6763. },
  6764. enumerable: true,
  6765. configurable: true
  6766. });
  6767. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6768. get: function () {
  6769. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6770. },
  6771. enumerable: true,
  6772. configurable: true
  6773. });
  6774. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6775. get: function () {
  6776. return Engine._TEXTUREFORMAT_RGB;
  6777. },
  6778. enumerable: true,
  6779. configurable: true
  6780. });
  6781. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6782. get: function () {
  6783. return Engine._TEXTUREFORMAT_RGBA;
  6784. },
  6785. enumerable: true,
  6786. configurable: true
  6787. });
  6788. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6789. get: function () {
  6790. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6791. },
  6792. enumerable: true,
  6793. configurable: true
  6794. });
  6795. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6796. get: function () {
  6797. return Engine._TEXTURETYPE_FLOAT;
  6798. },
  6799. enumerable: true,
  6800. configurable: true
  6801. });
  6802. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6803. get: function () {
  6804. return Engine._TEXTURETYPE_HALF_FLOAT;
  6805. },
  6806. enumerable: true,
  6807. configurable: true
  6808. });
  6809. Object.defineProperty(Engine, "Version", {
  6810. get: function () {
  6811. return "2.5.-beta";
  6812. },
  6813. enumerable: true,
  6814. configurable: true
  6815. });
  6816. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6817. get: function () {
  6818. return this._webGLVersion;
  6819. },
  6820. enumerable: true,
  6821. configurable: true
  6822. });
  6823. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6824. /**
  6825. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6826. */
  6827. get: function () {
  6828. return this._isStencilEnable;
  6829. },
  6830. enumerable: true,
  6831. configurable: true
  6832. });
  6833. Engine.prototype._prepareWorkingCanvas = function () {
  6834. if (this._workingCanvas) {
  6835. return;
  6836. }
  6837. this._workingCanvas = document.createElement("canvas");
  6838. this._workingContext = this._workingCanvas.getContext("2d");
  6839. };
  6840. Engine.prototype.resetTextureCache = function () {
  6841. for (var index = 0; index < this._maxTextureChannels; index++) {
  6842. this._activeTexturesCache[index] = null;
  6843. }
  6844. };
  6845. Engine.prototype.getGlInfo = function () {
  6846. return {
  6847. vendor: this._glVendor,
  6848. renderer: this._glRenderer,
  6849. version: this._glVersion
  6850. };
  6851. };
  6852. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6853. if (useScreen === void 0) { useScreen = false; }
  6854. var viewport = camera.viewport;
  6855. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6856. };
  6857. Engine.prototype.getRenderWidth = function (useScreen) {
  6858. if (useScreen === void 0) { useScreen = false; }
  6859. if (!useScreen && this._currentRenderTarget) {
  6860. return this._currentRenderTarget._width;
  6861. }
  6862. return this._renderingCanvas.width;
  6863. };
  6864. Engine.prototype.getRenderHeight = function (useScreen) {
  6865. if (useScreen === void 0) { useScreen = false; }
  6866. if (!useScreen && this._currentRenderTarget) {
  6867. return this._currentRenderTarget._height;
  6868. }
  6869. return this._renderingCanvas.height;
  6870. };
  6871. Engine.prototype.getRenderingCanvas = function () {
  6872. return this._renderingCanvas;
  6873. };
  6874. Engine.prototype.getRenderingCanvasClientRect = function () {
  6875. return this._renderingCanvas.getBoundingClientRect();
  6876. };
  6877. Engine.prototype.setHardwareScalingLevel = function (level) {
  6878. this._hardwareScalingLevel = level;
  6879. this.resize();
  6880. };
  6881. Engine.prototype.getHardwareScalingLevel = function () {
  6882. return this._hardwareScalingLevel;
  6883. };
  6884. Engine.prototype.getLoadedTexturesCache = function () {
  6885. return this._loadedTexturesCache;
  6886. };
  6887. Engine.prototype.getCaps = function () {
  6888. return this._caps;
  6889. };
  6890. Object.defineProperty(Engine.prototype, "drawCalls", {
  6891. get: function () {
  6892. return this._drawCalls.current;
  6893. },
  6894. enumerable: true,
  6895. configurable: true
  6896. });
  6897. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6898. get: function () {
  6899. return this._drawCalls;
  6900. },
  6901. enumerable: true,
  6902. configurable: true
  6903. });
  6904. Engine.prototype.getDepthFunction = function () {
  6905. return this._depthCullingState.depthFunc;
  6906. };
  6907. Engine.prototype.setDepthFunction = function (depthFunc) {
  6908. this._depthCullingState.depthFunc = depthFunc;
  6909. };
  6910. Engine.prototype.setDepthFunctionToGreater = function () {
  6911. this._depthCullingState.depthFunc = this._gl.GREATER;
  6912. };
  6913. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6914. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6915. };
  6916. Engine.prototype.setDepthFunctionToLess = function () {
  6917. this._depthCullingState.depthFunc = this._gl.LESS;
  6918. };
  6919. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6920. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6921. };
  6922. Engine.prototype.getStencilBuffer = function () {
  6923. return this._stencilState.stencilTest;
  6924. };
  6925. Engine.prototype.setStencilBuffer = function (enable) {
  6926. this._stencilState.stencilTest = enable;
  6927. };
  6928. Engine.prototype.getStencilMask = function () {
  6929. return this._stencilState.stencilMask;
  6930. };
  6931. Engine.prototype.setStencilMask = function (mask) {
  6932. this._stencilState.stencilMask = mask;
  6933. };
  6934. Engine.prototype.getStencilFunction = function () {
  6935. return this._stencilState.stencilFunc;
  6936. };
  6937. Engine.prototype.getStencilFunctionReference = function () {
  6938. return this._stencilState.stencilFuncRef;
  6939. };
  6940. Engine.prototype.getStencilFunctionMask = function () {
  6941. return this._stencilState.stencilFuncMask;
  6942. };
  6943. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6944. this._stencilState.stencilFunc = stencilFunc;
  6945. };
  6946. Engine.prototype.setStencilFunctionReference = function (reference) {
  6947. this._stencilState.stencilFuncRef = reference;
  6948. };
  6949. Engine.prototype.setStencilFunctionMask = function (mask) {
  6950. this._stencilState.stencilFuncMask = mask;
  6951. };
  6952. Engine.prototype.getStencilOperationFail = function () {
  6953. return this._stencilState.stencilOpStencilFail;
  6954. };
  6955. Engine.prototype.getStencilOperationDepthFail = function () {
  6956. return this._stencilState.stencilOpDepthFail;
  6957. };
  6958. Engine.prototype.getStencilOperationPass = function () {
  6959. return this._stencilState.stencilOpStencilDepthPass;
  6960. };
  6961. Engine.prototype.setStencilOperationFail = function (operation) {
  6962. this._stencilState.stencilOpStencilFail = operation;
  6963. };
  6964. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6965. this._stencilState.stencilOpDepthFail = operation;
  6966. };
  6967. Engine.prototype.setStencilOperationPass = function (operation) {
  6968. this._stencilState.stencilOpStencilDepthPass = operation;
  6969. };
  6970. /**
  6971. * stop executing a render loop function and remove it from the execution array
  6972. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6973. */
  6974. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6975. if (!renderFunction) {
  6976. this._activeRenderLoops = [];
  6977. return;
  6978. }
  6979. var index = this._activeRenderLoops.indexOf(renderFunction);
  6980. if (index >= 0) {
  6981. this._activeRenderLoops.splice(index, 1);
  6982. }
  6983. };
  6984. Engine.prototype._renderLoop = function () {
  6985. var shouldRender = true;
  6986. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6987. shouldRender = false;
  6988. }
  6989. if (shouldRender) {
  6990. // Start new frame
  6991. this.beginFrame();
  6992. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6993. var renderFunction = this._activeRenderLoops[index];
  6994. renderFunction();
  6995. }
  6996. // Present
  6997. this.endFrame();
  6998. }
  6999. if (this._activeRenderLoops.length > 0) {
  7000. // Register new frame
  7001. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7002. }
  7003. else {
  7004. this._renderingQueueLaunched = false;
  7005. }
  7006. };
  7007. /**
  7008. * Register and execute a render loop. The engine can have more than one render function.
  7009. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7010. * @example
  7011. * engine.runRenderLoop(function () {
  7012. * scene.render()
  7013. * })
  7014. */
  7015. Engine.prototype.runRenderLoop = function (renderFunction) {
  7016. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7017. return;
  7018. }
  7019. this._activeRenderLoops.push(renderFunction);
  7020. if (!this._renderingQueueLaunched) {
  7021. this._renderingQueueLaunched = true;
  7022. this._bindedRenderFunction = this._renderLoop.bind(this);
  7023. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7024. }
  7025. };
  7026. /**
  7027. * Toggle full screen mode.
  7028. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7029. * @param {any} options - an options object to be sent to the requestFullscreen function
  7030. */
  7031. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7032. if (this.isFullscreen) {
  7033. BABYLON.Tools.ExitFullscreen();
  7034. }
  7035. else {
  7036. this._pointerLockRequested = requestPointerLock;
  7037. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7038. }
  7039. };
  7040. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7041. if (stencil === void 0) { stencil = false; }
  7042. this.applyStates();
  7043. var mode = 0;
  7044. if (backBuffer) {
  7045. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7046. mode |= this._gl.COLOR_BUFFER_BIT;
  7047. }
  7048. if (depth) {
  7049. this._gl.clearDepth(1.0);
  7050. mode |= this._gl.DEPTH_BUFFER_BIT;
  7051. }
  7052. if (stencil) {
  7053. this._gl.clearStencil(0);
  7054. mode |= this._gl.STENCIL_BUFFER_BIT;
  7055. }
  7056. this._gl.clear(mode);
  7057. };
  7058. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7059. var gl = this._gl;
  7060. // Save state
  7061. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7062. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7063. // Change state
  7064. gl.enable(gl.SCISSOR_TEST);
  7065. gl.scissor(x, y, width, height);
  7066. // Clear
  7067. this.clear(clearColor, true, true, true);
  7068. // Restore state
  7069. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7070. if (curScissor === true) {
  7071. gl.enable(gl.SCISSOR_TEST);
  7072. }
  7073. else {
  7074. gl.disable(gl.SCISSOR_TEST);
  7075. }
  7076. };
  7077. /**
  7078. * Set the WebGL's viewport
  7079. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7080. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7081. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7082. */
  7083. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7084. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  7085. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  7086. var x = viewport.x || 0;
  7087. var y = viewport.y || 0;
  7088. this._cachedViewport = viewport;
  7089. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7090. };
  7091. /**
  7092. * Directly set the WebGL Viewport
  7093. * The x, y, width & height are directly passed to the WebGL call
  7094. * @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.
  7095. */
  7096. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7097. var currentViewport = this._cachedViewport;
  7098. this._cachedViewport = null;
  7099. this._gl.viewport(x, y, width, height);
  7100. return currentViewport;
  7101. };
  7102. Engine.prototype.beginFrame = function () {
  7103. this._measureFps();
  7104. };
  7105. Engine.prototype.endFrame = function () {
  7106. //force a flush in case we are using a bad OS.
  7107. if (this._badOS) {
  7108. this.flushFramebuffer();
  7109. }
  7110. //submit frame to the vr device, if enabled
  7111. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7112. this._vrDisplayEnabled.submitFrame();
  7113. }
  7114. };
  7115. /**
  7116. * resize the view according to the canvas' size.
  7117. * @example
  7118. * window.addEventListener("resize", function () {
  7119. * engine.resize();
  7120. * });
  7121. */
  7122. Engine.prototype.resize = function () {
  7123. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7124. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7125. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7126. for (var index = 0; index < this.scenes.length; index++) {
  7127. var scene = this.scenes[index];
  7128. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  7129. scene.debugLayer._syncPositions();
  7130. }
  7131. }
  7132. };
  7133. /**
  7134. * force a specific size of the canvas
  7135. * @param {number} width - the new canvas' width
  7136. * @param {number} height - the new canvas' height
  7137. */
  7138. Engine.prototype.setSize = function (width, height) {
  7139. this._renderingCanvas.width = width;
  7140. this._renderingCanvas.height = height;
  7141. for (var index = 0; index < this.scenes.length; index++) {
  7142. var scene = this.scenes[index];
  7143. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7144. var cam = scene.cameras[camIndex];
  7145. cam._currentRenderId = 0;
  7146. }
  7147. }
  7148. };
  7149. //WebVR functions
  7150. Engine.prototype.initWebVR = function () {
  7151. if (!this.vrDisplaysPromise) {
  7152. this._getVRDisplays();
  7153. }
  7154. };
  7155. Engine.prototype.enableVR = function (vrDevice) {
  7156. this._vrDisplayEnabled = vrDevice;
  7157. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7158. };
  7159. Engine.prototype.disableVR = function () {
  7160. if (this._vrDisplayEnabled) {
  7161. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7162. }
  7163. };
  7164. Engine.prototype._getVRDisplays = function () {
  7165. var _this = this;
  7166. var getWebVRDevices = function (devices) {
  7167. var size = devices.length;
  7168. var i = 0;
  7169. _this._vrDisplays = devices.filter(function (device) {
  7170. return devices[i] instanceof VRDisplay;
  7171. });
  7172. return _this._vrDisplays;
  7173. };
  7174. //using a key due to typescript
  7175. if (navigator.getVRDisplays) {
  7176. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7177. }
  7178. };
  7179. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7180. this._currentRenderTarget = texture;
  7181. this.bindUnboundFramebuffer(texture._framebuffer);
  7182. var gl = this._gl;
  7183. if (texture.isCube) {
  7184. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7185. }
  7186. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7187. this.wipeCaches();
  7188. };
  7189. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7190. if (this._currentFramebuffer !== framebuffer) {
  7191. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7192. this._currentFramebuffer = framebuffer;
  7193. }
  7194. };
  7195. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7196. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7197. this._currentRenderTarget = null;
  7198. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7199. var gl = this._gl;
  7200. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7201. gl.generateMipmap(gl.TEXTURE_2D);
  7202. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7203. }
  7204. this.bindUnboundFramebuffer(null);
  7205. };
  7206. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7207. if (texture.generateMipMaps) {
  7208. var gl = this._gl;
  7209. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7210. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7211. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7212. }
  7213. };
  7214. Engine.prototype.flushFramebuffer = function () {
  7215. this._gl.flush();
  7216. };
  7217. Engine.prototype.restoreDefaultFramebuffer = function () {
  7218. this._currentRenderTarget = null;
  7219. this.bindUnboundFramebuffer(null);
  7220. this.setViewport(this._cachedViewport);
  7221. this.wipeCaches();
  7222. };
  7223. // VBOs
  7224. Engine.prototype._resetVertexBufferBinding = function () {
  7225. this.bindArrayBuffer(null);
  7226. this._cachedVertexBuffers = null;
  7227. };
  7228. Engine.prototype.createVertexBuffer = function (vertices) {
  7229. var vbo = this._gl.createBuffer();
  7230. this.bindArrayBuffer(vbo);
  7231. if (vertices instanceof Float32Array) {
  7232. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7233. }
  7234. else {
  7235. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7236. }
  7237. this._resetVertexBufferBinding();
  7238. vbo.references = 1;
  7239. return vbo;
  7240. };
  7241. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7242. var vbo = this._gl.createBuffer();
  7243. this.bindArrayBuffer(vbo);
  7244. if (vertices instanceof Float32Array) {
  7245. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7246. }
  7247. else {
  7248. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7249. }
  7250. this._resetVertexBufferBinding();
  7251. vbo.references = 1;
  7252. return vbo;
  7253. };
  7254. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7255. this.bindArrayBuffer(vertexBuffer);
  7256. if (offset === undefined) {
  7257. offset = 0;
  7258. }
  7259. if (count === undefined) {
  7260. if (vertices instanceof Float32Array) {
  7261. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7262. }
  7263. else {
  7264. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7265. }
  7266. }
  7267. else {
  7268. if (vertices instanceof Float32Array) {
  7269. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7270. }
  7271. else {
  7272. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7273. }
  7274. }
  7275. this._resetVertexBufferBinding();
  7276. };
  7277. Engine.prototype._resetIndexBufferBinding = function () {
  7278. this.bindIndexBuffer(null);
  7279. this._cachedIndexBuffer = null;
  7280. };
  7281. Engine.prototype.createIndexBuffer = function (indices) {
  7282. var vbo = this._gl.createBuffer();
  7283. this.bindIndexBuffer(vbo);
  7284. // Check for 32 bits indices
  7285. var arrayBuffer;
  7286. var need32Bits = false;
  7287. if (this._caps.uintIndices) {
  7288. for (var index = 0; index < indices.length; index++) {
  7289. if (indices[index] > 65535) {
  7290. need32Bits = true;
  7291. break;
  7292. }
  7293. }
  7294. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7295. }
  7296. else {
  7297. arrayBuffer = new Uint16Array(indices);
  7298. }
  7299. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7300. this._resetIndexBufferBinding();
  7301. vbo.references = 1;
  7302. vbo.is32Bits = need32Bits;
  7303. return vbo;
  7304. };
  7305. Engine.prototype.bindArrayBuffer = function (buffer) {
  7306. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7307. };
  7308. Engine.prototype.bindIndexBuffer = function (buffer) {
  7309. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7310. };
  7311. Engine.prototype.bindBuffer = function (buffer, target) {
  7312. if (this._currentBoundBuffer[target] !== buffer) {
  7313. this._gl.bindBuffer(target, buffer);
  7314. this._currentBoundBuffer[target] = buffer;
  7315. }
  7316. };
  7317. Engine.prototype.updateArrayBuffer = function (data) {
  7318. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7319. };
  7320. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7321. var pointer = this._currentBufferPointers[indx];
  7322. var changed = false;
  7323. if (!pointer) {
  7324. changed = true;
  7325. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7326. }
  7327. else {
  7328. if (pointer.buffer !== buffer) {
  7329. pointer.buffer = buffer;
  7330. changed = true;
  7331. }
  7332. if (pointer.size !== size) {
  7333. pointer.size = size;
  7334. changed = true;
  7335. }
  7336. if (pointer.type !== type) {
  7337. pointer.type = type;
  7338. changed = true;
  7339. }
  7340. if (pointer.normalized !== normalized) {
  7341. pointer.normalized = normalized;
  7342. changed = true;
  7343. }
  7344. if (pointer.stride !== stride) {
  7345. pointer.stride = stride;
  7346. changed = true;
  7347. }
  7348. if (pointer.offset !== offset) {
  7349. pointer.offset = offset;
  7350. changed = true;
  7351. }
  7352. }
  7353. if (changed) {
  7354. this.bindArrayBuffer(buffer);
  7355. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7356. }
  7357. };
  7358. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7359. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7360. this._cachedVertexBuffers = vertexBuffer;
  7361. this._cachedEffectForVertexBuffers = effect;
  7362. var attributesCount = effect.getAttributesCount();
  7363. var offset = 0;
  7364. for (var index = 0; index < attributesCount; index++) {
  7365. if (index < vertexDeclaration.length) {
  7366. var order = effect.getAttributeLocation(index);
  7367. if (order >= 0) {
  7368. if (!this._vertexAttribArraysEnabled[order]) {
  7369. this._gl.enableVertexAttribArray(order);
  7370. this._vertexAttribArraysEnabled[order] = true;
  7371. }
  7372. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7373. }
  7374. offset += vertexDeclaration[index] * 4;
  7375. }
  7376. else {
  7377. //disable effect attributes that have no data
  7378. var order = effect.getAttributeLocation(index);
  7379. if (this._vertexAttribArraysEnabled[order]) {
  7380. this._gl.disableVertexAttribArray(order);
  7381. this._vertexAttribArraysEnabled[order] = false;
  7382. }
  7383. }
  7384. }
  7385. }
  7386. if (this._cachedIndexBuffer !== indexBuffer) {
  7387. this._cachedIndexBuffer = indexBuffer;
  7388. this.bindIndexBuffer(indexBuffer);
  7389. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7390. }
  7391. };
  7392. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7393. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7394. this._cachedVertexBuffers = vertexBuffers;
  7395. this._cachedEffectForVertexBuffers = effect;
  7396. var attributes = effect.getAttributesNames();
  7397. for (var index = 0; index < attributes.length; index++) {
  7398. var order = effect.getAttributeLocation(index);
  7399. if (order >= 0) {
  7400. var vertexBuffer = vertexBuffers[attributes[index]];
  7401. if (!vertexBuffer) {
  7402. if (this._vertexAttribArraysEnabled[order]) {
  7403. this._gl.disableVertexAttribArray(order);
  7404. this._vertexAttribArraysEnabled[order] = false;
  7405. }
  7406. continue;
  7407. }
  7408. if (!this._vertexAttribArraysEnabled[order]) {
  7409. this._gl.enableVertexAttribArray(order);
  7410. this._vertexAttribArraysEnabled[order] = true;
  7411. }
  7412. var buffer = vertexBuffer.getBuffer();
  7413. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7414. if (vertexBuffer.getIsInstanced()) {
  7415. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7416. this._currentInstanceLocations.push(order);
  7417. this._currentInstanceBuffers.push(buffer);
  7418. }
  7419. }
  7420. }
  7421. }
  7422. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7423. this._cachedIndexBuffer = indexBuffer;
  7424. this.bindIndexBuffer(indexBuffer);
  7425. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7426. }
  7427. };
  7428. Engine.prototype.unbindInstanceAttributes = function () {
  7429. var boundBuffer;
  7430. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7431. var instancesBuffer = this._currentInstanceBuffers[i];
  7432. if (boundBuffer != instancesBuffer) {
  7433. boundBuffer = instancesBuffer;
  7434. this.bindArrayBuffer(instancesBuffer);
  7435. }
  7436. var offsetLocation = this._currentInstanceLocations[i];
  7437. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7438. }
  7439. this._currentInstanceBuffers.length = 0;
  7440. this._currentInstanceLocations.length = 0;
  7441. };
  7442. Engine.prototype._releaseBuffer = function (buffer) {
  7443. buffer.references--;
  7444. if (buffer.references === 0) {
  7445. this._gl.deleteBuffer(buffer);
  7446. return true;
  7447. }
  7448. return false;
  7449. };
  7450. Engine.prototype.createInstancesBuffer = function (capacity) {
  7451. var buffer = this._gl.createBuffer();
  7452. buffer.capacity = capacity;
  7453. this.bindArrayBuffer(buffer);
  7454. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7455. return buffer;
  7456. };
  7457. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7458. this._gl.deleteBuffer(buffer);
  7459. };
  7460. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7461. this.bindArrayBuffer(instancesBuffer);
  7462. if (data) {
  7463. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7464. }
  7465. if (offsetLocations[0].index !== undefined) {
  7466. var stride = 0;
  7467. for (var i = 0; i < offsetLocations.length; i++) {
  7468. var ai = offsetLocations[i];
  7469. stride += ai.attributeSize * 4;
  7470. }
  7471. for (var i = 0; i < offsetLocations.length; i++) {
  7472. var ai = offsetLocations[i];
  7473. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7474. this._gl.enableVertexAttribArray(ai.index);
  7475. this._vertexAttribArraysEnabled[ai.index] = true;
  7476. }
  7477. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7478. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7479. this._currentInstanceLocations.push(ai.index);
  7480. this._currentInstanceBuffers.push(instancesBuffer);
  7481. }
  7482. }
  7483. else {
  7484. for (var index = 0; index < 4; index++) {
  7485. var offsetLocation = offsetLocations[index];
  7486. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7487. this._gl.enableVertexAttribArray(offsetLocation);
  7488. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7489. }
  7490. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7491. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7492. this._currentInstanceLocations.push(offsetLocation);
  7493. this._currentInstanceBuffers.push(instancesBuffer);
  7494. }
  7495. }
  7496. };
  7497. Engine.prototype.applyStates = function () {
  7498. this._depthCullingState.apply(this._gl);
  7499. this._stencilState.apply(this._gl);
  7500. this._alphaState.apply(this._gl);
  7501. };
  7502. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7503. // Apply states
  7504. this.applyStates();
  7505. this._drawCalls.addCount(1, false);
  7506. // Render
  7507. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7508. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7509. if (instancesCount) {
  7510. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7511. return;
  7512. }
  7513. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7514. };
  7515. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7516. // Apply states
  7517. this.applyStates();
  7518. this._drawCalls.addCount(1, false);
  7519. if (instancesCount) {
  7520. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7521. return;
  7522. }
  7523. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7524. };
  7525. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7526. // Apply states
  7527. this.applyStates();
  7528. this._drawCalls.addCount(1, false);
  7529. if (instancesCount) {
  7530. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7531. return;
  7532. }
  7533. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7534. };
  7535. // Shaders
  7536. Engine.prototype._releaseEffect = function (effect) {
  7537. if (this._compiledEffects[effect._key]) {
  7538. delete this._compiledEffects[effect._key];
  7539. if (effect.getProgram()) {
  7540. this._gl.deleteProgram(effect.getProgram());
  7541. }
  7542. }
  7543. };
  7544. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7545. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7546. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7547. var name = vertex + "+" + fragment + "@" + defines;
  7548. if (this._compiledEffects[name]) {
  7549. return this._compiledEffects[name];
  7550. }
  7551. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7552. effect._key = name;
  7553. this._compiledEffects[name] = effect;
  7554. return effect;
  7555. };
  7556. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7557. if (uniformsNames === void 0) { uniformsNames = []; }
  7558. if (samplers === void 0) { samplers = []; }
  7559. if (defines === void 0) { defines = ""; }
  7560. return this.createEffect({
  7561. vertex: "particles",
  7562. fragmentElement: fragmentName
  7563. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7564. };
  7565. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7566. context = context || this._gl;
  7567. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7568. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7569. var shaderProgram = context.createProgram();
  7570. context.attachShader(shaderProgram, vertexShader);
  7571. context.attachShader(shaderProgram, fragmentShader);
  7572. context.linkProgram(shaderProgram);
  7573. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7574. if (!linked) {
  7575. var error = context.getProgramInfoLog(shaderProgram);
  7576. if (error) {
  7577. throw new Error(error);
  7578. }
  7579. }
  7580. context.deleteShader(vertexShader);
  7581. context.deleteShader(fragmentShader);
  7582. return shaderProgram;
  7583. };
  7584. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7585. var results = [];
  7586. for (var index = 0; index < uniformsNames.length; index++) {
  7587. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7588. }
  7589. return results;
  7590. };
  7591. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7592. var results = [];
  7593. for (var index = 0; index < attributesNames.length; index++) {
  7594. try {
  7595. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7596. }
  7597. catch (e) {
  7598. results.push(-1);
  7599. }
  7600. }
  7601. return results;
  7602. };
  7603. Engine.prototype.enableEffect = function (effect) {
  7604. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7605. // if (effect && effect.onBind) {
  7606. // effect.onBind(effect);
  7607. // }
  7608. // return;
  7609. //}
  7610. // Use program
  7611. this.setProgram(effect.getProgram());
  7612. this._currentEffect = effect;
  7613. if (effect.onBind) {
  7614. effect.onBind(effect);
  7615. }
  7616. };
  7617. Engine.prototype.setIntArray = function (uniform, array) {
  7618. if (!uniform)
  7619. return;
  7620. this._gl.uniform1iv(uniform, array);
  7621. };
  7622. Engine.prototype.setIntArray2 = function (uniform, array) {
  7623. if (!uniform || array.length % 2 !== 0)
  7624. return;
  7625. this._gl.uniform2iv(uniform, array);
  7626. };
  7627. Engine.prototype.setIntArray3 = function (uniform, array) {
  7628. if (!uniform || array.length % 3 !== 0)
  7629. return;
  7630. this._gl.uniform3iv(uniform, array);
  7631. };
  7632. Engine.prototype.setIntArray4 = function (uniform, array) {
  7633. if (!uniform || array.length % 4 !== 0)
  7634. return;
  7635. this._gl.uniform4iv(uniform, array);
  7636. };
  7637. Engine.prototype.setFloatArray = function (uniform, array) {
  7638. if (!uniform)
  7639. return;
  7640. this._gl.uniform1fv(uniform, array);
  7641. };
  7642. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7643. if (!uniform || array.length % 2 !== 0)
  7644. return;
  7645. this._gl.uniform2fv(uniform, array);
  7646. };
  7647. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7648. if (!uniform || array.length % 3 !== 0)
  7649. return;
  7650. this._gl.uniform3fv(uniform, array);
  7651. };
  7652. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7653. if (!uniform || array.length % 4 !== 0)
  7654. return;
  7655. this._gl.uniform4fv(uniform, array);
  7656. };
  7657. Engine.prototype.setArray = function (uniform, array) {
  7658. if (!uniform)
  7659. return;
  7660. this._gl.uniform1fv(uniform, array);
  7661. };
  7662. Engine.prototype.setArray2 = function (uniform, array) {
  7663. if (!uniform || array.length % 2 !== 0)
  7664. return;
  7665. this._gl.uniform2fv(uniform, array);
  7666. };
  7667. Engine.prototype.setArray3 = function (uniform, array) {
  7668. if (!uniform || array.length % 3 !== 0)
  7669. return;
  7670. this._gl.uniform3fv(uniform, array);
  7671. };
  7672. Engine.prototype.setArray4 = function (uniform, array) {
  7673. if (!uniform || array.length % 4 !== 0)
  7674. return;
  7675. this._gl.uniform4fv(uniform, array);
  7676. };
  7677. Engine.prototype.setMatrices = function (uniform, matrices) {
  7678. if (!uniform)
  7679. return;
  7680. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7681. };
  7682. Engine.prototype.setMatrix = function (uniform, matrix) {
  7683. if (!uniform)
  7684. return;
  7685. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7686. };
  7687. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7688. if (!uniform)
  7689. return;
  7690. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7691. };
  7692. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7693. if (!uniform)
  7694. return;
  7695. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7696. };
  7697. Engine.prototype.setFloat = function (uniform, value) {
  7698. if (!uniform)
  7699. return;
  7700. this._gl.uniform1f(uniform, value);
  7701. };
  7702. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7703. if (!uniform)
  7704. return;
  7705. this._gl.uniform2f(uniform, x, y);
  7706. };
  7707. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7708. if (!uniform)
  7709. return;
  7710. this._gl.uniform3f(uniform, x, y, z);
  7711. };
  7712. Engine.prototype.setBool = function (uniform, bool) {
  7713. if (!uniform)
  7714. return;
  7715. this._gl.uniform1i(uniform, bool);
  7716. };
  7717. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7718. if (!uniform)
  7719. return;
  7720. this._gl.uniform4f(uniform, x, y, z, w);
  7721. };
  7722. Engine.prototype.setColor3 = function (uniform, color3) {
  7723. if (!uniform)
  7724. return;
  7725. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7726. };
  7727. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7728. if (!uniform)
  7729. return;
  7730. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7731. };
  7732. // States
  7733. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7734. if (zOffset === void 0) { zOffset = 0; }
  7735. if (reverseSide === void 0) { reverseSide = false; }
  7736. // Culling
  7737. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7738. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7739. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7740. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7741. if (culling) {
  7742. this._depthCullingState.cullFace = cullFace;
  7743. this._depthCullingState.cull = true;
  7744. }
  7745. else {
  7746. this._depthCullingState.cull = false;
  7747. }
  7748. }
  7749. // Z offset
  7750. this._depthCullingState.zOffset = zOffset;
  7751. };
  7752. Engine.prototype.setDepthBuffer = function (enable) {
  7753. this._depthCullingState.depthTest = enable;
  7754. };
  7755. Engine.prototype.getDepthWrite = function () {
  7756. return this._depthCullingState.depthMask;
  7757. };
  7758. Engine.prototype.setDepthWrite = function (enable) {
  7759. this._depthCullingState.depthMask = enable;
  7760. };
  7761. Engine.prototype.setColorWrite = function (enable) {
  7762. this._gl.colorMask(enable, enable, enable, enable);
  7763. };
  7764. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7765. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7766. if (this._alphaMode === mode) {
  7767. return;
  7768. }
  7769. switch (mode) {
  7770. case Engine.ALPHA_DISABLE:
  7771. this._alphaState.alphaBlend = false;
  7772. break;
  7773. case Engine.ALPHA_COMBINE:
  7774. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7775. this._alphaState.alphaBlend = true;
  7776. break;
  7777. case Engine.ALPHA_ONEONE:
  7778. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7779. this._alphaState.alphaBlend = true;
  7780. break;
  7781. case Engine.ALPHA_ADD:
  7782. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7783. this._alphaState.alphaBlend = true;
  7784. break;
  7785. case Engine.ALPHA_SUBTRACT:
  7786. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7787. this._alphaState.alphaBlend = true;
  7788. break;
  7789. case Engine.ALPHA_MULTIPLY:
  7790. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7791. this._alphaState.alphaBlend = true;
  7792. break;
  7793. case Engine.ALPHA_MAXIMIZED:
  7794. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7795. this._alphaState.alphaBlend = true;
  7796. break;
  7797. }
  7798. if (!noDepthWriteChange) {
  7799. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7800. }
  7801. this._alphaMode = mode;
  7802. };
  7803. Engine.prototype.getAlphaMode = function () {
  7804. return this._alphaMode;
  7805. };
  7806. Engine.prototype.setAlphaTesting = function (enable) {
  7807. this._alphaTest = enable;
  7808. };
  7809. Engine.prototype.getAlphaTesting = function () {
  7810. return this._alphaTest;
  7811. };
  7812. // Textures
  7813. Engine.prototype.wipeCaches = function () {
  7814. this.resetTextureCache();
  7815. this._currentEffect = null;
  7816. this._stencilState.reset();
  7817. this._depthCullingState.reset();
  7818. this.setDepthFunctionToLessOrEqual();
  7819. this._alphaState.reset();
  7820. this._cachedVertexBuffers = null;
  7821. this._cachedIndexBuffer = null;
  7822. this._cachedEffectForVertexBuffers = null;
  7823. };
  7824. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7825. var gl = this._gl;
  7826. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7827. var magFilter = gl.NEAREST;
  7828. var minFilter = gl.NEAREST;
  7829. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7830. magFilter = gl.LINEAR;
  7831. minFilter = gl.LINEAR;
  7832. }
  7833. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7834. magFilter = gl.LINEAR;
  7835. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7836. }
  7837. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7838. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7839. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7840. texture.samplingMode = samplingMode;
  7841. };
  7842. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7843. var _this = this;
  7844. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7845. if (onLoad === void 0) { onLoad = null; }
  7846. if (onError === void 0) { onError = null; }
  7847. if (buffer === void 0) { buffer = null; }
  7848. var texture = this._gl.createTexture();
  7849. var extension;
  7850. var fromData = false;
  7851. if (url.substr(0, 5) === "data:") {
  7852. fromData = true;
  7853. }
  7854. if (!fromData)
  7855. extension = url.substr(url.length - 4, 4).toLowerCase();
  7856. else {
  7857. var oldUrl = url;
  7858. fromData = oldUrl.split(':');
  7859. url = oldUrl;
  7860. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7861. }
  7862. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7863. var isTGA = (extension === ".tga");
  7864. scene._addPendingData(texture);
  7865. texture.url = url;
  7866. texture.noMipmap = noMipmap;
  7867. texture.references = 1;
  7868. texture.samplingMode = samplingMode;
  7869. texture.onLoadedCallbacks = [onLoad];
  7870. this._loadedTexturesCache.push(texture);
  7871. var onerror = function () {
  7872. scene._removePendingData(texture);
  7873. if (onError) {
  7874. onError();
  7875. }
  7876. };
  7877. var callback;
  7878. if (isTGA) {
  7879. callback = function (arrayBuffer) {
  7880. var data = new Uint8Array(arrayBuffer);
  7881. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7882. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7883. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7884. }, samplingMode);
  7885. };
  7886. if (!(fromData instanceof Array))
  7887. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7888. callback(arrayBuffer);
  7889. }, null, scene.database, true, onerror);
  7890. else
  7891. callback(buffer);
  7892. }
  7893. else if (isDDS) {
  7894. callback = function (data) {
  7895. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7896. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7897. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7898. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7899. }, samplingMode);
  7900. };
  7901. if (!(fromData instanceof Array))
  7902. BABYLON.Tools.LoadFile(url, function (data) {
  7903. callback(data);
  7904. }, null, scene.database, true, onerror);
  7905. else
  7906. callback(buffer);
  7907. }
  7908. else {
  7909. var onload = function (img) {
  7910. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7911. var isPot = (img.width === potWidth && img.height === potHeight);
  7912. if (!isPot) {
  7913. _this._prepareWorkingCanvas();
  7914. _this._workingCanvas.width = potWidth;
  7915. _this._workingCanvas.height = potHeight;
  7916. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7917. _this._workingContext.imageSmoothingEnabled = false;
  7918. _this._workingContext.mozImageSmoothingEnabled = false;
  7919. _this._workingContext.oImageSmoothingEnabled = false;
  7920. _this._workingContext.webkitImageSmoothingEnabled = false;
  7921. _this._workingContext.msImageSmoothingEnabled = false;
  7922. }
  7923. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7924. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7925. _this._workingContext.imageSmoothingEnabled = true;
  7926. _this._workingContext.mozImageSmoothingEnabled = true;
  7927. _this._workingContext.oImageSmoothingEnabled = true;
  7928. _this._workingContext.webkitImageSmoothingEnabled = true;
  7929. _this._workingContext.msImageSmoothingEnabled = true;
  7930. }
  7931. }
  7932. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7933. }, samplingMode);
  7934. };
  7935. if (!(fromData instanceof Array))
  7936. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7937. else
  7938. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7939. }
  7940. return texture;
  7941. };
  7942. Engine.prototype._getInternalFormat = function (format) {
  7943. var internalFormat = this._gl.RGBA;
  7944. switch (format) {
  7945. case Engine.TEXTUREFORMAT_ALPHA:
  7946. internalFormat = this._gl.ALPHA;
  7947. break;
  7948. case Engine.TEXTUREFORMAT_LUMINANCE:
  7949. internalFormat = this._gl.LUMINANCE;
  7950. break;
  7951. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7952. internalFormat = this._gl.LUMINANCE_ALPHA;
  7953. break;
  7954. case Engine.TEXTUREFORMAT_RGB:
  7955. internalFormat = this._gl.RGB;
  7956. break;
  7957. case Engine.TEXTUREFORMAT_RGBA:
  7958. internalFormat = this._gl.RGBA;
  7959. break;
  7960. }
  7961. return internalFormat;
  7962. };
  7963. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7964. if (compression === void 0) { compression = null; }
  7965. var internalFormat = this._getInternalFormat(format);
  7966. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7967. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7968. if (texture._width % 4 !== 0) {
  7969. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7970. }
  7971. if (compression) {
  7972. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7973. }
  7974. else {
  7975. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7976. }
  7977. if (texture.generateMipMaps) {
  7978. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7979. }
  7980. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7981. this.resetTextureCache();
  7982. texture.isReady = true;
  7983. };
  7984. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7985. if (compression === void 0) { compression = null; }
  7986. var texture = this._gl.createTexture();
  7987. texture._baseWidth = width;
  7988. texture._baseHeight = height;
  7989. texture._width = width;
  7990. texture._height = height;
  7991. texture.references = 1;
  7992. this.updateRawTexture(texture, data, format, invertY, compression);
  7993. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7994. // Filters
  7995. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7996. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7997. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7998. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7999. texture.samplingMode = samplingMode;
  8000. this._loadedTexturesCache.push(texture);
  8001. return texture;
  8002. };
  8003. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8004. var texture = this._gl.createTexture();
  8005. texture._baseWidth = width;
  8006. texture._baseHeight = height;
  8007. if (generateMipMaps) {
  8008. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8009. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8010. }
  8011. this.resetTextureCache();
  8012. texture._width = width;
  8013. texture._height = height;
  8014. texture.isReady = false;
  8015. texture.generateMipMaps = generateMipMaps;
  8016. texture.references = 1;
  8017. texture.samplingMode = samplingMode;
  8018. this.updateTextureSamplingMode(samplingMode, texture);
  8019. this._loadedTexturesCache.push(texture);
  8020. return texture;
  8021. };
  8022. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8023. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8024. if (texture.isCube) {
  8025. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8026. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8027. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8028. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8029. }
  8030. else {
  8031. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8032. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8033. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8034. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8035. }
  8036. };
  8037. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8038. if (premulAlpha === void 0) { premulAlpha = false; }
  8039. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8040. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8041. if (premulAlpha) {
  8042. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8043. }
  8044. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8045. if (texture.generateMipMaps) {
  8046. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8047. }
  8048. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8049. if (premulAlpha) {
  8050. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8051. }
  8052. this.resetTextureCache();
  8053. texture.isReady = true;
  8054. };
  8055. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8056. if (texture._isDisabled) {
  8057. return;
  8058. }
  8059. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8060. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8061. try {
  8062. // Testing video texture support
  8063. if (this._videoTextureSupported === undefined) {
  8064. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8065. if (this._gl.getError() !== 0) {
  8066. this._videoTextureSupported = false;
  8067. }
  8068. else {
  8069. this._videoTextureSupported = true;
  8070. }
  8071. }
  8072. // Copy video through the current working canvas if video texture is not supported
  8073. if (!this._videoTextureSupported) {
  8074. if (!texture._workingCanvas) {
  8075. texture._workingCanvas = document.createElement("canvas");
  8076. texture._workingContext = texture._workingCanvas.getContext("2d");
  8077. texture._workingCanvas.width = texture._width;
  8078. texture._workingCanvas.height = texture._height;
  8079. }
  8080. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8081. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8082. }
  8083. else {
  8084. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8085. }
  8086. if (texture.generateMipMaps) {
  8087. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8088. }
  8089. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8090. this.resetTextureCache();
  8091. texture.isReady = true;
  8092. }
  8093. catch (ex) {
  8094. // Something unexpected
  8095. // Let's disable the texture
  8096. texture._isDisabled = true;
  8097. }
  8098. };
  8099. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8100. // old version had a "generateMipMaps" arg instead of options.
  8101. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8102. // in the same way, generateDepthBuffer is defaulted to true
  8103. var generateMipMaps = false;
  8104. var generateDepthBuffer = true;
  8105. var generateStencilBuffer = false;
  8106. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8107. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8108. if (options !== undefined) {
  8109. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8110. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8111. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8112. type = options.type === undefined ? type : options.type;
  8113. if (options.samplingMode !== undefined) {
  8114. samplingMode = options.samplingMode;
  8115. }
  8116. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8117. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8118. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8119. }
  8120. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8121. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8122. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8123. }
  8124. }
  8125. var gl = this._gl;
  8126. var texture = gl.createTexture();
  8127. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8128. var width = size.width || size;
  8129. var height = size.height || size;
  8130. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8131. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8132. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8133. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8134. }
  8135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8138. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8139. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8140. var depthStencilBuffer;
  8141. // Create the depth/stencil buffer
  8142. if (generateStencilBuffer) {
  8143. depthStencilBuffer = gl.createRenderbuffer();
  8144. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8145. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8146. }
  8147. else if (generateDepthBuffer) {
  8148. depthStencilBuffer = gl.createRenderbuffer();
  8149. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8150. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8151. }
  8152. // Create the framebuffer
  8153. var framebuffer = gl.createFramebuffer();
  8154. this.bindUnboundFramebuffer(framebuffer);
  8155. // Manage attachments
  8156. if (generateStencilBuffer) {
  8157. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8158. }
  8159. else if (generateDepthBuffer) {
  8160. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8161. }
  8162. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8163. if (generateMipMaps) {
  8164. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8165. }
  8166. // Unbind
  8167. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8168. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8169. this.bindUnboundFramebuffer(null);
  8170. texture._framebuffer = framebuffer;
  8171. if (generateDepthBuffer) {
  8172. texture._depthBuffer = depthStencilBuffer;
  8173. }
  8174. texture._baseWidth = width;
  8175. texture._baseHeight = height;
  8176. texture._width = width;
  8177. texture._height = height;
  8178. texture.isReady = true;
  8179. texture.generateMipMaps = generateMipMaps;
  8180. texture.references = 1;
  8181. texture.samplingMode = samplingMode;
  8182. texture.type = type;
  8183. this.resetTextureCache();
  8184. this._loadedTexturesCache.push(texture);
  8185. return texture;
  8186. };
  8187. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8188. var gl = this._gl;
  8189. var texture = gl.createTexture();
  8190. var generateMipMaps = true;
  8191. var generateDepthBuffer = true;
  8192. var generateStencilBuffer = false;
  8193. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8194. if (options !== undefined) {
  8195. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8196. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8197. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8198. if (options.samplingMode !== undefined) {
  8199. samplingMode = options.samplingMode;
  8200. }
  8201. }
  8202. texture.isCube = true;
  8203. texture.references = 1;
  8204. texture.generateMipMaps = generateMipMaps;
  8205. texture.references = 1;
  8206. texture.samplingMode = samplingMode;
  8207. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8208. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8209. for (var face = 0; face < 6; face++) {
  8210. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8211. }
  8212. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8213. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8214. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8215. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8216. // Create the depth buffer
  8217. var depthStencilBuffer;
  8218. // Create the depth/stencil buffer
  8219. if (generateStencilBuffer) {
  8220. depthStencilBuffer = gl.createRenderbuffer();
  8221. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8222. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8223. }
  8224. else if (generateDepthBuffer) {
  8225. depthStencilBuffer = gl.createRenderbuffer();
  8226. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8227. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8228. }
  8229. // Create the framebuffer
  8230. var framebuffer = gl.createFramebuffer();
  8231. this.bindUnboundFramebuffer(framebuffer);
  8232. // Manage attachments
  8233. if (generateStencilBuffer) {
  8234. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8235. }
  8236. else if (generateDepthBuffer) {
  8237. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8238. }
  8239. // Mipmaps
  8240. if (texture.generateMipMaps) {
  8241. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8242. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8243. }
  8244. // Unbind
  8245. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8246. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8247. this.bindUnboundFramebuffer(null);
  8248. texture._framebuffer = framebuffer;
  8249. if (generateDepthBuffer) {
  8250. texture._depthBuffer = depthStencilBuffer;
  8251. }
  8252. texture._width = size;
  8253. texture._height = size;
  8254. texture.isReady = true;
  8255. this.resetTextureCache();
  8256. this._loadedTexturesCache.push(texture);
  8257. return texture;
  8258. };
  8259. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8260. var _this = this;
  8261. if (onLoad === void 0) { onLoad = null; }
  8262. if (onError === void 0) { onError = null; }
  8263. var gl = this._gl;
  8264. var texture = gl.createTexture();
  8265. texture.isCube = true;
  8266. texture.url = rootUrl;
  8267. texture.references = 1;
  8268. texture.onLoadedCallbacks = [];
  8269. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8270. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8271. if (isDDS) {
  8272. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8273. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8274. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8275. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8276. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8277. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8278. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8279. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8280. }
  8281. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8282. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8283. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8284. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8285. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8286. _this.resetTextureCache();
  8287. texture._width = info.width;
  8288. texture._height = info.height;
  8289. texture.isReady = true;
  8290. }, null, null, true, onError);
  8291. }
  8292. else {
  8293. cascadeLoad(rootUrl, scene, function (imgs) {
  8294. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8295. var height = width;
  8296. _this._prepareWorkingCanvas();
  8297. _this._workingCanvas.width = width;
  8298. _this._workingCanvas.height = height;
  8299. var faces = [
  8300. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8301. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8302. ];
  8303. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8304. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8305. for (var index = 0; index < faces.length; index++) {
  8306. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8307. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8308. }
  8309. if (!noMipmap) {
  8310. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8311. }
  8312. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8313. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8314. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8315. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8316. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8317. _this.resetTextureCache();
  8318. texture._width = width;
  8319. texture._height = height;
  8320. texture.isReady = true;
  8321. texture.onLoadedCallbacks.forEach(function (callback) {
  8322. callback();
  8323. });
  8324. if (onLoad) {
  8325. onLoad();
  8326. }
  8327. }, files, onError);
  8328. }
  8329. this._loadedTexturesCache.push(texture);
  8330. return texture;
  8331. };
  8332. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8333. texture._width = width;
  8334. texture._height = height;
  8335. texture._size = width * height;
  8336. texture._baseWidth = width;
  8337. texture._baseHeight = height;
  8338. };
  8339. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8340. var _this = this;
  8341. var gl = this._gl;
  8342. var texture = gl.createTexture();
  8343. scene._addPendingData(texture);
  8344. texture.isCube = true;
  8345. texture.references = 1;
  8346. texture.url = url;
  8347. var internalFormat = this._getInternalFormat(format);
  8348. var textureType = gl.UNSIGNED_BYTE;
  8349. if (type === Engine.TEXTURETYPE_FLOAT) {
  8350. textureType = gl.FLOAT;
  8351. }
  8352. var width = size;
  8353. var height = width;
  8354. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8355. texture._width = width;
  8356. texture._height = height;
  8357. var onerror = function () {
  8358. scene._removePendingData(texture);
  8359. };
  8360. var internalCallback = function (data) {
  8361. var rgbeDataArrays = callback(data);
  8362. var facesIndex = [
  8363. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8364. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8365. ];
  8366. width = texture._width;
  8367. height = texture._height;
  8368. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8369. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8370. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8371. if (!noMipmap && isPot) {
  8372. if (mipmmapGenerator) {
  8373. var arrayTemp = [];
  8374. // Data are known to be in +X +Y +Z -X -Y -Z
  8375. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8376. arrayTemp.push(rgbeDataArrays[0]); // +X
  8377. arrayTemp.push(rgbeDataArrays[3]); // -X
  8378. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8379. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8380. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8381. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8382. var mipData = mipmmapGenerator(arrayTemp);
  8383. for (var level = 0; level < mipData.length; level++) {
  8384. var mipSize = width >> level;
  8385. // mipData is order in +X -X +Y -Y +Z -Z
  8386. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8387. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8388. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8389. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8390. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8391. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8392. }
  8393. }
  8394. else {
  8395. // Data are known to be in +X +Y +Z -X -Y -Z
  8396. for (var index = 0; index < facesIndex.length; index++) {
  8397. var faceData = rgbeDataArrays[index];
  8398. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8399. }
  8400. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8401. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8402. // By following the webgl standard changes from Revision 7, 2014/11/24
  8403. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8404. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8405. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8406. // Data are known to be in +X +Y +Z -X -Y -Z
  8407. for (var index = 0; index < facesIndex.length; index++) {
  8408. var faceData = rgbeDataArrays[index];
  8409. // Create a new RGBA Face.
  8410. var newFaceData = new Float32Array(width * height * 4);
  8411. for (var x = 0; x < width; x++) {
  8412. for (var y = 0; y < height; y++) {
  8413. var index_1 = (y * width + x) * 3;
  8414. var newIndex = (y * width + x) * 4;
  8415. // Map Old Value to new value.
  8416. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8417. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8418. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8419. // Add fully opaque alpha channel.
  8420. newFaceData[newIndex + 3] = 1;
  8421. }
  8422. }
  8423. // Reupload the face.
  8424. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8425. }
  8426. // Try to generate mipmap again.
  8427. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8428. }
  8429. }
  8430. }
  8431. else {
  8432. noMipmap = true;
  8433. }
  8434. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8437. }
  8438. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8439. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8440. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8441. }
  8442. else {
  8443. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8444. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8445. }
  8446. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8447. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8448. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8449. texture.isReady = true;
  8450. _this.resetTextureCache();
  8451. scene._removePendingData(texture);
  8452. };
  8453. BABYLON.Tools.LoadFile(url, function (data) {
  8454. internalCallback(data);
  8455. }, onerror, scene.database, true);
  8456. return texture;
  8457. };
  8458. ;
  8459. Engine.prototype._releaseTexture = function (texture) {
  8460. var gl = this._gl;
  8461. if (texture._framebuffer) {
  8462. gl.deleteFramebuffer(texture._framebuffer);
  8463. }
  8464. if (texture._depthBuffer) {
  8465. gl.deleteRenderbuffer(texture._depthBuffer);
  8466. }
  8467. gl.deleteTexture(texture);
  8468. // Unbind channels
  8469. this.unbindAllTextures();
  8470. var index = this._loadedTexturesCache.indexOf(texture);
  8471. if (index !== -1) {
  8472. this._loadedTexturesCache.splice(index, 1);
  8473. }
  8474. };
  8475. Engine.prototype.setProgram = function (program) {
  8476. if (this._currentProgram !== program) {
  8477. this._gl.useProgram(program);
  8478. this._currentProgram = program;
  8479. }
  8480. };
  8481. Engine.prototype.bindSamplers = function (effect) {
  8482. this.setProgram(effect.getProgram());
  8483. var samplers = effect.getSamplers();
  8484. for (var index = 0; index < samplers.length; index++) {
  8485. var uniform = effect.getUniform(samplers[index]);
  8486. this._gl.uniform1i(uniform, index);
  8487. }
  8488. this._currentEffect = null;
  8489. };
  8490. Engine.prototype.activateTexture = function (texture) {
  8491. if (this._activeTexture !== texture) {
  8492. this._gl.activeTexture(texture);
  8493. this._activeTexture = texture;
  8494. }
  8495. };
  8496. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8497. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8498. this._gl.bindTexture(target, texture);
  8499. this._activeTexturesCache[this._activeTexture] = texture;
  8500. }
  8501. };
  8502. Engine.prototype._bindTexture = function (channel, texture) {
  8503. if (channel < 0) {
  8504. return;
  8505. }
  8506. this.activateTexture(this._gl["TEXTURE" + channel]);
  8507. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8508. };
  8509. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8510. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8511. };
  8512. Engine.prototype.unbindAllTextures = function () {
  8513. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8514. this.activateTexture(this._gl["TEXTURE" + channel]);
  8515. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8516. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8517. }
  8518. };
  8519. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8520. if (channel < 0) {
  8521. return;
  8522. }
  8523. this._gl.uniform1i(uniform, channel);
  8524. this._setTexture(channel, texture);
  8525. };
  8526. Engine.prototype._setTexture = function (channel, texture) {
  8527. // Not ready?
  8528. if (!texture || !texture.isReady()) {
  8529. if (this._activeTexturesCache[channel] != null) {
  8530. this.activateTexture(this._gl["TEXTURE" + channel]);
  8531. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8532. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8533. }
  8534. return;
  8535. }
  8536. // Video
  8537. var alreadyActivated = false;
  8538. if (texture instanceof BABYLON.VideoTexture) {
  8539. this.activateTexture(this._gl["TEXTURE" + channel]);
  8540. alreadyActivated = true;
  8541. texture.update();
  8542. }
  8543. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8544. texture.delayLoad();
  8545. return;
  8546. }
  8547. var internalTexture = texture.getInternalTexture();
  8548. if (this._activeTexturesCache[channel] === internalTexture) {
  8549. return;
  8550. }
  8551. if (!alreadyActivated) {
  8552. this.activateTexture(this._gl["TEXTURE" + channel]);
  8553. }
  8554. if (internalTexture.isCube) {
  8555. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8556. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8557. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8558. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8559. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8560. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8561. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8562. }
  8563. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8564. }
  8565. else {
  8566. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8567. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8568. internalTexture._cachedWrapU = texture.wrapU;
  8569. switch (texture.wrapU) {
  8570. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8571. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8572. break;
  8573. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8574. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8575. break;
  8576. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8577. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8578. break;
  8579. }
  8580. }
  8581. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8582. internalTexture._cachedWrapV = texture.wrapV;
  8583. switch (texture.wrapV) {
  8584. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8585. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8586. break;
  8587. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8588. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8589. break;
  8590. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8591. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8592. break;
  8593. }
  8594. }
  8595. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8596. }
  8597. };
  8598. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8599. if (channel < 0) {
  8600. return;
  8601. }
  8602. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8603. this._textureUnits = new Int32Array(textures.length);
  8604. }
  8605. for (var i = 0; i < textures.length; i++) {
  8606. this._textureUnits[i] = channel + i;
  8607. }
  8608. this._gl.uniform1iv(uniform, this._textureUnits);
  8609. for (var index = 0; index < textures.length; index++) {
  8610. this._setTexture(channel + index, textures[index]);
  8611. }
  8612. };
  8613. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8614. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8615. var value = texture.anisotropicFilteringLevel;
  8616. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8617. value = 1;
  8618. }
  8619. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8620. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8621. texture._cachedAnisotropicFilteringLevel = value;
  8622. }
  8623. };
  8624. Engine.prototype.readPixels = function (x, y, width, height) {
  8625. var data = new Uint8Array(height * width * 4);
  8626. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8627. return data;
  8628. };
  8629. /**
  8630. * Add an externaly attached data from its key.
  8631. * This method call will fail and return false, if such key already exists.
  8632. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8633. * @param key the unique key that identifies the data
  8634. * @param data the data object to associate to the key for this Engine instance
  8635. * @return true if no such key were already present and the data was added successfully, false otherwise
  8636. */
  8637. Engine.prototype.addExternalData = function (key, data) {
  8638. return this._externalData.add(key, data);
  8639. };
  8640. /**
  8641. * Get an externaly attached data from its key
  8642. * @param key the unique key that identifies the data
  8643. * @return the associated data, if present (can be null), or undefined if not present
  8644. */
  8645. Engine.prototype.getExternalData = function (key) {
  8646. return this._externalData.get(key);
  8647. };
  8648. /**
  8649. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8650. * @param key the unique key that identifies the data
  8651. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8652. * @return the associated data, can be null if the factory returned null.
  8653. */
  8654. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8655. return this._externalData.getOrAddWithFactory(key, factory);
  8656. };
  8657. /**
  8658. * Remove an externaly attached data from the Engine instance
  8659. * @param key the unique key that identifies the data
  8660. * @return true if the data was successfully removed, false if it doesn't exist
  8661. */
  8662. Engine.prototype.removeExternalData = function (key) {
  8663. return this._externalData.remove(key);
  8664. };
  8665. Engine.prototype.releaseInternalTexture = function (texture) {
  8666. if (!texture) {
  8667. return;
  8668. }
  8669. texture.references--;
  8670. // Final reference ?
  8671. if (texture.references === 0) {
  8672. var texturesCache = this.getLoadedTexturesCache();
  8673. var index = texturesCache.indexOf(texture);
  8674. if (index > -1) {
  8675. texturesCache.splice(index, 1);
  8676. }
  8677. this._releaseTexture(texture);
  8678. }
  8679. };
  8680. Engine.prototype.unbindAllAttributes = function () {
  8681. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8682. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8683. continue;
  8684. }
  8685. this._gl.disableVertexAttribArray(i);
  8686. this._vertexAttribArraysEnabled[i] = false;
  8687. }
  8688. };
  8689. // Dispose
  8690. Engine.prototype.dispose = function () {
  8691. this.hideLoadingUI();
  8692. this.stopRenderLoop();
  8693. // Release scenes
  8694. while (this.scenes.length) {
  8695. this.scenes[0].dispose();
  8696. }
  8697. // Release audio engine
  8698. Engine.audioEngine.dispose();
  8699. // Release effects
  8700. for (var name in this._compiledEffects) {
  8701. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8702. }
  8703. // Unbind
  8704. this.unbindAllAttributes();
  8705. this._gl = null;
  8706. //WebVR
  8707. this.disableVR();
  8708. // Events
  8709. window.removeEventListener("blur", this._onBlur);
  8710. window.removeEventListener("focus", this._onFocus);
  8711. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8712. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8713. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8714. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8715. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8716. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8717. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8718. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8719. };
  8720. // Loading screen
  8721. Engine.prototype.displayLoadingUI = function () {
  8722. this._loadingScreen.displayLoadingUI();
  8723. };
  8724. Engine.prototype.hideLoadingUI = function () {
  8725. this._loadingScreen.hideLoadingUI();
  8726. };
  8727. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8728. get: function () {
  8729. return this._loadingScreen;
  8730. },
  8731. set: function (loadingScreen) {
  8732. this._loadingScreen = loadingScreen;
  8733. },
  8734. enumerable: true,
  8735. configurable: true
  8736. });
  8737. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8738. set: function (text) {
  8739. this._loadingScreen.loadingUIText = text;
  8740. },
  8741. enumerable: true,
  8742. configurable: true
  8743. });
  8744. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8745. set: function (color) {
  8746. this._loadingScreen.loadingUIBackgroundColor = color;
  8747. },
  8748. enumerable: true,
  8749. configurable: true
  8750. });
  8751. Engine.prototype.attachContextLostEvent = function (callback) {
  8752. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8753. };
  8754. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8755. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8756. };
  8757. // FPS
  8758. Engine.prototype.getFps = function () {
  8759. return this.fps;
  8760. };
  8761. Engine.prototype.getDeltaTime = function () {
  8762. return this.deltaTime;
  8763. };
  8764. Engine.prototype._measureFps = function () {
  8765. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8766. var length = this.previousFramesDuration.length;
  8767. if (length >= 2) {
  8768. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8769. }
  8770. if (length >= this.fpsRange) {
  8771. if (length > this.fpsRange) {
  8772. this.previousFramesDuration.splice(0, 1);
  8773. length = this.previousFramesDuration.length;
  8774. }
  8775. var sum = 0;
  8776. for (var id = 0; id < length - 1; id++) {
  8777. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8778. }
  8779. this.fps = 1000.0 / (sum / (length - 1));
  8780. }
  8781. };
  8782. Engine.prototype._canRenderToFloatTexture = function () {
  8783. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8784. };
  8785. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8786. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8787. };
  8788. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8789. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8790. var tempcanvas = document.createElement("canvas");
  8791. tempcanvas.height = 16;
  8792. tempcanvas.width = 16;
  8793. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8794. // extension.
  8795. var ext = gl.getExtension(extension);
  8796. if (!ext) {
  8797. return false;
  8798. }
  8799. // setup GLSL program
  8800. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8801. 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 }";
  8802. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8803. gl.useProgram(program);
  8804. // look up where the vertex data needs to go.
  8805. var positionLocation = gl.getAttribLocation(program, "a_position");
  8806. var colorLoc = gl.getUniformLocation(program, "u_color");
  8807. // provide texture coordinates for the rectangle.
  8808. var positionBuffer = gl.createBuffer();
  8809. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8810. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8811. -1.0, -1.0,
  8812. 1.0, -1.0,
  8813. -1.0, 1.0,
  8814. -1.0, 1.0,
  8815. 1.0, -1.0,
  8816. 1.0, 1.0]), gl.STATIC_DRAW);
  8817. gl.enableVertexAttribArray(positionLocation);
  8818. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8819. var whiteTex = gl.createTexture();
  8820. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8821. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8822. var tex = gl.createTexture();
  8823. gl.bindTexture(gl.TEXTURE_2D, tex);
  8824. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8825. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8826. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8827. var fb = gl.createFramebuffer();
  8828. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8829. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8830. var cleanup = function () {
  8831. gl.deleteProgram(program);
  8832. gl.disableVertexAttribArray(positionLocation);
  8833. gl.deleteBuffer(positionBuffer);
  8834. gl.deleteFramebuffer(fb);
  8835. gl.deleteTexture(whiteTex);
  8836. gl.deleteTexture(tex);
  8837. };
  8838. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8839. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8840. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8841. cleanup();
  8842. return false;
  8843. }
  8844. // Draw the rectangle.
  8845. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8846. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8847. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8848. gl.bindTexture(gl.TEXTURE_2D, tex);
  8849. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8850. gl.clearColor(1, 0, 0, 1);
  8851. gl.clear(gl.COLOR_BUFFER_BIT);
  8852. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8853. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8854. var pixel = new Uint8Array(4);
  8855. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8856. if (pixel[0] !== 0 ||
  8857. pixel[1] < 248 ||
  8858. pixel[2] < 248 ||
  8859. pixel[3] < 254) {
  8860. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8861. cleanup();
  8862. return false;
  8863. }
  8864. // Succesfully rendered to "format" texture.
  8865. cleanup();
  8866. return true;
  8867. };
  8868. // Statics
  8869. Engine.isSupported = function () {
  8870. try {
  8871. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8872. if (navigator.isCocoonJS) {
  8873. return true;
  8874. }
  8875. var tempcanvas = document.createElement("canvas");
  8876. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8877. return gl != null && !!window.WebGLRenderingContext;
  8878. }
  8879. catch (e) {
  8880. return false;
  8881. }
  8882. };
  8883. // Const statics
  8884. Engine._ALPHA_DISABLE = 0;
  8885. Engine._ALPHA_ADD = 1;
  8886. Engine._ALPHA_COMBINE = 2;
  8887. Engine._ALPHA_SUBTRACT = 3;
  8888. Engine._ALPHA_MULTIPLY = 4;
  8889. Engine._ALPHA_MAXIMIZED = 5;
  8890. Engine._ALPHA_ONEONE = 6;
  8891. Engine._DELAYLOADSTATE_NONE = 0;
  8892. Engine._DELAYLOADSTATE_LOADED = 1;
  8893. Engine._DELAYLOADSTATE_LOADING = 2;
  8894. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8895. Engine._TEXTUREFORMAT_ALPHA = 0;
  8896. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8897. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8898. Engine._TEXTUREFORMAT_RGB = 4;
  8899. Engine._TEXTUREFORMAT_RGBA = 5;
  8900. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8901. Engine._TEXTURETYPE_FLOAT = 1;
  8902. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8903. // Depht or Stencil test Constants.
  8904. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  8905. 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.
  8906. 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.
  8907. 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.
  8908. 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.
  8909. 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.
  8910. 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.
  8911. 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.
  8912. // Stencil Actions Constants.
  8913. Engine._KEEP = 0x1E00;
  8914. Engine._REPLACE = 0x1E01;
  8915. Engine._INCR = 0x1E02;
  8916. Engine._DECR = 0x1E03;
  8917. Engine._INVERT = 0x150A;
  8918. Engine._INCR_WRAP = 0x8507;
  8919. Engine._DECR_WRAP = 0x8508;
  8920. // Updatable statics so stick with vars here
  8921. Engine.CollisionsEpsilon = 0.001;
  8922. Engine.CodeRepository = "src/";
  8923. Engine.ShadersRepository = "src/Shaders/";
  8924. return Engine;
  8925. }());
  8926. BABYLON.Engine = Engine;
  8927. })(BABYLON || (BABYLON = {}));
  8928. var BABYLON;
  8929. (function (BABYLON) {
  8930. /**
  8931. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8932. */
  8933. var Node = (function () {
  8934. /**
  8935. * @constructor
  8936. * @param {string} name - the name and id to be given to this node
  8937. * @param {BABYLON.Scene} the scene this node will be added to
  8938. */
  8939. function Node(name, scene) {
  8940. this.state = "";
  8941. this.animations = new Array();
  8942. this._ranges = {};
  8943. this._childrenFlag = -1;
  8944. this._isEnabled = true;
  8945. this._isReady = true;
  8946. this._currentRenderId = -1;
  8947. this._parentRenderId = -1;
  8948. this.name = name;
  8949. this.id = name;
  8950. this._scene = scene;
  8951. this._initCache();
  8952. }
  8953. Object.defineProperty(Node.prototype, "parent", {
  8954. get: function () {
  8955. return this._parentNode;
  8956. },
  8957. set: function (parent) {
  8958. if (this._parentNode === parent) {
  8959. return;
  8960. }
  8961. if (this._parentNode) {
  8962. var index = this._parentNode._children.indexOf(this);
  8963. if (index !== -1) {
  8964. this._parentNode._children.splice(index, 1);
  8965. }
  8966. }
  8967. this._parentNode = parent;
  8968. if (this._parentNode) {
  8969. if (!this._parentNode._children) {
  8970. this._parentNode._children = new Array();
  8971. }
  8972. this._parentNode._children.push(this);
  8973. }
  8974. },
  8975. enumerable: true,
  8976. configurable: true
  8977. });
  8978. Node.prototype.getScene = function () {
  8979. return this._scene;
  8980. };
  8981. Node.prototype.getEngine = function () {
  8982. return this._scene.getEngine();
  8983. };
  8984. // override it in derived class
  8985. Node.prototype.getWorldMatrix = function () {
  8986. return BABYLON.Matrix.Identity();
  8987. };
  8988. // override it in derived class if you add new variables to the cache
  8989. // and call the parent class method
  8990. Node.prototype._initCache = function () {
  8991. this._cache = {};
  8992. this._cache.parent = undefined;
  8993. };
  8994. Node.prototype.updateCache = function (force) {
  8995. if (!force && this.isSynchronized())
  8996. return;
  8997. this._cache.parent = this.parent;
  8998. this._updateCache();
  8999. };
  9000. // override it in derived class if you add new variables to the cache
  9001. // and call the parent class method if !ignoreParentClass
  9002. Node.prototype._updateCache = function (ignoreParentClass) {
  9003. };
  9004. // override it in derived class if you add new variables to the cache
  9005. Node.prototype._isSynchronized = function () {
  9006. return true;
  9007. };
  9008. Node.prototype._markSyncedWithParent = function () {
  9009. this._parentRenderId = this.parent._currentRenderId;
  9010. };
  9011. Node.prototype.isSynchronizedWithParent = function () {
  9012. if (!this.parent) {
  9013. return true;
  9014. }
  9015. if (this._parentRenderId !== this.parent._currentRenderId) {
  9016. return false;
  9017. }
  9018. return this.parent.isSynchronized();
  9019. };
  9020. Node.prototype.isSynchronized = function (updateCache) {
  9021. var check = this.hasNewParent();
  9022. check = check || !this.isSynchronizedWithParent();
  9023. check = check || !this._isSynchronized();
  9024. if (updateCache)
  9025. this.updateCache(true);
  9026. return !check;
  9027. };
  9028. Node.prototype.hasNewParent = function (update) {
  9029. if (this._cache.parent === this.parent)
  9030. return false;
  9031. if (update)
  9032. this._cache.parent = this.parent;
  9033. return true;
  9034. };
  9035. /**
  9036. * Is this node ready to be used/rendered
  9037. * @return {boolean} is it ready
  9038. */
  9039. Node.prototype.isReady = function () {
  9040. return this._isReady;
  9041. };
  9042. /**
  9043. * Is this node enabled.
  9044. * If the node has a parent and is enabled, the parent will be inspected as well.
  9045. * @return {boolean} whether this node (and its parent) is enabled.
  9046. * @see setEnabled
  9047. */
  9048. Node.prototype.isEnabled = function () {
  9049. if (!this._isEnabled) {
  9050. return false;
  9051. }
  9052. if (this.parent) {
  9053. return this.parent.isEnabled();
  9054. }
  9055. return true;
  9056. };
  9057. /**
  9058. * Set the enabled state of this node.
  9059. * @param {boolean} value - the new enabled state
  9060. * @see isEnabled
  9061. */
  9062. Node.prototype.setEnabled = function (value) {
  9063. this._isEnabled = value;
  9064. };
  9065. /**
  9066. * Is this node a descendant of the given node.
  9067. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9068. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9069. * @see parent
  9070. */
  9071. Node.prototype.isDescendantOf = function (ancestor) {
  9072. if (this.parent) {
  9073. if (this.parent === ancestor) {
  9074. return true;
  9075. }
  9076. return this.parent.isDescendantOf(ancestor);
  9077. }
  9078. return false;
  9079. };
  9080. /**
  9081. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9082. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9083. * @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.
  9084. * @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.
  9085. */
  9086. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9087. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9088. if (!this._children) {
  9089. return;
  9090. }
  9091. for (var index = 0; index < this._children.length; index++) {
  9092. var item = this._children[index];
  9093. if (!predicate || predicate(item)) {
  9094. results.push(item);
  9095. }
  9096. if (!directDescendantsOnly) {
  9097. item._getDescendants(results, false, predicate);
  9098. }
  9099. }
  9100. };
  9101. /**
  9102. * Will return all nodes that have this node as ascendant.
  9103. * @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.
  9104. * @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.
  9105. * @return {BABYLON.Node[]} all children nodes of all types.
  9106. */
  9107. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9108. var results = [];
  9109. this._getDescendants(results, directDescendantsOnly, predicate);
  9110. return results;
  9111. };
  9112. /**
  9113. * @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.
  9114. * @Deprecated, legacy support.
  9115. * use getDecendants instead.
  9116. */
  9117. Node.prototype.getChildren = function (predicate) {
  9118. return this.getDescendants(true, predicate);
  9119. };
  9120. /**
  9121. * Get all child-meshes of this node.
  9122. */
  9123. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9124. var results = [];
  9125. this._getDescendants(results, directDecendantsOnly, function (node) {
  9126. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9127. });
  9128. return results;
  9129. };
  9130. Node.prototype._setReady = function (state) {
  9131. if (state === this._isReady) {
  9132. return;
  9133. }
  9134. if (!state) {
  9135. this._isReady = false;
  9136. return;
  9137. }
  9138. this._isReady = true;
  9139. if (this.onReady) {
  9140. this.onReady(this);
  9141. }
  9142. };
  9143. Node.prototype.getAnimationByName = function (name) {
  9144. for (var i = 0; i < this.animations.length; i++) {
  9145. var animation = this.animations[i];
  9146. if (animation.name === name) {
  9147. return animation;
  9148. }
  9149. }
  9150. return null;
  9151. };
  9152. Node.prototype.createAnimationRange = function (name, from, to) {
  9153. // check name not already in use
  9154. if (!this._ranges[name]) {
  9155. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9156. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9157. if (this.animations[i]) {
  9158. this.animations[i].createRange(name, from, to);
  9159. }
  9160. }
  9161. }
  9162. };
  9163. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9164. if (deleteFrames === void 0) { deleteFrames = true; }
  9165. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9166. if (this.animations[i]) {
  9167. this.animations[i].deleteRange(name, deleteFrames);
  9168. }
  9169. }
  9170. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9171. };
  9172. Node.prototype.getAnimationRange = function (name) {
  9173. return this._ranges[name];
  9174. };
  9175. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9176. var range = this.getAnimationRange(name);
  9177. if (!range) {
  9178. return null;
  9179. }
  9180. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9181. };
  9182. Node.prototype.serializeAnimationRanges = function () {
  9183. var serializationRanges = [];
  9184. for (var name in this._ranges) {
  9185. var range = {};
  9186. range.name = name;
  9187. range.from = this._ranges[name].from;
  9188. range.to = this._ranges[name].to;
  9189. serializationRanges.push(range);
  9190. }
  9191. return serializationRanges;
  9192. };
  9193. Node.prototype.dispose = function () {
  9194. this.parent = null;
  9195. };
  9196. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9197. if (parsedNode.ranges) {
  9198. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9199. var data = parsedNode.ranges[index];
  9200. node.createAnimationRange(data.name, data.from, data.to);
  9201. }
  9202. }
  9203. };
  9204. __decorate([
  9205. BABYLON.serialize()
  9206. ], Node.prototype, "name", void 0);
  9207. __decorate([
  9208. BABYLON.serialize()
  9209. ], Node.prototype, "id", void 0);
  9210. __decorate([
  9211. BABYLON.serialize()
  9212. ], Node.prototype, "uniqueId", void 0);
  9213. __decorate([
  9214. BABYLON.serialize()
  9215. ], Node.prototype, "state", void 0);
  9216. return Node;
  9217. }());
  9218. BABYLON.Node = Node;
  9219. })(BABYLON || (BABYLON = {}));
  9220. var BABYLON;
  9221. (function (BABYLON) {
  9222. var FilesInput = (function () {
  9223. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9224. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9225. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9226. this._engine = p_engine;
  9227. this._canvas = p_canvas;
  9228. this._currentScene = p_scene;
  9229. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9230. this._progressCallback = p_progressCallback;
  9231. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9232. this._textureLoadingCallback = p_textureLoadingCallback;
  9233. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9234. }
  9235. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9236. var _this = this;
  9237. if (p_elementToMonitor) {
  9238. this._elementToMonitor = p_elementToMonitor;
  9239. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9240. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9241. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9242. }
  9243. };
  9244. FilesInput.prototype.renderFunction = function () {
  9245. if (this._additionnalRenderLoopLogicCallback) {
  9246. this._additionnalRenderLoopLogicCallback();
  9247. }
  9248. if (this._currentScene) {
  9249. if (this._textureLoadingCallback) {
  9250. var remaining = this._currentScene.getWaitingItemsCount();
  9251. if (remaining > 0) {
  9252. this._textureLoadingCallback(remaining);
  9253. }
  9254. }
  9255. this._currentScene.render();
  9256. }
  9257. };
  9258. FilesInput.prototype.drag = function (e) {
  9259. e.stopPropagation();
  9260. e.preventDefault();
  9261. };
  9262. FilesInput.prototype.drop = function (eventDrop) {
  9263. eventDrop.stopPropagation();
  9264. eventDrop.preventDefault();
  9265. this.loadFiles(eventDrop);
  9266. };
  9267. FilesInput.prototype.loadFiles = function (event) {
  9268. if (this._startingProcessingFilesCallback)
  9269. this._startingProcessingFilesCallback();
  9270. // Handling data transfer via drag'n'drop
  9271. if (event && event.dataTransfer && event.dataTransfer.files) {
  9272. this._filesToLoad = event.dataTransfer.files;
  9273. }
  9274. // Handling files from input files
  9275. if (event && event.target && event.target.files) {
  9276. this._filesToLoad = event.target.files;
  9277. }
  9278. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9279. for (var i = 0; i < this._filesToLoad.length; i++) {
  9280. switch (this._filesToLoad[i].type) {
  9281. case "image/jpeg":
  9282. case "image/png":
  9283. case "image/bmp":
  9284. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9285. break;
  9286. case "image/targa":
  9287. case "image/vnd.ms-dds":
  9288. case "audio/wav":
  9289. case "audio/x-wav":
  9290. case "audio/mp3":
  9291. case "audio/mpeg":
  9292. case "audio/mpeg3":
  9293. case "audio/x-mpeg-3":
  9294. case "audio/ogg":
  9295. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9296. break;
  9297. default:
  9298. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9299. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9300. }
  9301. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9302. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9303. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9304. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9305. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9306. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9307. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9308. this._sceneFileToLoad = this._filesToLoad[i];
  9309. }
  9310. break;
  9311. }
  9312. }
  9313. this.reload();
  9314. }
  9315. };
  9316. FilesInput.prototype.reload = function () {
  9317. var _this = this;
  9318. var that = this;
  9319. // If a ".babylon" file has been provided
  9320. if (this._sceneFileToLoad) {
  9321. if (this._currentScene) {
  9322. if (BABYLON.Tools.errorsCount > 0) {
  9323. BABYLON.Tools.ClearLogCache();
  9324. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9325. }
  9326. this._engine.stopRenderLoop();
  9327. this._currentScene.dispose();
  9328. }
  9329. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9330. that._currentScene = newScene;
  9331. // Wait for textures and shaders to be ready
  9332. that._currentScene.executeWhenReady(function () {
  9333. // Attach camera to canvas inputs
  9334. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9335. that._currentScene.createDefaultCameraOrLight();
  9336. }
  9337. that._currentScene.activeCamera.attachControl(that._canvas);
  9338. if (that._sceneLoadedCallback) {
  9339. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9340. }
  9341. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9342. });
  9343. }, function (progress) {
  9344. if (_this._progressCallback) {
  9345. _this._progressCallback(progress);
  9346. }
  9347. });
  9348. }
  9349. else {
  9350. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9351. }
  9352. };
  9353. FilesInput.FilesTextures = new Array();
  9354. FilesInput.FilesToLoad = new Array();
  9355. return FilesInput;
  9356. }());
  9357. BABYLON.FilesInput = FilesInput;
  9358. })(BABYLON || (BABYLON = {}));
  9359. var BABYLON;
  9360. (function (BABYLON) {
  9361. var IntersectionInfo = (function () {
  9362. function IntersectionInfo(bu, bv, distance) {
  9363. this.bu = bu;
  9364. this.bv = bv;
  9365. this.distance = distance;
  9366. this.faceId = 0;
  9367. this.subMeshId = 0;
  9368. }
  9369. return IntersectionInfo;
  9370. }());
  9371. BABYLON.IntersectionInfo = IntersectionInfo;
  9372. var PickingInfo = (function () {
  9373. function PickingInfo() {
  9374. this.hit = false;
  9375. this.distance = 0;
  9376. this.pickedPoint = null;
  9377. this.pickedMesh = null;
  9378. this.bu = 0;
  9379. this.bv = 0;
  9380. this.faceId = -1;
  9381. this.subMeshId = 0;
  9382. this.pickedSprite = null;
  9383. }
  9384. // Methods
  9385. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9386. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9387. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9388. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9389. return null;
  9390. }
  9391. var indices = this.pickedMesh.getIndices();
  9392. var result;
  9393. if (useVerticesNormals) {
  9394. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9395. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9396. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9397. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9398. normal0 = normal0.scale(this.bu);
  9399. normal1 = normal1.scale(this.bv);
  9400. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9401. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9402. }
  9403. else {
  9404. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9405. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9406. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9407. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9408. var p1p2 = vertex1.subtract(vertex2);
  9409. var p3p2 = vertex3.subtract(vertex2);
  9410. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9411. }
  9412. if (useWorldCoordinates) {
  9413. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9414. }
  9415. return BABYLON.Vector3.Normalize(result);
  9416. };
  9417. PickingInfo.prototype.getTextureCoordinates = function () {
  9418. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9419. return null;
  9420. }
  9421. var indices = this.pickedMesh.getIndices();
  9422. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9423. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9424. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9425. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9426. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9427. uv1 = uv1.scale(this.bu);
  9428. uv2 = uv2.scale(this.bv);
  9429. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9430. };
  9431. return PickingInfo;
  9432. }());
  9433. BABYLON.PickingInfo = PickingInfo;
  9434. })(BABYLON || (BABYLON = {}));
  9435. var BABYLON;
  9436. (function (BABYLON) {
  9437. var BoundingSphere = (function () {
  9438. function BoundingSphere(minimum, maximum) {
  9439. this.minimum = minimum;
  9440. this.maximum = maximum;
  9441. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9442. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9443. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9444. this.radius = distance * 0.5;
  9445. this.centerWorld = BABYLON.Vector3.Zero();
  9446. this._update(BABYLON.Matrix.Identity());
  9447. }
  9448. // Methods
  9449. BoundingSphere.prototype._update = function (world) {
  9450. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9451. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9452. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9453. };
  9454. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9455. for (var i = 0; i < 6; i++) {
  9456. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9457. return false;
  9458. }
  9459. return true;
  9460. };
  9461. BoundingSphere.prototype.intersectsPoint = function (point) {
  9462. var x = this.centerWorld.x - point.x;
  9463. var y = this.centerWorld.y - point.y;
  9464. var z = this.centerWorld.z - point.z;
  9465. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9466. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9467. return false;
  9468. return true;
  9469. };
  9470. // Statics
  9471. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9472. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9473. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9474. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9475. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9476. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9477. return false;
  9478. return true;
  9479. };
  9480. return BoundingSphere;
  9481. }());
  9482. BABYLON.BoundingSphere = BoundingSphere;
  9483. })(BABYLON || (BABYLON = {}));
  9484. var BABYLON;
  9485. (function (BABYLON) {
  9486. var BoundingBox = (function () {
  9487. function BoundingBox(minimum, maximum) {
  9488. this.minimum = minimum;
  9489. this.maximum = maximum;
  9490. this.vectors = new Array();
  9491. this.vectorsWorld = new Array();
  9492. // Bounding vectors
  9493. this.vectors.push(this.minimum.clone());
  9494. this.vectors.push(this.maximum.clone());
  9495. this.vectors.push(this.minimum.clone());
  9496. this.vectors[2].x = this.maximum.x;
  9497. this.vectors.push(this.minimum.clone());
  9498. this.vectors[3].y = this.maximum.y;
  9499. this.vectors.push(this.minimum.clone());
  9500. this.vectors[4].z = this.maximum.z;
  9501. this.vectors.push(this.maximum.clone());
  9502. this.vectors[5].z = this.minimum.z;
  9503. this.vectors.push(this.maximum.clone());
  9504. this.vectors[6].x = this.minimum.x;
  9505. this.vectors.push(this.maximum.clone());
  9506. this.vectors[7].y = this.minimum.y;
  9507. // OBB
  9508. this.center = this.maximum.add(this.minimum).scale(0.5);
  9509. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9510. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9511. // World
  9512. for (var index = 0; index < this.vectors.length; index++) {
  9513. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9514. }
  9515. this.minimumWorld = BABYLON.Vector3.Zero();
  9516. this.maximumWorld = BABYLON.Vector3.Zero();
  9517. this._update(BABYLON.Matrix.Identity());
  9518. }
  9519. // Methods
  9520. BoundingBox.prototype.getWorldMatrix = function () {
  9521. return this._worldMatrix;
  9522. };
  9523. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9524. this._worldMatrix.copyFrom(matrix);
  9525. return this;
  9526. };
  9527. BoundingBox.prototype._update = function (world) {
  9528. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9529. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9530. for (var index = 0; index < this.vectors.length; index++) {
  9531. var v = this.vectorsWorld[index];
  9532. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9533. if (v.x < this.minimumWorld.x)
  9534. this.minimumWorld.x = v.x;
  9535. if (v.y < this.minimumWorld.y)
  9536. this.minimumWorld.y = v.y;
  9537. if (v.z < this.minimumWorld.z)
  9538. this.minimumWorld.z = v.z;
  9539. if (v.x > this.maximumWorld.x)
  9540. this.maximumWorld.x = v.x;
  9541. if (v.y > this.maximumWorld.y)
  9542. this.maximumWorld.y = v.y;
  9543. if (v.z > this.maximumWorld.z)
  9544. this.maximumWorld.z = v.z;
  9545. }
  9546. // OBB
  9547. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9548. this.center.scaleInPlace(0.5);
  9549. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9550. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9551. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9552. this._worldMatrix = world;
  9553. };
  9554. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9555. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9556. };
  9557. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9558. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9559. };
  9560. BoundingBox.prototype.intersectsPoint = function (point) {
  9561. var delta = -BABYLON.Epsilon;
  9562. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9563. return false;
  9564. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9565. return false;
  9566. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9567. return false;
  9568. return true;
  9569. };
  9570. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9571. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9572. };
  9573. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9574. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9575. return false;
  9576. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9577. return false;
  9578. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9579. return false;
  9580. return true;
  9581. };
  9582. // Statics
  9583. BoundingBox.Intersects = function (box0, box1) {
  9584. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9585. return false;
  9586. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9587. return false;
  9588. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9589. return false;
  9590. return true;
  9591. };
  9592. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9593. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9594. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9595. return (num <= (sphereRadius * sphereRadius));
  9596. };
  9597. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9598. for (var p = 0; p < 6; p++) {
  9599. for (var i = 0; i < 8; i++) {
  9600. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9601. return false;
  9602. }
  9603. }
  9604. }
  9605. return true;
  9606. };
  9607. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9608. for (var p = 0; p < 6; p++) {
  9609. var inCount = 8;
  9610. for (var i = 0; i < 8; i++) {
  9611. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9612. --inCount;
  9613. }
  9614. else {
  9615. break;
  9616. }
  9617. }
  9618. if (inCount === 0)
  9619. return false;
  9620. }
  9621. return true;
  9622. };
  9623. return BoundingBox;
  9624. }());
  9625. BABYLON.BoundingBox = BoundingBox;
  9626. })(BABYLON || (BABYLON = {}));
  9627. var BABYLON;
  9628. (function (BABYLON) {
  9629. var computeBoxExtents = function (axis, box) {
  9630. var p = BABYLON.Vector3.Dot(box.center, axis);
  9631. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9632. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9633. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9634. var r = r0 + r1 + r2;
  9635. return {
  9636. min: p - r,
  9637. max: p + r
  9638. };
  9639. };
  9640. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9641. var axisOverlap = function (axis, box0, box1) {
  9642. var result0 = computeBoxExtents(axis, box0);
  9643. var result1 = computeBoxExtents(axis, box1);
  9644. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9645. };
  9646. var BoundingInfo = (function () {
  9647. function BoundingInfo(minimum, maximum) {
  9648. this.minimum = minimum;
  9649. this.maximum = maximum;
  9650. this._isLocked = false;
  9651. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9652. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9653. }
  9654. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9655. get: function () {
  9656. return this._isLocked;
  9657. },
  9658. set: function (value) {
  9659. this._isLocked = value;
  9660. },
  9661. enumerable: true,
  9662. configurable: true
  9663. });
  9664. // Methods
  9665. BoundingInfo.prototype.update = function (world) {
  9666. if (this._isLocked) {
  9667. return;
  9668. }
  9669. this.boundingBox._update(world);
  9670. this.boundingSphere._update(world);
  9671. };
  9672. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9673. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9674. return false;
  9675. return this.boundingBox.isInFrustum(frustumPlanes);
  9676. };
  9677. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9678. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9679. };
  9680. BoundingInfo.prototype._checkCollision = function (collider) {
  9681. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9682. };
  9683. BoundingInfo.prototype.intersectsPoint = function (point) {
  9684. if (!this.boundingSphere.centerWorld) {
  9685. return false;
  9686. }
  9687. if (!this.boundingSphere.intersectsPoint(point)) {
  9688. return false;
  9689. }
  9690. if (!this.boundingBox.intersectsPoint(point)) {
  9691. return false;
  9692. }
  9693. return true;
  9694. };
  9695. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9696. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9697. return false;
  9698. }
  9699. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9700. return false;
  9701. }
  9702. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9703. return false;
  9704. }
  9705. if (!precise) {
  9706. return true;
  9707. }
  9708. var box0 = this.boundingBox;
  9709. var box1 = boundingInfo.boundingBox;
  9710. if (!axisOverlap(box0.directions[0], box0, box1))
  9711. return false;
  9712. if (!axisOverlap(box0.directions[1], box0, box1))
  9713. return false;
  9714. if (!axisOverlap(box0.directions[2], box0, box1))
  9715. return false;
  9716. if (!axisOverlap(box1.directions[0], box0, box1))
  9717. return false;
  9718. if (!axisOverlap(box1.directions[1], box0, box1))
  9719. return false;
  9720. if (!axisOverlap(box1.directions[2], box0, box1))
  9721. return false;
  9722. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9723. return false;
  9724. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9725. return false;
  9726. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9727. return false;
  9728. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9729. return false;
  9730. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9731. return false;
  9732. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9733. return false;
  9734. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9735. return false;
  9736. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9737. return false;
  9738. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9739. return false;
  9740. return true;
  9741. };
  9742. return BoundingInfo;
  9743. }());
  9744. BABYLON.BoundingInfo = BoundingInfo;
  9745. })(BABYLON || (BABYLON = {}));
  9746. var BABYLON;
  9747. (function (BABYLON) {
  9748. var Ray = (function () {
  9749. function Ray(origin, direction, length) {
  9750. if (length === void 0) { length = Number.MAX_VALUE; }
  9751. this.origin = origin;
  9752. this.direction = direction;
  9753. this.length = length;
  9754. }
  9755. // Methods
  9756. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9757. var d = 0.0;
  9758. var maxValue = Number.MAX_VALUE;
  9759. var inv;
  9760. var min;
  9761. var max;
  9762. var temp;
  9763. if (Math.abs(this.direction.x) < 0.0000001) {
  9764. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9765. return false;
  9766. }
  9767. }
  9768. else {
  9769. inv = 1.0 / this.direction.x;
  9770. min = (minimum.x - this.origin.x) * inv;
  9771. max = (maximum.x - this.origin.x) * inv;
  9772. if (max === -Infinity) {
  9773. max = Infinity;
  9774. }
  9775. if (min > max) {
  9776. temp = min;
  9777. min = max;
  9778. max = temp;
  9779. }
  9780. d = Math.max(min, d);
  9781. maxValue = Math.min(max, maxValue);
  9782. if (d > maxValue) {
  9783. return false;
  9784. }
  9785. }
  9786. if (Math.abs(this.direction.y) < 0.0000001) {
  9787. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9788. return false;
  9789. }
  9790. }
  9791. else {
  9792. inv = 1.0 / this.direction.y;
  9793. min = (minimum.y - this.origin.y) * inv;
  9794. max = (maximum.y - this.origin.y) * inv;
  9795. if (max === -Infinity) {
  9796. max = Infinity;
  9797. }
  9798. if (min > max) {
  9799. temp = min;
  9800. min = max;
  9801. max = temp;
  9802. }
  9803. d = Math.max(min, d);
  9804. maxValue = Math.min(max, maxValue);
  9805. if (d > maxValue) {
  9806. return false;
  9807. }
  9808. }
  9809. if (Math.abs(this.direction.z) < 0.0000001) {
  9810. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9811. return false;
  9812. }
  9813. }
  9814. else {
  9815. inv = 1.0 / this.direction.z;
  9816. min = (minimum.z - this.origin.z) * inv;
  9817. max = (maximum.z - this.origin.z) * inv;
  9818. if (max === -Infinity) {
  9819. max = Infinity;
  9820. }
  9821. if (min > max) {
  9822. temp = min;
  9823. min = max;
  9824. max = temp;
  9825. }
  9826. d = Math.max(min, d);
  9827. maxValue = Math.min(max, maxValue);
  9828. if (d > maxValue) {
  9829. return false;
  9830. }
  9831. }
  9832. return true;
  9833. };
  9834. Ray.prototype.intersectsBox = function (box) {
  9835. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9836. };
  9837. Ray.prototype.intersectsSphere = function (sphere) {
  9838. var x = sphere.center.x - this.origin.x;
  9839. var y = sphere.center.y - this.origin.y;
  9840. var z = sphere.center.z - this.origin.z;
  9841. var pyth = (x * x) + (y * y) + (z * z);
  9842. var rr = sphere.radius * sphere.radius;
  9843. if (pyth <= rr) {
  9844. return true;
  9845. }
  9846. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9847. if (dot < 0.0) {
  9848. return false;
  9849. }
  9850. var temp = pyth - (dot * dot);
  9851. return temp <= rr;
  9852. };
  9853. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9854. if (!this._edge1) {
  9855. this._edge1 = BABYLON.Vector3.Zero();
  9856. this._edge2 = BABYLON.Vector3.Zero();
  9857. this._pvec = BABYLON.Vector3.Zero();
  9858. this._tvec = BABYLON.Vector3.Zero();
  9859. this._qvec = BABYLON.Vector3.Zero();
  9860. }
  9861. vertex1.subtractToRef(vertex0, this._edge1);
  9862. vertex2.subtractToRef(vertex0, this._edge2);
  9863. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9864. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9865. if (det === 0) {
  9866. return null;
  9867. }
  9868. var invdet = 1 / det;
  9869. this.origin.subtractToRef(vertex0, this._tvec);
  9870. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9871. if (bu < 0 || bu > 1.0) {
  9872. return null;
  9873. }
  9874. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9875. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9876. if (bv < 0 || bu + bv > 1.0) {
  9877. return null;
  9878. }
  9879. //check if the distance is longer than the predefined length.
  9880. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9881. if (distance > this.length) {
  9882. return null;
  9883. }
  9884. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9885. };
  9886. Ray.prototype.intersectsPlane = function (plane) {
  9887. var distance;
  9888. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9889. if (Math.abs(result1) < 9.99999997475243E-07) {
  9890. return null;
  9891. }
  9892. else {
  9893. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9894. distance = (-plane.d - result2) / result1;
  9895. if (distance < 0.0) {
  9896. if (distance < -9.99999997475243E-07) {
  9897. return null;
  9898. }
  9899. else {
  9900. return 0;
  9901. }
  9902. }
  9903. return distance;
  9904. }
  9905. };
  9906. /**
  9907. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9908. * @param sega the first point of the segment to test the intersection against
  9909. * @param segb the second point of the segment to test the intersection against
  9910. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9911. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9912. */
  9913. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9914. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9915. var u = segb.subtract(sega);
  9916. var v = rsegb.subtract(this.origin);
  9917. var w = sega.subtract(this.origin);
  9918. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9919. var b = BABYLON.Vector3.Dot(u, v);
  9920. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9921. var d = BABYLON.Vector3.Dot(u, w);
  9922. var e = BABYLON.Vector3.Dot(v, w);
  9923. var D = a * c - b * b; // always >= 0
  9924. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9925. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9926. // compute the line parameters of the two closest points
  9927. if (D < Ray.smallnum) {
  9928. sN = 0.0; // force using point P0 on segment S1
  9929. sD = 1.0; // to prevent possible division by 0.0 later
  9930. tN = e;
  9931. tD = c;
  9932. }
  9933. else {
  9934. sN = (b * e - c * d);
  9935. tN = (a * e - b * d);
  9936. if (sN < 0.0) {
  9937. sN = 0.0;
  9938. tN = e;
  9939. tD = c;
  9940. }
  9941. else if (sN > sD) {
  9942. sN = sD;
  9943. tN = e + b;
  9944. tD = c;
  9945. }
  9946. }
  9947. if (tN < 0.0) {
  9948. tN = 0.0;
  9949. // recompute sc for this edge
  9950. if (-d < 0.0) {
  9951. sN = 0.0;
  9952. }
  9953. else if (-d > a)
  9954. sN = sD;
  9955. else {
  9956. sN = -d;
  9957. sD = a;
  9958. }
  9959. }
  9960. else if (tN > tD) {
  9961. tN = tD;
  9962. // recompute sc for this edge
  9963. if ((-d + b) < 0.0) {
  9964. sN = 0;
  9965. }
  9966. else if ((-d + b) > a) {
  9967. sN = sD;
  9968. }
  9969. else {
  9970. sN = (-d + b);
  9971. sD = a;
  9972. }
  9973. }
  9974. // finally do the division to get sc and tc
  9975. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9976. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9977. // get the difference of the two closest points
  9978. var qtc = v.multiplyByFloats(tc, tc, tc);
  9979. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9980. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9981. if (isIntersected) {
  9982. return qtc.length();
  9983. }
  9984. return -1;
  9985. };
  9986. // Statics
  9987. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9988. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9989. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9990. var direction = end.subtract(start);
  9991. direction.normalize();
  9992. return new Ray(start, direction);
  9993. };
  9994. /**
  9995. * 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
  9996. * transformed to the given world matrix.
  9997. * @param origin The origin point
  9998. * @param end The end point
  9999. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10000. */
  10001. Ray.CreateNewFromTo = function (origin, end, world) {
  10002. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10003. var direction = end.subtract(origin);
  10004. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10005. direction.normalize();
  10006. return Ray.Transform(new Ray(origin, direction, length), world);
  10007. };
  10008. Ray.Transform = function (ray, matrix) {
  10009. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10010. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10011. newDirection.normalize();
  10012. return new Ray(newOrigin, newDirection, ray.length);
  10013. };
  10014. Ray.smallnum = 0.00000001;
  10015. Ray.rayl = 10e8;
  10016. return Ray;
  10017. }());
  10018. BABYLON.Ray = Ray;
  10019. })(BABYLON || (BABYLON = {}));
  10020. var BABYLON;
  10021. (function (BABYLON) {
  10022. var AbstractMesh = (function (_super) {
  10023. __extends(AbstractMesh, _super);
  10024. // Constructor
  10025. function AbstractMesh(name, scene) {
  10026. var _this = this;
  10027. _super.call(this, name, scene);
  10028. // Events
  10029. /**
  10030. * An event triggered when the mesh is disposed.
  10031. * @type {BABYLON.Observable}
  10032. */
  10033. this.onDisposeObservable = new BABYLON.Observable();
  10034. /**
  10035. * An event triggered when this mesh collides with another one
  10036. * @type {BABYLON.Observable}
  10037. */
  10038. this.onCollideObservable = new BABYLON.Observable();
  10039. /**
  10040. * An event triggered when the collision's position changes
  10041. * @type {BABYLON.Observable}
  10042. */
  10043. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10044. /**
  10045. * An event triggered after the world matrix is updated
  10046. * @type {BABYLON.Observable}
  10047. */
  10048. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10049. // Properties
  10050. this.definedFacingForward = true; // orientation for POV movement & rotation
  10051. this.position = new BABYLON.Vector3(0, 0, 0);
  10052. this._rotation = new BABYLON.Vector3(0, 0, 0);
  10053. this._scaling = new BABYLON.Vector3(1, 1, 1);
  10054. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10055. this.visibility = 1.0;
  10056. this.alphaIndex = Number.MAX_VALUE;
  10057. this.infiniteDistance = false;
  10058. this.isVisible = true;
  10059. this.isPickable = true;
  10060. this.showBoundingBox = false;
  10061. this.showSubMeshesBoundingBox = false;
  10062. this.isBlocker = false;
  10063. this.renderingGroupId = 0;
  10064. this.receiveShadows = false;
  10065. this.renderOutline = false;
  10066. this.outlineColor = BABYLON.Color3.Red();
  10067. this.outlineWidth = 0.02;
  10068. this.renderOverlay = false;
  10069. this.overlayColor = BABYLON.Color3.Red();
  10070. this.overlayAlpha = 0.5;
  10071. this.hasVertexAlpha = false;
  10072. this.useVertexColors = true;
  10073. this.applyFog = true;
  10074. this.computeBonesUsingShaders = true;
  10075. this.scalingDeterminant = 1;
  10076. this.numBoneInfluencers = 4;
  10077. this.useOctreeForRenderingSelection = true;
  10078. this.useOctreeForPicking = true;
  10079. this.useOctreeForCollisions = true;
  10080. this.layerMask = 0x0FFFFFFF;
  10081. this.alwaysSelectAsActiveMesh = false;
  10082. // Collisions
  10083. this._checkCollisions = false;
  10084. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10085. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10086. this._collider = new BABYLON.Collider();
  10087. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10088. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10089. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10090. // Edges
  10091. this.edgesWidth = 1;
  10092. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10093. // Cache
  10094. this._localWorld = BABYLON.Matrix.Zero();
  10095. this._worldMatrix = BABYLON.Matrix.Zero();
  10096. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10097. this._absolutePosition = BABYLON.Vector3.Zero();
  10098. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10099. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10100. this._isDirty = false;
  10101. this._pivotMatrix = BABYLON.Matrix.Identity();
  10102. this._isDisposed = false;
  10103. this._renderId = 0;
  10104. this._intersectionsInProgress = new Array();
  10105. this._isWorldMatrixFrozen = false;
  10106. this._unIndexed = false;
  10107. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10108. if (collidedMesh === void 0) { collidedMesh = null; }
  10109. //TODO move this to the collision coordinator!
  10110. if (_this.getScene().workerCollisions)
  10111. newPosition.multiplyInPlace(_this._collider.radius);
  10112. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10113. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10114. _this.position.addInPlace(_this._diffPositionForCollisions);
  10115. }
  10116. if (collidedMesh) {
  10117. _this.onCollideObservable.notifyObservers(collidedMesh);
  10118. }
  10119. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10120. };
  10121. scene.addMesh(this);
  10122. }
  10123. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10124. get: function () {
  10125. return AbstractMesh._BILLBOARDMODE_NONE;
  10126. },
  10127. enumerable: true,
  10128. configurable: true
  10129. });
  10130. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10131. get: function () {
  10132. return AbstractMesh._BILLBOARDMODE_X;
  10133. },
  10134. enumerable: true,
  10135. configurable: true
  10136. });
  10137. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10138. get: function () {
  10139. return AbstractMesh._BILLBOARDMODE_Y;
  10140. },
  10141. enumerable: true,
  10142. configurable: true
  10143. });
  10144. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10145. get: function () {
  10146. return AbstractMesh._BILLBOARDMODE_Z;
  10147. },
  10148. enumerable: true,
  10149. configurable: true
  10150. });
  10151. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10152. get: function () {
  10153. return AbstractMesh._BILLBOARDMODE_ALL;
  10154. },
  10155. enumerable: true,
  10156. configurable: true
  10157. });
  10158. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  10159. set: function (callback) {
  10160. if (this._onDisposeObserver) {
  10161. this.onDisposeObservable.remove(this._onDisposeObserver);
  10162. }
  10163. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10164. },
  10165. enumerable: true,
  10166. configurable: true
  10167. });
  10168. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10169. set: function (callback) {
  10170. if (this._onCollideObserver) {
  10171. this.onCollideObservable.remove(this._onCollideObserver);
  10172. }
  10173. this._onCollideObserver = this.onCollideObservable.add(callback);
  10174. },
  10175. enumerable: true,
  10176. configurable: true
  10177. });
  10178. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10179. set: function (callback) {
  10180. if (this._onCollisionPositionChangeObserver) {
  10181. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10182. }
  10183. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10184. },
  10185. enumerable: true,
  10186. configurable: true
  10187. });
  10188. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10189. get: function () {
  10190. return this._skeleton;
  10191. },
  10192. set: function (value) {
  10193. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10194. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10195. }
  10196. if (value && value.needInitialSkinMatrix) {
  10197. value._registerMeshWithPoseMatrix(this);
  10198. }
  10199. this._skeleton = value;
  10200. if (!this._skeleton) {
  10201. this._bonesTransformMatrices = null;
  10202. }
  10203. },
  10204. enumerable: true,
  10205. configurable: true
  10206. });
  10207. /**
  10208. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10209. */
  10210. AbstractMesh.prototype.toString = function (fullDetails) {
  10211. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10212. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10213. if (this._skeleton) {
  10214. ret += ", skeleton: " + this._skeleton.name;
  10215. }
  10216. if (fullDetails) {
  10217. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10218. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10219. }
  10220. return ret;
  10221. };
  10222. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10223. /**
  10224. * Getting the rotation object.
  10225. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10226. */
  10227. get: function () {
  10228. return this._rotation;
  10229. },
  10230. set: function (newRotation) {
  10231. this._rotation = newRotation;
  10232. },
  10233. enumerable: true,
  10234. configurable: true
  10235. });
  10236. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10237. get: function () {
  10238. return this._scaling;
  10239. },
  10240. set: function (newScaling) {
  10241. this._scaling = newScaling;
  10242. if (this.physicsImpostor) {
  10243. this.physicsImpostor.forceUpdate();
  10244. }
  10245. },
  10246. enumerable: true,
  10247. configurable: true
  10248. });
  10249. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10250. get: function () {
  10251. return this._rotationQuaternion;
  10252. },
  10253. set: function (quaternion) {
  10254. this._rotationQuaternion = quaternion;
  10255. //reset the rotation vector.
  10256. if (quaternion && this.rotation.length()) {
  10257. this.rotation.copyFromFloats(0, 0, 0);
  10258. }
  10259. },
  10260. enumerable: true,
  10261. configurable: true
  10262. });
  10263. // Methods
  10264. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10265. this._poseMatrix.copyFrom(matrix);
  10266. };
  10267. AbstractMesh.prototype.getPoseMatrix = function () {
  10268. return this._poseMatrix;
  10269. };
  10270. AbstractMesh.prototype.disableEdgesRendering = function () {
  10271. if (this._edgesRenderer !== undefined) {
  10272. this._edgesRenderer.dispose();
  10273. this._edgesRenderer = undefined;
  10274. }
  10275. };
  10276. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10277. if (epsilon === void 0) { epsilon = 0.95; }
  10278. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10279. this.disableEdgesRendering();
  10280. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10281. };
  10282. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10283. get: function () {
  10284. return false;
  10285. },
  10286. enumerable: true,
  10287. configurable: true
  10288. });
  10289. AbstractMesh.prototype.getLOD = function (camera) {
  10290. return this;
  10291. };
  10292. AbstractMesh.prototype.getTotalVertices = function () {
  10293. return 0;
  10294. };
  10295. AbstractMesh.prototype.getIndices = function () {
  10296. return null;
  10297. };
  10298. AbstractMesh.prototype.getVerticesData = function (kind) {
  10299. return null;
  10300. };
  10301. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10302. return false;
  10303. };
  10304. AbstractMesh.prototype.getBoundingInfo = function () {
  10305. if (this._masterMesh) {
  10306. return this._masterMesh.getBoundingInfo();
  10307. }
  10308. if (!this._boundingInfo) {
  10309. this._updateBoundingInfo();
  10310. }
  10311. return this._boundingInfo;
  10312. };
  10313. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10314. this._boundingInfo = boundingInfo;
  10315. };
  10316. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10317. get: function () {
  10318. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10319. },
  10320. enumerable: true,
  10321. configurable: true
  10322. });
  10323. AbstractMesh.prototype._preActivate = function () {
  10324. };
  10325. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10326. };
  10327. AbstractMesh.prototype._activate = function (renderId) {
  10328. this._renderId = renderId;
  10329. };
  10330. AbstractMesh.prototype.getWorldMatrix = function () {
  10331. if (this._masterMesh) {
  10332. return this._masterMesh.getWorldMatrix();
  10333. }
  10334. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10335. this.computeWorldMatrix();
  10336. }
  10337. return this._worldMatrix;
  10338. };
  10339. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10340. get: function () {
  10341. return this._worldMatrix;
  10342. },
  10343. enumerable: true,
  10344. configurable: true
  10345. });
  10346. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10347. get: function () {
  10348. return this._absolutePosition;
  10349. },
  10350. enumerable: true,
  10351. configurable: true
  10352. });
  10353. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10354. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10355. this.computeWorldMatrix(true);
  10356. this._isWorldMatrixFrozen = true;
  10357. };
  10358. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10359. this._isWorldMatrixFrozen = false;
  10360. this.computeWorldMatrix(true);
  10361. };
  10362. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10363. get: function () {
  10364. return this._isWorldMatrixFrozen;
  10365. },
  10366. enumerable: true,
  10367. configurable: true
  10368. });
  10369. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10370. axis.normalize();
  10371. if (!this.rotationQuaternion) {
  10372. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10373. this.rotation = BABYLON.Vector3.Zero();
  10374. }
  10375. var rotationQuaternion;
  10376. if (!space || space === BABYLON.Space.LOCAL) {
  10377. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10378. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10379. }
  10380. else {
  10381. if (this.parent) {
  10382. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10383. invertParentWorldMatrix.invert();
  10384. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10385. }
  10386. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10387. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10388. }
  10389. };
  10390. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10391. var displacementVector = axis.scale(distance);
  10392. if (!space || space === BABYLON.Space.LOCAL) {
  10393. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10394. this.setPositionWithLocalVector(tempV3);
  10395. }
  10396. else {
  10397. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10398. }
  10399. };
  10400. AbstractMesh.prototype.getAbsolutePosition = function () {
  10401. this.computeWorldMatrix();
  10402. return this._absolutePosition;
  10403. };
  10404. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10405. if (!absolutePosition) {
  10406. return;
  10407. }
  10408. var absolutePositionX;
  10409. var absolutePositionY;
  10410. var absolutePositionZ;
  10411. if (absolutePosition.x === undefined) {
  10412. if (arguments.length < 3) {
  10413. return;
  10414. }
  10415. absolutePositionX = arguments[0];
  10416. absolutePositionY = arguments[1];
  10417. absolutePositionZ = arguments[2];
  10418. }
  10419. else {
  10420. absolutePositionX = absolutePosition.x;
  10421. absolutePositionY = absolutePosition.y;
  10422. absolutePositionZ = absolutePosition.z;
  10423. }
  10424. if (this.parent) {
  10425. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10426. invertParentWorldMatrix.invert();
  10427. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10428. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10429. }
  10430. else {
  10431. this.position.x = absolutePositionX;
  10432. this.position.y = absolutePositionY;
  10433. this.position.z = absolutePositionZ;
  10434. }
  10435. };
  10436. // ================================== Point of View Movement =================================
  10437. /**
  10438. * Perform relative position change from the point of view of behind the front of the mesh.
  10439. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10440. * Supports definition of mesh facing forward or backward.
  10441. * @param {number} amountRight
  10442. * @param {number} amountUp
  10443. * @param {number} amountForward
  10444. */
  10445. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10446. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10447. };
  10448. /**
  10449. * Calculate relative position change from the point of view of behind the front of the mesh.
  10450. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10451. * Supports definition of mesh facing forward or backward.
  10452. * @param {number} amountRight
  10453. * @param {number} amountUp
  10454. * @param {number} amountForward
  10455. */
  10456. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10457. var rotMatrix = new BABYLON.Matrix();
  10458. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10459. rotQuaternion.toRotationMatrix(rotMatrix);
  10460. var translationDelta = BABYLON.Vector3.Zero();
  10461. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10462. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10463. return translationDelta;
  10464. };
  10465. // ================================== Point of View Rotation =================================
  10466. /**
  10467. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10468. * Supports definition of mesh facing forward or backward.
  10469. * @param {number} flipBack
  10470. * @param {number} twirlClockwise
  10471. * @param {number} tiltRight
  10472. */
  10473. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10474. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10475. };
  10476. /**
  10477. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10478. * Supports definition of mesh facing forward or backward.
  10479. * @param {number} flipBack
  10480. * @param {number} twirlClockwise
  10481. * @param {number} tiltRight
  10482. */
  10483. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10484. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10485. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10486. };
  10487. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10488. this._pivotMatrix = matrix;
  10489. this._cache.pivotMatrixUpdated = true;
  10490. };
  10491. AbstractMesh.prototype.getPivotMatrix = function () {
  10492. return this._pivotMatrix;
  10493. };
  10494. AbstractMesh.prototype._isSynchronized = function () {
  10495. if (this._isDirty) {
  10496. return false;
  10497. }
  10498. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10499. return false;
  10500. if (this._cache.pivotMatrixUpdated) {
  10501. return false;
  10502. }
  10503. if (this.infiniteDistance) {
  10504. return false;
  10505. }
  10506. if (!this._cache.position.equals(this.position))
  10507. return false;
  10508. if (this.rotationQuaternion) {
  10509. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10510. return false;
  10511. }
  10512. if (!this._cache.rotation.equals(this.rotation))
  10513. return false;
  10514. if (!this._cache.scaling.equals(this.scaling))
  10515. return false;
  10516. return true;
  10517. };
  10518. AbstractMesh.prototype._initCache = function () {
  10519. _super.prototype._initCache.call(this);
  10520. this._cache.localMatrixUpdated = false;
  10521. this._cache.position = BABYLON.Vector3.Zero();
  10522. this._cache.scaling = BABYLON.Vector3.Zero();
  10523. this._cache.rotation = BABYLON.Vector3.Zero();
  10524. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10525. this._cache.billboardMode = -1;
  10526. };
  10527. AbstractMesh.prototype.markAsDirty = function (property) {
  10528. if (property === "rotation") {
  10529. this.rotationQuaternion = null;
  10530. }
  10531. this._currentRenderId = Number.MAX_VALUE;
  10532. this._isDirty = true;
  10533. };
  10534. AbstractMesh.prototype._updateBoundingInfo = function () {
  10535. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10536. this._boundingInfo.update(this.worldMatrixFromCache);
  10537. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10538. };
  10539. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10540. if (!this.subMeshes) {
  10541. return;
  10542. }
  10543. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10544. var subMesh = this.subMeshes[subIndex];
  10545. if (!subMesh.IsGlobal) {
  10546. subMesh.updateBoundingInfo(matrix);
  10547. }
  10548. }
  10549. };
  10550. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10551. if (this._isWorldMatrixFrozen) {
  10552. return this._worldMatrix;
  10553. }
  10554. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10555. this._currentRenderId = this.getScene().getRenderId();
  10556. return this._worldMatrix;
  10557. }
  10558. this._cache.position.copyFrom(this.position);
  10559. this._cache.scaling.copyFrom(this.scaling);
  10560. this._cache.pivotMatrixUpdated = false;
  10561. this._cache.billboardMode = this.billboardMode;
  10562. this._currentRenderId = this.getScene().getRenderId();
  10563. this._isDirty = false;
  10564. // Scaling
  10565. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10566. // Rotation
  10567. //rotate, if quaternion is set and rotation was used
  10568. if (this.rotationQuaternion) {
  10569. var len = this.rotation.length();
  10570. if (len) {
  10571. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10572. this.rotation.copyFromFloats(0, 0, 0);
  10573. }
  10574. }
  10575. if (this.rotationQuaternion) {
  10576. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10577. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10578. }
  10579. else {
  10580. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10581. this._cache.rotation.copyFrom(this.rotation);
  10582. }
  10583. // Translation
  10584. if (this.infiniteDistance && !this.parent) {
  10585. var camera = this.getScene().activeCamera;
  10586. if (camera) {
  10587. var cameraWorldMatrix = camera.getWorldMatrix();
  10588. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10589. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10590. }
  10591. }
  10592. else {
  10593. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10594. }
  10595. // Composing transformations
  10596. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10597. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10598. // Billboarding
  10599. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10600. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10601. var localPosition = BABYLON.Tmp.Vector3[0];
  10602. if (this.parent && this.parent.getWorldMatrix) {
  10603. this._markSyncedWithParent();
  10604. var parentMatrix;
  10605. if (this._meshToBoneReferal) {
  10606. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10607. parentMatrix = BABYLON.Tmp.Matrix[6];
  10608. }
  10609. else {
  10610. parentMatrix = this.parent.getWorldMatrix();
  10611. }
  10612. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10613. localPosition = BABYLON.Tmp.Vector3[1];
  10614. }
  10615. var zero = this.getScene().activeCamera.globalPosition.clone();
  10616. if (this.parent && this.parent.position) {
  10617. localPosition.addInPlace(this.parent.position);
  10618. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10619. }
  10620. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10621. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10622. zero.x = localPosition.x + BABYLON.Epsilon;
  10623. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10624. zero.y = localPosition.y + BABYLON.Epsilon;
  10625. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10626. zero.z = localPosition.z + BABYLON.Epsilon;
  10627. }
  10628. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10629. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10630. BABYLON.Tmp.Matrix[3].invert();
  10631. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10632. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10633. }
  10634. // Local world
  10635. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10636. // Parent
  10637. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10638. this._markSyncedWithParent();
  10639. if (this._meshToBoneReferal) {
  10640. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10641. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10642. }
  10643. else {
  10644. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10645. }
  10646. }
  10647. else {
  10648. this._worldMatrix.copyFrom(this._localWorld);
  10649. }
  10650. // Bounding info
  10651. this._updateBoundingInfo();
  10652. // Absolute position
  10653. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10654. // Callbacks
  10655. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10656. if (!this._poseMatrix) {
  10657. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10658. }
  10659. return this._worldMatrix;
  10660. };
  10661. /**
  10662. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10663. * @param func: callback function to add
  10664. */
  10665. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10666. this.onAfterWorldMatrixUpdateObservable.add(func);
  10667. };
  10668. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10669. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10670. };
  10671. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10672. this.computeWorldMatrix();
  10673. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10674. };
  10675. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10676. this.computeWorldMatrix();
  10677. var invLocalWorldMatrix = this._localWorld.clone();
  10678. invLocalWorldMatrix.invert();
  10679. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10680. };
  10681. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10682. this.computeWorldMatrix(true);
  10683. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10684. };
  10685. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10686. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10687. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10688. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10689. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10690. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10691. /// <returns>Mesh oriented towards targetMesh</returns>
  10692. if (yawCor === void 0) { yawCor = 0; }
  10693. if (pitchCor === void 0) { pitchCor = 0; }
  10694. if (rollCor === void 0) { rollCor = 0; }
  10695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10696. var dv = AbstractMesh._lookAtVectorCache;
  10697. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10698. targetPoint.subtractToRef(pos, dv);
  10699. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10700. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10701. var pitch = Math.atan2(dv.y, len);
  10702. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10703. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10704. };
  10705. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10706. this._meshToBoneReferal = affectedMesh;
  10707. this.parent = bone;
  10708. if (bone.getWorldMatrix().determinant() < 0) {
  10709. this.scalingDeterminant *= -1;
  10710. }
  10711. };
  10712. AbstractMesh.prototype.detachFromBone = function () {
  10713. if (this.parent.getWorldMatrix().determinant() < 0) {
  10714. this.scalingDeterminant *= -1;
  10715. }
  10716. this._meshToBoneReferal = null;
  10717. this.parent = null;
  10718. };
  10719. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10720. return this._boundingInfo.isInFrustum(frustumPlanes);
  10721. };
  10722. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10723. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10724. ;
  10725. };
  10726. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10727. if (!this._boundingInfo || !mesh._boundingInfo) {
  10728. return false;
  10729. }
  10730. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10731. };
  10732. AbstractMesh.prototype.intersectsPoint = function (point) {
  10733. if (!this._boundingInfo) {
  10734. return false;
  10735. }
  10736. return this._boundingInfo.intersectsPoint(point);
  10737. };
  10738. // Physics
  10739. /**
  10740. * @Deprecated. Use new PhysicsImpostor instead.
  10741. * */
  10742. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10743. //legacy support
  10744. if (impostor.impostor) {
  10745. options = impostor;
  10746. impostor = impostor.impostor;
  10747. }
  10748. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10749. return this.physicsImpostor.physicsBody;
  10750. };
  10751. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10752. return this.physicsImpostor;
  10753. };
  10754. /**
  10755. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10756. */
  10757. AbstractMesh.prototype.getPhysicsMass = function () {
  10758. return this.physicsImpostor.getParam("mass");
  10759. };
  10760. /**
  10761. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10762. */
  10763. AbstractMesh.prototype.getPhysicsFriction = function () {
  10764. return this.physicsImpostor.getParam("friction");
  10765. };
  10766. /**
  10767. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10768. */
  10769. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10770. return this.physicsImpostor.getParam("restitution");
  10771. };
  10772. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10773. if (!camera) {
  10774. camera = this.getScene().activeCamera;
  10775. }
  10776. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10777. };
  10778. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10779. if (!camera) {
  10780. camera = this.getScene().activeCamera;
  10781. }
  10782. return this.absolutePosition.subtract(camera.position).length();
  10783. };
  10784. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10785. if (!this.physicsImpostor) {
  10786. return;
  10787. }
  10788. this.physicsImpostor.applyImpulse(force, contactPoint);
  10789. };
  10790. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10791. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10792. return;
  10793. }
  10794. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10795. mainPivot: pivot1,
  10796. connectedPivot: pivot2,
  10797. nativeParams: options
  10798. });
  10799. };
  10800. /**
  10801. * @Deprecated
  10802. */
  10803. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10804. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10805. this.updatePhysicsBody();
  10806. };
  10807. /**
  10808. * @Deprecated
  10809. * Calling this function is not needed anymore.
  10810. * The physics engine takes care of transofmration automatically.
  10811. */
  10812. AbstractMesh.prototype.updatePhysicsBody = function () {
  10813. //Unneeded
  10814. };
  10815. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10816. // Collisions
  10817. get: function () {
  10818. return this._checkCollisions;
  10819. },
  10820. set: function (collisionEnabled) {
  10821. this._checkCollisions = collisionEnabled;
  10822. if (this.getScene().workerCollisions) {
  10823. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10824. }
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10830. var globalPosition = this.getAbsolutePosition();
  10831. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10832. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10833. this._collider.radius = this.ellipsoid;
  10834. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10835. };
  10836. // Submeshes octree
  10837. /**
  10838. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10839. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10840. */
  10841. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10842. if (maxCapacity === void 0) { maxCapacity = 64; }
  10843. if (maxDepth === void 0) { maxDepth = 2; }
  10844. if (!this._submeshesOctree) {
  10845. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10846. }
  10847. this.computeWorldMatrix(true);
  10848. // Update octree
  10849. var bbox = this.getBoundingInfo().boundingBox;
  10850. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10851. return this._submeshesOctree;
  10852. };
  10853. // Collisions
  10854. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10855. this._generatePointsArray();
  10856. // Transformation
  10857. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10858. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10859. subMesh._lastColliderWorldVertices = [];
  10860. subMesh._trianglePlanes = [];
  10861. var start = subMesh.verticesStart;
  10862. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10863. for (var i = start; i < end; i++) {
  10864. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10865. }
  10866. }
  10867. // Collide
  10868. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10869. if (collider.collisionFound) {
  10870. collider.collidedMesh = this;
  10871. }
  10872. };
  10873. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10874. var subMeshes;
  10875. var len;
  10876. // Octrees
  10877. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10878. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10879. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10880. len = intersections.length;
  10881. subMeshes = intersections.data;
  10882. }
  10883. else {
  10884. subMeshes = this.subMeshes;
  10885. len = subMeshes.length;
  10886. }
  10887. for (var index = 0; index < len; index++) {
  10888. var subMesh = subMeshes[index];
  10889. // Bounding test
  10890. if (len > 1 && !subMesh._checkCollision(collider))
  10891. continue;
  10892. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10893. }
  10894. };
  10895. AbstractMesh.prototype._checkCollision = function (collider) {
  10896. // Bounding box test
  10897. if (!this._boundingInfo._checkCollision(collider))
  10898. return;
  10899. // Transformation matrix
  10900. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10901. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10902. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10903. };
  10904. // Picking
  10905. AbstractMesh.prototype._generatePointsArray = function () {
  10906. return false;
  10907. };
  10908. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10909. var pickingInfo = new BABYLON.PickingInfo();
  10910. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10911. return pickingInfo;
  10912. }
  10913. if (!this._generatePointsArray()) {
  10914. return pickingInfo;
  10915. }
  10916. var intersectInfo = null;
  10917. // Octrees
  10918. var subMeshes;
  10919. var len;
  10920. if (this._submeshesOctree && this.useOctreeForPicking) {
  10921. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10922. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10923. len = intersections.length;
  10924. subMeshes = intersections.data;
  10925. }
  10926. else {
  10927. subMeshes = this.subMeshes;
  10928. len = subMeshes.length;
  10929. }
  10930. for (var index = 0; index < len; index++) {
  10931. var subMesh = subMeshes[index];
  10932. // Bounding test
  10933. if (len > 1 && !subMesh.canIntersects(ray))
  10934. continue;
  10935. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10936. if (currentIntersectInfo) {
  10937. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10938. intersectInfo = currentIntersectInfo;
  10939. intersectInfo.subMeshId = index;
  10940. if (fastCheck) {
  10941. break;
  10942. }
  10943. }
  10944. }
  10945. }
  10946. if (intersectInfo) {
  10947. // Get picked point
  10948. var world = this.getWorldMatrix();
  10949. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10950. var direction = ray.direction.clone();
  10951. direction = direction.scale(intersectInfo.distance);
  10952. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10953. var pickedPoint = worldOrigin.add(worldDirection);
  10954. // Return result
  10955. pickingInfo.hit = true;
  10956. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10957. pickingInfo.pickedPoint = pickedPoint;
  10958. pickingInfo.pickedMesh = this;
  10959. pickingInfo.bu = intersectInfo.bu;
  10960. pickingInfo.bv = intersectInfo.bv;
  10961. pickingInfo.faceId = intersectInfo.faceId;
  10962. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10963. return pickingInfo;
  10964. }
  10965. return pickingInfo;
  10966. };
  10967. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10968. return null;
  10969. };
  10970. AbstractMesh.prototype.releaseSubMeshes = function () {
  10971. if (this.subMeshes) {
  10972. while (this.subMeshes.length) {
  10973. this.subMeshes[0].dispose();
  10974. }
  10975. }
  10976. else {
  10977. this.subMeshes = new Array();
  10978. }
  10979. };
  10980. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10981. var _this = this;
  10982. var index;
  10983. // Action manager
  10984. if (this.actionManager) {
  10985. this.actionManager.dispose();
  10986. this.actionManager = null;
  10987. }
  10988. // Skeleton
  10989. this.skeleton = null;
  10990. // Animations
  10991. this.getScene().stopAnimation(this);
  10992. // Physics
  10993. if (this.physicsImpostor) {
  10994. this.physicsImpostor.dispose();
  10995. }
  10996. // Intersections in progress
  10997. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10998. var other = this._intersectionsInProgress[index];
  10999. var pos = other._intersectionsInProgress.indexOf(this);
  11000. other._intersectionsInProgress.splice(pos, 1);
  11001. }
  11002. this._intersectionsInProgress = [];
  11003. // Lights
  11004. var lights = this.getScene().lights;
  11005. lights.forEach(function (light) {
  11006. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11007. if (meshIndex !== -1) {
  11008. light.includedOnlyMeshes.splice(meshIndex, 1);
  11009. }
  11010. meshIndex = light.excludedMeshes.indexOf(_this);
  11011. if (meshIndex !== -1) {
  11012. light.excludedMeshes.splice(meshIndex, 1);
  11013. }
  11014. // Shadow generators
  11015. var generator = light.getShadowGenerator();
  11016. if (generator) {
  11017. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11018. if (meshIndex !== -1) {
  11019. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11020. }
  11021. }
  11022. });
  11023. // Edges
  11024. if (this._edgesRenderer) {
  11025. this._edgesRenderer.dispose();
  11026. this._edgesRenderer = null;
  11027. }
  11028. // SubMeshes
  11029. this.releaseSubMeshes();
  11030. // Engine
  11031. this.getScene().getEngine().unbindAllAttributes();
  11032. // Remove from scene
  11033. this.getScene().removeMesh(this);
  11034. if (!doNotRecurse) {
  11035. // Particles
  11036. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11037. if (this.getScene().particleSystems[index].emitter === this) {
  11038. this.getScene().particleSystems[index].dispose();
  11039. index--;
  11040. }
  11041. }
  11042. // Children
  11043. var objects = this.getDescendants(true);
  11044. for (index = 0; index < objects.length; index++) {
  11045. objects[index].dispose();
  11046. }
  11047. }
  11048. else {
  11049. var childMeshes = this.getChildMeshes(true);
  11050. for (index = 0; index < childMeshes.length; index++) {
  11051. var child = childMeshes[index];
  11052. child.parent = null;
  11053. child.computeWorldMatrix(true);
  11054. }
  11055. }
  11056. _super.prototype.dispose.call(this);
  11057. this.onAfterWorldMatrixUpdateObservable.clear();
  11058. this.onCollideObservable.clear();
  11059. this.onCollisionPositionChangeObservable.clear();
  11060. this._isDisposed = true;
  11061. // Callback
  11062. this.onDisposeObservable.notifyObservers(this);
  11063. this.onDisposeObservable.clear();
  11064. };
  11065. // Statics
  11066. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11067. AbstractMesh._BILLBOARDMODE_X = 1;
  11068. AbstractMesh._BILLBOARDMODE_Y = 2;
  11069. AbstractMesh._BILLBOARDMODE_Z = 4;
  11070. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11071. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11072. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11073. return AbstractMesh;
  11074. }(BABYLON.Node));
  11075. BABYLON.AbstractMesh = AbstractMesh;
  11076. })(BABYLON || (BABYLON = {}));
  11077. var BABYLON;
  11078. (function (BABYLON) {
  11079. var Light = (function (_super) {
  11080. __extends(Light, _super);
  11081. function Light(name, scene) {
  11082. _super.call(this, name, scene);
  11083. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11084. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11085. this.intensity = 1.0;
  11086. this.range = Number.MAX_VALUE;
  11087. this.includeOnlyWithLayerMask = 0;
  11088. this.includedOnlyMeshes = new Array();
  11089. this.excludedMeshes = new Array();
  11090. this.excludeWithLayerMask = 0;
  11091. this.lightmapMode = 0;
  11092. // PBR Properties.
  11093. this.radius = 0.00001;
  11094. this._excludedMeshesIds = new Array();
  11095. this._includedOnlyMeshesIds = new Array();
  11096. scene.addLight(this);
  11097. }
  11098. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11099. /**
  11100. * If every light affecting the material is in this lightmapMode,
  11101. * material.lightmapTexture adds or multiplies
  11102. * (depends on material.useLightmapAsShadowmap)
  11103. * after every other light calculations.
  11104. */
  11105. get: function () {
  11106. return Light._LIGHTMAP_DEFAULT;
  11107. },
  11108. enumerable: true,
  11109. configurable: true
  11110. });
  11111. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11112. /**
  11113. * material.lightmapTexture as only diffuse lighting from this light
  11114. * adds pnly specular lighting from this light
  11115. * adds dynamic shadows
  11116. */
  11117. get: function () {
  11118. return Light._LIGHTMAP_SPECULAR;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11124. /**
  11125. * material.lightmapTexture as only lighting
  11126. * no light calculation from this light
  11127. * only adds dynamic shadows from this light
  11128. */
  11129. get: function () {
  11130. return Light._LIGHTMAP_SHADOWSONLY;
  11131. },
  11132. enumerable: true,
  11133. configurable: true
  11134. });
  11135. /**
  11136. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11137. */
  11138. Light.prototype.toString = function (fullDetails) {
  11139. var ret = "Name: " + this.name;
  11140. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11141. if (this.animations) {
  11142. for (var i = 0; i < this.animations.length; i++) {
  11143. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11144. }
  11145. }
  11146. if (fullDetails) {
  11147. }
  11148. return ret;
  11149. };
  11150. Light.prototype.getShadowGenerator = function () {
  11151. return this._shadowGenerator;
  11152. };
  11153. Light.prototype.getAbsolutePosition = function () {
  11154. return BABYLON.Vector3.Zero();
  11155. };
  11156. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11157. };
  11158. Light.prototype._getWorldMatrix = function () {
  11159. return BABYLON.Matrix.Identity();
  11160. };
  11161. Light.prototype.canAffectMesh = function (mesh) {
  11162. if (!mesh) {
  11163. return true;
  11164. }
  11165. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11166. return false;
  11167. }
  11168. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11169. return false;
  11170. }
  11171. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11172. return false;
  11173. }
  11174. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11175. return false;
  11176. }
  11177. return true;
  11178. };
  11179. Light.prototype.getWorldMatrix = function () {
  11180. this._currentRenderId = this.getScene().getRenderId();
  11181. var worldMatrix = this._getWorldMatrix();
  11182. if (this.parent && this.parent.getWorldMatrix) {
  11183. if (!this._parentedWorldMatrix) {
  11184. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11185. }
  11186. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11187. this._markSyncedWithParent();
  11188. return this._parentedWorldMatrix;
  11189. }
  11190. return worldMatrix;
  11191. };
  11192. Light.prototype.dispose = function () {
  11193. if (this._shadowGenerator) {
  11194. this._shadowGenerator.dispose();
  11195. this._shadowGenerator = null;
  11196. }
  11197. // Animations
  11198. this.getScene().stopAnimation(this);
  11199. // Remove from scene
  11200. this.getScene().removeLight(this);
  11201. _super.prototype.dispose.call(this);
  11202. };
  11203. Light.prototype.getTypeID = function () {
  11204. return 0;
  11205. };
  11206. Light.prototype.clone = function (name) {
  11207. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11208. };
  11209. Light.prototype.serialize = function () {
  11210. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11211. // Type
  11212. serializationObject.type = this.getTypeID();
  11213. // Parent
  11214. if (this.parent) {
  11215. serializationObject.parentId = this.parent.id;
  11216. }
  11217. // Inclusion / exclusions
  11218. if (this.excludedMeshes.length > 0) {
  11219. serializationObject.excludedMeshesIds = [];
  11220. this.excludedMeshes.forEach(function (mesh) {
  11221. serializationObject.excludedMeshesIds.push(mesh.id);
  11222. });
  11223. }
  11224. if (this.includedOnlyMeshes.length > 0) {
  11225. serializationObject.includedOnlyMeshesIds = [];
  11226. this.includedOnlyMeshes.forEach(function (mesh) {
  11227. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11228. });
  11229. }
  11230. // Animations
  11231. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11232. serializationObject.ranges = this.serializeAnimationRanges();
  11233. return serializationObject;
  11234. };
  11235. Light.GetConstructorFromName = function (type, name, scene) {
  11236. switch (type) {
  11237. case 0:
  11238. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11239. case 1:
  11240. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11241. case 2:
  11242. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11243. case 3:
  11244. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11245. }
  11246. };
  11247. Light.Parse = function (parsedLight, scene) {
  11248. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11249. // Inclusion / exclusions
  11250. if (parsedLight.excludedMeshesIds) {
  11251. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11252. }
  11253. if (parsedLight.includedOnlyMeshesIds) {
  11254. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11255. }
  11256. // Parent
  11257. if (parsedLight.parentId) {
  11258. light._waitingParentId = parsedLight.parentId;
  11259. }
  11260. // Animations
  11261. if (parsedLight.animations) {
  11262. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11263. var parsedAnimation = parsedLight.animations[animationIndex];
  11264. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11265. }
  11266. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11267. }
  11268. if (parsedLight.autoAnimate) {
  11269. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11270. }
  11271. return light;
  11272. };
  11273. //lightmapMode Consts
  11274. Light._LIGHTMAP_DEFAULT = 0;
  11275. Light._LIGHTMAP_SPECULAR = 1;
  11276. Light._LIGHTMAP_SHADOWSONLY = 2;
  11277. __decorate([
  11278. BABYLON.serializeAsColor3()
  11279. ], Light.prototype, "diffuse", void 0);
  11280. __decorate([
  11281. BABYLON.serializeAsColor3()
  11282. ], Light.prototype, "specular", void 0);
  11283. __decorate([
  11284. BABYLON.serialize()
  11285. ], Light.prototype, "intensity", void 0);
  11286. __decorate([
  11287. BABYLON.serialize()
  11288. ], Light.prototype, "range", void 0);
  11289. __decorate([
  11290. BABYLON.serialize()
  11291. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11292. __decorate([
  11293. BABYLON.serialize()
  11294. ], Light.prototype, "excludeWithLayerMask", void 0);
  11295. __decorate([
  11296. BABYLON.serialize()
  11297. ], Light.prototype, "lightmapMode", void 0);
  11298. __decorate([
  11299. BABYLON.serialize()
  11300. ], Light.prototype, "radius", void 0);
  11301. return Light;
  11302. }(BABYLON.Node));
  11303. BABYLON.Light = Light;
  11304. })(BABYLON || (BABYLON = {}));
  11305. var BABYLON;
  11306. (function (BABYLON) {
  11307. var PointLight = (function (_super) {
  11308. __extends(PointLight, _super);
  11309. function PointLight(name, position, scene) {
  11310. _super.call(this, name, scene);
  11311. this.position = position;
  11312. }
  11313. PointLight.prototype.getAbsolutePosition = function () {
  11314. return this.transformedPosition ? this.transformedPosition : this.position;
  11315. };
  11316. PointLight.prototype.computeTransformedPosition = function () {
  11317. if (this.parent && this.parent.getWorldMatrix) {
  11318. if (!this.transformedPosition) {
  11319. this.transformedPosition = BABYLON.Vector3.Zero();
  11320. }
  11321. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11322. return true;
  11323. }
  11324. return false;
  11325. };
  11326. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11327. if (this.parent && this.parent.getWorldMatrix) {
  11328. this.computeTransformedPosition();
  11329. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11330. return;
  11331. }
  11332. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11333. };
  11334. PointLight.prototype.needCube = function () {
  11335. return true;
  11336. };
  11337. PointLight.prototype.supportsVSM = function () {
  11338. return false;
  11339. };
  11340. PointLight.prototype.needRefreshPerFrame = function () {
  11341. return false;
  11342. };
  11343. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11344. switch (faceIndex) {
  11345. case 0:
  11346. return new BABYLON.Vector3(1, 0, 0);
  11347. case 1:
  11348. return new BABYLON.Vector3(-1, 0, 0);
  11349. case 2:
  11350. return new BABYLON.Vector3(0, -1, 0);
  11351. case 3:
  11352. return new BABYLON.Vector3(0, 1, 0);
  11353. case 4:
  11354. return new BABYLON.Vector3(0, 0, 1);
  11355. case 5:
  11356. return new BABYLON.Vector3(0, 0, -1);
  11357. }
  11358. return BABYLON.Vector3.Zero();
  11359. };
  11360. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11361. var activeCamera = this.getScene().activeCamera;
  11362. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11363. };
  11364. PointLight.prototype._getWorldMatrix = function () {
  11365. if (!this._worldMatrix) {
  11366. this._worldMatrix = BABYLON.Matrix.Identity();
  11367. }
  11368. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11369. return this._worldMatrix;
  11370. };
  11371. PointLight.prototype.getTypeID = function () {
  11372. return 0;
  11373. };
  11374. __decorate([
  11375. BABYLON.serializeAsVector3()
  11376. ], PointLight.prototype, "position", void 0);
  11377. return PointLight;
  11378. }(BABYLON.Light));
  11379. BABYLON.PointLight = PointLight;
  11380. })(BABYLON || (BABYLON = {}));
  11381. var BABYLON;
  11382. (function (BABYLON) {
  11383. var SpotLight = (function (_super) {
  11384. __extends(SpotLight, _super);
  11385. function SpotLight(name, position, direction, angle, exponent, scene) {
  11386. _super.call(this, name, scene);
  11387. this.position = position;
  11388. this.direction = direction;
  11389. this.angle = angle;
  11390. this.exponent = exponent;
  11391. }
  11392. SpotLight.prototype.getAbsolutePosition = function () {
  11393. return this.transformedPosition ? this.transformedPosition : this.position;
  11394. };
  11395. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11396. var activeCamera = this.getScene().activeCamera;
  11397. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11398. };
  11399. SpotLight.prototype.needCube = function () {
  11400. return false;
  11401. };
  11402. SpotLight.prototype.supportsVSM = function () {
  11403. return true;
  11404. };
  11405. SpotLight.prototype.needRefreshPerFrame = function () {
  11406. return false;
  11407. };
  11408. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11409. return this.direction;
  11410. };
  11411. SpotLight.prototype.setDirectionToTarget = function (target) {
  11412. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11413. return this.direction;
  11414. };
  11415. SpotLight.prototype.computeTransformedPosition = function () {
  11416. if (this.parent && this.parent.getWorldMatrix) {
  11417. if (!this.transformedPosition) {
  11418. this.transformedPosition = BABYLON.Vector3.Zero();
  11419. }
  11420. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11421. return true;
  11422. }
  11423. return false;
  11424. };
  11425. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11426. var normalizeDirection;
  11427. if (this.parent && this.parent.getWorldMatrix) {
  11428. if (!this._transformedDirection) {
  11429. this._transformedDirection = BABYLON.Vector3.Zero();
  11430. }
  11431. this.computeTransformedPosition();
  11432. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11433. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11434. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11435. }
  11436. else {
  11437. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11438. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11439. }
  11440. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11441. };
  11442. SpotLight.prototype._getWorldMatrix = function () {
  11443. if (!this._worldMatrix) {
  11444. this._worldMatrix = BABYLON.Matrix.Identity();
  11445. }
  11446. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11447. return this._worldMatrix;
  11448. };
  11449. SpotLight.prototype.getTypeID = function () {
  11450. return 2;
  11451. };
  11452. __decorate([
  11453. BABYLON.serializeAsVector3()
  11454. ], SpotLight.prototype, "position", void 0);
  11455. __decorate([
  11456. BABYLON.serializeAsVector3()
  11457. ], SpotLight.prototype, "direction", void 0);
  11458. __decorate([
  11459. BABYLON.serialize()
  11460. ], SpotLight.prototype, "angle", void 0);
  11461. __decorate([
  11462. BABYLON.serialize()
  11463. ], SpotLight.prototype, "exponent", void 0);
  11464. return SpotLight;
  11465. }(BABYLON.Light));
  11466. BABYLON.SpotLight = SpotLight;
  11467. })(BABYLON || (BABYLON = {}));
  11468. var BABYLON;
  11469. (function (BABYLON) {
  11470. var HemisphericLight = (function (_super) {
  11471. __extends(HemisphericLight, _super);
  11472. function HemisphericLight(name, direction, scene) {
  11473. _super.call(this, name, scene);
  11474. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11475. this.direction = direction;
  11476. }
  11477. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11478. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11479. return this.direction;
  11480. };
  11481. HemisphericLight.prototype.getShadowGenerator = function () {
  11482. return null;
  11483. };
  11484. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11485. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11486. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11487. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11488. };
  11489. HemisphericLight.prototype._getWorldMatrix = function () {
  11490. if (!this._worldMatrix) {
  11491. this._worldMatrix = BABYLON.Matrix.Identity();
  11492. }
  11493. return this._worldMatrix;
  11494. };
  11495. HemisphericLight.prototype.getTypeID = function () {
  11496. return 3;
  11497. };
  11498. __decorate([
  11499. BABYLON.serializeAsColor3()
  11500. ], HemisphericLight.prototype, "groundColor", void 0);
  11501. __decorate([
  11502. BABYLON.serializeAsVector3()
  11503. ], HemisphericLight.prototype, "direction", void 0);
  11504. return HemisphericLight;
  11505. }(BABYLON.Light));
  11506. BABYLON.HemisphericLight = HemisphericLight;
  11507. })(BABYLON || (BABYLON = {}));
  11508. var BABYLON;
  11509. (function (BABYLON) {
  11510. var DirectionalLight = (function (_super) {
  11511. __extends(DirectionalLight, _super);
  11512. function DirectionalLight(name, direction, scene) {
  11513. _super.call(this, name, scene);
  11514. this.shadowOrthoScale = 0.5;
  11515. this.autoUpdateExtends = true;
  11516. // Cache
  11517. this._orthoLeft = Number.MAX_VALUE;
  11518. this._orthoRight = Number.MIN_VALUE;
  11519. this._orthoTop = Number.MIN_VALUE;
  11520. this._orthoBottom = Number.MAX_VALUE;
  11521. this.position = direction.scale(-1);
  11522. this.direction = direction;
  11523. }
  11524. DirectionalLight.prototype.getAbsolutePosition = function () {
  11525. return this.transformedPosition ? this.transformedPosition : this.position;
  11526. };
  11527. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11528. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11529. return this.direction;
  11530. };
  11531. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11532. var activeCamera = this.getScene().activeCamera;
  11533. // Check extends
  11534. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11535. var tempVector3 = BABYLON.Vector3.Zero();
  11536. this._orthoLeft = Number.MAX_VALUE;
  11537. this._orthoRight = Number.MIN_VALUE;
  11538. this._orthoTop = Number.MIN_VALUE;
  11539. this._orthoBottom = Number.MAX_VALUE;
  11540. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11541. var mesh = renderList[meshIndex];
  11542. if (!mesh) {
  11543. continue;
  11544. }
  11545. var boundingInfo = mesh.getBoundingInfo();
  11546. if (!boundingInfo) {
  11547. continue;
  11548. }
  11549. var boundingBox = boundingInfo.boundingBox;
  11550. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11551. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11552. if (tempVector3.x < this._orthoLeft)
  11553. this._orthoLeft = tempVector3.x;
  11554. if (tempVector3.y < this._orthoBottom)
  11555. this._orthoBottom = tempVector3.y;
  11556. if (tempVector3.x > this._orthoRight)
  11557. this._orthoRight = tempVector3.x;
  11558. if (tempVector3.y > this._orthoTop)
  11559. this._orthoTop = tempVector3.y;
  11560. }
  11561. }
  11562. }
  11563. var xOffset = this._orthoRight - this._orthoLeft;
  11564. var yOffset = this._orthoTop - this._orthoBottom;
  11565. 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);
  11566. };
  11567. DirectionalLight.prototype.supportsVSM = function () {
  11568. return true;
  11569. };
  11570. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11571. return true;
  11572. };
  11573. DirectionalLight.prototype.needCube = function () {
  11574. return false;
  11575. };
  11576. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11577. return this.direction;
  11578. };
  11579. DirectionalLight.prototype.computeTransformedPosition = function () {
  11580. if (this.parent && this.parent.getWorldMatrix) {
  11581. if (!this.transformedPosition) {
  11582. this.transformedPosition = BABYLON.Vector3.Zero();
  11583. }
  11584. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11585. return true;
  11586. }
  11587. return false;
  11588. };
  11589. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11590. if (this.parent && this.parent.getWorldMatrix) {
  11591. if (!this._transformedDirection) {
  11592. this._transformedDirection = BABYLON.Vector3.Zero();
  11593. }
  11594. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11595. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11596. return;
  11597. }
  11598. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11599. };
  11600. DirectionalLight.prototype._getWorldMatrix = function () {
  11601. if (!this._worldMatrix) {
  11602. this._worldMatrix = BABYLON.Matrix.Identity();
  11603. }
  11604. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11605. return this._worldMatrix;
  11606. };
  11607. DirectionalLight.prototype.getTypeID = function () {
  11608. return 1;
  11609. };
  11610. __decorate([
  11611. BABYLON.serializeAsVector3()
  11612. ], DirectionalLight.prototype, "position", void 0);
  11613. __decorate([
  11614. BABYLON.serializeAsVector3()
  11615. ], DirectionalLight.prototype, "direction", void 0);
  11616. __decorate([
  11617. BABYLON.serialize()
  11618. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11619. __decorate([
  11620. BABYLON.serialize()
  11621. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11622. return DirectionalLight;
  11623. }(BABYLON.Light));
  11624. BABYLON.DirectionalLight = DirectionalLight;
  11625. })(BABYLON || (BABYLON = {}));
  11626. var BABYLON;
  11627. (function (BABYLON) {
  11628. var ShadowGenerator = (function () {
  11629. function ShadowGenerator(mapSize, light) {
  11630. var _this = this;
  11631. // Members
  11632. this._filter = ShadowGenerator.FILTER_NONE;
  11633. this.blurScale = 2;
  11634. this._blurBoxOffset = 0;
  11635. this._bias = 0.00005;
  11636. this._lightDirection = BABYLON.Vector3.Zero();
  11637. this.forceBackFacesOnly = false;
  11638. this._darkness = 0;
  11639. this._transparencyShadow = false;
  11640. this._viewMatrix = BABYLON.Matrix.Zero();
  11641. this._projectionMatrix = BABYLON.Matrix.Zero();
  11642. this._transformMatrix = BABYLON.Matrix.Zero();
  11643. this._worldViewProjection = BABYLON.Matrix.Zero();
  11644. this._currentFaceIndex = 0;
  11645. this._currentFaceIndexCache = 0;
  11646. this._useFullFloat = true;
  11647. this._light = light;
  11648. this._scene = light.getScene();
  11649. this._mapSize = mapSize;
  11650. light._shadowGenerator = this;
  11651. // Texture type fallback from float to int if not supported.
  11652. var textureType;
  11653. var caps = this._scene.getEngine().getCaps();
  11654. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11655. this._useFullFloat = true;
  11656. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11657. }
  11658. else {
  11659. this._useFullFloat = false;
  11660. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11661. }
  11662. // Render target
  11663. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11664. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11665. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11666. this._shadowMap.anisotropicFilteringLevel = 1;
  11667. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11668. this._shadowMap.renderParticles = false;
  11669. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11670. _this._currentFaceIndex = faceIndex;
  11671. });
  11672. this._shadowMap.onAfterUnbindObservable.add(function () {
  11673. if (!_this.useBlurVarianceShadowMap) {
  11674. return;
  11675. }
  11676. if (!_this._shadowMap2) {
  11677. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11678. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11679. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11680. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11681. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11682. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11683. effect.setTexture("textureSampler", _this._shadowMap);
  11684. });
  11685. _this.blurBoxOffset = 1;
  11686. }
  11687. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11688. });
  11689. // Custom render function
  11690. var renderSubMesh = function (subMesh) {
  11691. var mesh = subMesh.getRenderingMesh();
  11692. var scene = _this._scene;
  11693. var engine = scene.getEngine();
  11694. // Culling
  11695. engine.setState(subMesh.getMaterial().backFaceCulling);
  11696. // Managing instances
  11697. var batch = mesh._getInstancesRenderList(subMesh._id);
  11698. if (batch.mustReturn) {
  11699. return;
  11700. }
  11701. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11702. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11703. engine.enableEffect(_this._effect);
  11704. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11705. var material = subMesh.getMaterial();
  11706. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11707. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11708. if (_this.getLight().needCube()) {
  11709. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11710. }
  11711. // Alpha test
  11712. if (material && material.needAlphaTesting()) {
  11713. var alphaTexture = material.getAlphaTestTexture();
  11714. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11715. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11716. }
  11717. // Bones
  11718. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11719. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11720. }
  11721. if (_this.forceBackFacesOnly) {
  11722. engine.setState(true, 0, false, true);
  11723. }
  11724. // Draw
  11725. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11726. if (_this.forceBackFacesOnly) {
  11727. engine.setState(true, 0, false, false);
  11728. }
  11729. }
  11730. else {
  11731. // Need to reset refresh rate of the shadowMap
  11732. _this._shadowMap.resetRefreshCounter();
  11733. }
  11734. };
  11735. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11736. var index;
  11737. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11738. renderSubMesh(opaqueSubMeshes.data[index]);
  11739. }
  11740. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11741. renderSubMesh(alphaTestSubMeshes.data[index]);
  11742. }
  11743. if (_this._transparencyShadow) {
  11744. for (index = 0; index < transparentSubMeshes.length; index++) {
  11745. renderSubMesh(transparentSubMeshes.data[index]);
  11746. }
  11747. }
  11748. };
  11749. this._shadowMap.onClearObservable.add(function (engine) {
  11750. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11751. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11752. }
  11753. else {
  11754. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11755. }
  11756. });
  11757. }
  11758. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11759. // Static
  11760. get: function () {
  11761. return ShadowGenerator._FILTER_NONE;
  11762. },
  11763. enumerable: true,
  11764. configurable: true
  11765. });
  11766. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11767. get: function () {
  11768. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11774. get: function () {
  11775. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11781. get: function () {
  11782. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11788. get: function () {
  11789. return this._bias;
  11790. },
  11791. set: function (bias) {
  11792. this._bias = bias;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11798. get: function () {
  11799. return this._blurBoxOffset;
  11800. },
  11801. set: function (value) {
  11802. var _this = this;
  11803. if (this._blurBoxOffset === value) {
  11804. return;
  11805. }
  11806. this._blurBoxOffset = value;
  11807. if (this._boxBlurPostprocess) {
  11808. this._boxBlurPostprocess.dispose();
  11809. }
  11810. 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);
  11811. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11812. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11813. });
  11814. },
  11815. enumerable: true,
  11816. configurable: true
  11817. });
  11818. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11819. get: function () {
  11820. return this._filter;
  11821. },
  11822. set: function (value) {
  11823. if (this._filter === value) {
  11824. return;
  11825. }
  11826. this._filter = value;
  11827. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11828. this._shadowMap.anisotropicFilteringLevel = 16;
  11829. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11830. }
  11831. else {
  11832. this._shadowMap.anisotropicFilteringLevel = 1;
  11833. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11834. }
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11840. get: function () {
  11841. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11842. },
  11843. set: function (value) {
  11844. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11845. },
  11846. enumerable: true,
  11847. configurable: true
  11848. });
  11849. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11850. get: function () {
  11851. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11852. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11853. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11854. },
  11855. set: function (value) {
  11856. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11862. get: function () {
  11863. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11864. },
  11865. set: function (value) {
  11866. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11867. },
  11868. enumerable: true,
  11869. configurable: true
  11870. });
  11871. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11872. var defines = [];
  11873. if (this._useFullFloat) {
  11874. defines.push("#define FULLFLOAT");
  11875. }
  11876. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11877. defines.push("#define VSM");
  11878. }
  11879. if (this.getLight().needCube()) {
  11880. defines.push("#define CUBEMAP");
  11881. }
  11882. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11883. var mesh = subMesh.getMesh();
  11884. var material = subMesh.getMaterial();
  11885. // Alpha test
  11886. if (material && material.needAlphaTesting()) {
  11887. defines.push("#define ALPHATEST");
  11888. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11889. attribs.push(BABYLON.VertexBuffer.UVKind);
  11890. defines.push("#define UV1");
  11891. }
  11892. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11893. var alphaTexture = material.getAlphaTestTexture();
  11894. if (alphaTexture.coordinatesIndex === 1) {
  11895. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11896. defines.push("#define UV2");
  11897. }
  11898. }
  11899. }
  11900. // Bones
  11901. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11902. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11903. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11904. if (mesh.numBoneInfluencers > 4) {
  11905. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11906. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11907. }
  11908. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11909. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11910. }
  11911. else {
  11912. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11913. }
  11914. // Instances
  11915. if (useInstances) {
  11916. defines.push("#define INSTANCES");
  11917. attribs.push("world0");
  11918. attribs.push("world1");
  11919. attribs.push("world2");
  11920. attribs.push("world3");
  11921. }
  11922. // Get correct effect
  11923. var join = defines.join("\n");
  11924. if (this._cachedDefines !== join) {
  11925. this._cachedDefines = join;
  11926. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11927. }
  11928. return this._effect.isReady();
  11929. };
  11930. ShadowGenerator.prototype.getShadowMap = function () {
  11931. return this._shadowMap;
  11932. };
  11933. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11934. if (this._shadowMap2) {
  11935. return this._shadowMap2;
  11936. }
  11937. return this._shadowMap;
  11938. };
  11939. ShadowGenerator.prototype.getLight = function () {
  11940. return this._light;
  11941. };
  11942. // Methods
  11943. ShadowGenerator.prototype.getTransformMatrix = function () {
  11944. var scene = this._scene;
  11945. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11946. return this._transformMatrix;
  11947. }
  11948. this._currentRenderID = scene.getRenderId();
  11949. this._currentFaceIndexCache = this._currentFaceIndex;
  11950. var lightPosition = this._light.position;
  11951. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11952. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11953. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11954. }
  11955. if (this._light.computeTransformedPosition()) {
  11956. lightPosition = this._light.transformedPosition;
  11957. }
  11958. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11959. this._cachedPosition = lightPosition.clone();
  11960. this._cachedDirection = this._lightDirection.clone();
  11961. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11962. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11963. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11964. }
  11965. return this._transformMatrix;
  11966. };
  11967. ShadowGenerator.prototype.getDarkness = function () {
  11968. return this._darkness;
  11969. };
  11970. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11971. if (darkness >= 1.0)
  11972. this._darkness = 1.0;
  11973. else if (darkness <= 0.0)
  11974. this._darkness = 0.0;
  11975. else
  11976. this._darkness = darkness;
  11977. };
  11978. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11979. this._transparencyShadow = hasShadow;
  11980. };
  11981. ShadowGenerator.prototype._packHalf = function (depth) {
  11982. var scale = depth * 255.0;
  11983. var fract = scale - Math.floor(scale);
  11984. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11985. };
  11986. ShadowGenerator.prototype.dispose = function () {
  11987. this._shadowMap.dispose();
  11988. if (this._shadowMap2) {
  11989. this._shadowMap2.dispose();
  11990. }
  11991. if (this._downSamplePostprocess) {
  11992. this._downSamplePostprocess.dispose();
  11993. }
  11994. if (this._boxBlurPostprocess) {
  11995. this._boxBlurPostprocess.dispose();
  11996. }
  11997. };
  11998. ShadowGenerator.prototype.serialize = function () {
  11999. var serializationObject = {};
  12000. serializationObject.lightId = this._light.id;
  12001. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12002. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12003. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12004. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12005. serializationObject.renderList = [];
  12006. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12007. var mesh = this.getShadowMap().renderList[meshIndex];
  12008. serializationObject.renderList.push(mesh.id);
  12009. }
  12010. return serializationObject;
  12011. };
  12012. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12013. //casting to point light, as light is missing the position attr and typescript complains.
  12014. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12015. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12016. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12017. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12018. meshes.forEach(function (mesh) {
  12019. shadowGenerator.getShadowMap().renderList.push(mesh);
  12020. });
  12021. }
  12022. if (parsedShadowGenerator.usePoissonSampling) {
  12023. shadowGenerator.usePoissonSampling = true;
  12024. }
  12025. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12026. shadowGenerator.useVarianceShadowMap = true;
  12027. }
  12028. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12029. shadowGenerator.useBlurVarianceShadowMap = true;
  12030. if (parsedShadowGenerator.blurScale) {
  12031. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12032. }
  12033. if (parsedShadowGenerator.blurBoxOffset) {
  12034. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12035. }
  12036. }
  12037. if (parsedShadowGenerator.bias !== undefined) {
  12038. shadowGenerator.bias = parsedShadowGenerator.bias;
  12039. }
  12040. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12041. return shadowGenerator;
  12042. };
  12043. ShadowGenerator._FILTER_NONE = 0;
  12044. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12045. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12046. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12047. return ShadowGenerator;
  12048. }());
  12049. BABYLON.ShadowGenerator = ShadowGenerator;
  12050. })(BABYLON || (BABYLON = {}));
  12051. var BABYLON;
  12052. (function (BABYLON) {
  12053. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12054. if (boxMin.x > sphereCenter.x + sphereRadius)
  12055. return false;
  12056. if (sphereCenter.x - sphereRadius > boxMax.x)
  12057. return false;
  12058. if (boxMin.y > sphereCenter.y + sphereRadius)
  12059. return false;
  12060. if (sphereCenter.y - sphereRadius > boxMax.y)
  12061. return false;
  12062. if (boxMin.z > sphereCenter.z + sphereRadius)
  12063. return false;
  12064. if (sphereCenter.z - sphereRadius > boxMax.z)
  12065. return false;
  12066. return true;
  12067. };
  12068. var getLowestRoot = (function () {
  12069. var result = { root: 0, found: false };
  12070. return function (a, b, c, maxR) {
  12071. result.root = 0;
  12072. result.found = false;
  12073. var determinant = b * b - 4.0 * a * c;
  12074. if (determinant < 0)
  12075. return result;
  12076. var sqrtD = Math.sqrt(determinant);
  12077. var r1 = (-b - sqrtD) / (2.0 * a);
  12078. var r2 = (-b + sqrtD) / (2.0 * a);
  12079. if (r1 > r2) {
  12080. var temp = r2;
  12081. r2 = r1;
  12082. r1 = temp;
  12083. }
  12084. if (r1 > 0 && r1 < maxR) {
  12085. result.root = r1;
  12086. result.found = true;
  12087. return result;
  12088. }
  12089. if (r2 > 0 && r2 < maxR) {
  12090. result.root = r2;
  12091. result.found = true;
  12092. return result;
  12093. }
  12094. return result;
  12095. };
  12096. })();
  12097. var Collider = (function () {
  12098. function Collider() {
  12099. this.radius = new BABYLON.Vector3(1, 1, 1);
  12100. this.retry = 0;
  12101. this.basePointWorld = BABYLON.Vector3.Zero();
  12102. this.velocityWorld = BABYLON.Vector3.Zero();
  12103. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12104. this._collisionPoint = BABYLON.Vector3.Zero();
  12105. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12106. this._tempVector = BABYLON.Vector3.Zero();
  12107. this._tempVector2 = BABYLON.Vector3.Zero();
  12108. this._tempVector3 = BABYLON.Vector3.Zero();
  12109. this._tempVector4 = BABYLON.Vector3.Zero();
  12110. this._edge = BABYLON.Vector3.Zero();
  12111. this._baseToVertex = BABYLON.Vector3.Zero();
  12112. this._destinationPoint = BABYLON.Vector3.Zero();
  12113. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12114. this._displacementVector = BABYLON.Vector3.Zero();
  12115. }
  12116. // Methods
  12117. Collider.prototype._initialize = function (source, dir, e) {
  12118. this.velocity = dir;
  12119. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12120. this.basePoint = source;
  12121. source.multiplyToRef(this.radius, this.basePointWorld);
  12122. dir.multiplyToRef(this.radius, this.velocityWorld);
  12123. this.velocityWorldLength = this.velocityWorld.length();
  12124. this.epsilon = e;
  12125. this.collisionFound = false;
  12126. };
  12127. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12128. pa.subtractToRef(point, this._tempVector);
  12129. pb.subtractToRef(point, this._tempVector2);
  12130. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12131. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12132. if (d < 0)
  12133. return false;
  12134. pc.subtractToRef(point, this._tempVector3);
  12135. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12136. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12137. if (d < 0)
  12138. return false;
  12139. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12140. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12141. return d >= 0;
  12142. };
  12143. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12144. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12145. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12146. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12147. return false;
  12148. }
  12149. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12150. return false;
  12151. return true;
  12152. };
  12153. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12154. var t0;
  12155. var embeddedInPlane = false;
  12156. //defensive programming, actually not needed.
  12157. if (!trianglePlaneArray) {
  12158. trianglePlaneArray = [];
  12159. }
  12160. if (!trianglePlaneArray[faceIndex]) {
  12161. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12162. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12163. }
  12164. var trianglePlane = trianglePlaneArray[faceIndex];
  12165. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12166. return;
  12167. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12168. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12169. if (normalDotVelocity == 0) {
  12170. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12171. return;
  12172. embeddedInPlane = true;
  12173. t0 = 0;
  12174. }
  12175. else {
  12176. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12177. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12178. if (t0 > t1) {
  12179. var temp = t1;
  12180. t1 = t0;
  12181. t0 = temp;
  12182. }
  12183. if (t0 > 1.0 || t1 < 0.0)
  12184. return;
  12185. if (t0 < 0)
  12186. t0 = 0;
  12187. if (t0 > 1.0)
  12188. t0 = 1.0;
  12189. }
  12190. this._collisionPoint.copyFromFloats(0, 0, 0);
  12191. var found = false;
  12192. var t = 1.0;
  12193. if (!embeddedInPlane) {
  12194. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12195. this.velocity.scaleToRef(t0, this._tempVector);
  12196. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12197. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12198. found = true;
  12199. t = t0;
  12200. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12201. }
  12202. }
  12203. if (!found) {
  12204. var velocitySquaredLength = this.velocity.lengthSquared();
  12205. var a = velocitySquaredLength;
  12206. this.basePoint.subtractToRef(p1, this._tempVector);
  12207. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12208. var c = this._tempVector.lengthSquared() - 1.0;
  12209. var lowestRoot = getLowestRoot(a, b, c, t);
  12210. if (lowestRoot.found) {
  12211. t = lowestRoot.root;
  12212. found = true;
  12213. this._collisionPoint.copyFrom(p1);
  12214. }
  12215. this.basePoint.subtractToRef(p2, this._tempVector);
  12216. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12217. c = this._tempVector.lengthSquared() - 1.0;
  12218. lowestRoot = getLowestRoot(a, b, c, t);
  12219. if (lowestRoot.found) {
  12220. t = lowestRoot.root;
  12221. found = true;
  12222. this._collisionPoint.copyFrom(p2);
  12223. }
  12224. this.basePoint.subtractToRef(p3, this._tempVector);
  12225. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12226. c = this._tempVector.lengthSquared() - 1.0;
  12227. lowestRoot = getLowestRoot(a, b, c, t);
  12228. if (lowestRoot.found) {
  12229. t = lowestRoot.root;
  12230. found = true;
  12231. this._collisionPoint.copyFrom(p3);
  12232. }
  12233. p2.subtractToRef(p1, this._edge);
  12234. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12235. var edgeSquaredLength = this._edge.lengthSquared();
  12236. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12237. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12238. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12239. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12240. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12241. lowestRoot = getLowestRoot(a, b, c, t);
  12242. if (lowestRoot.found) {
  12243. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12244. if (f >= 0.0 && f <= 1.0) {
  12245. t = lowestRoot.root;
  12246. found = true;
  12247. this._edge.scaleInPlace(f);
  12248. p1.addToRef(this._edge, this._collisionPoint);
  12249. }
  12250. }
  12251. p3.subtractToRef(p2, this._edge);
  12252. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12253. edgeSquaredLength = this._edge.lengthSquared();
  12254. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12255. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12256. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12257. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12258. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12259. lowestRoot = getLowestRoot(a, b, c, t);
  12260. if (lowestRoot.found) {
  12261. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12262. if (f >= 0.0 && f <= 1.0) {
  12263. t = lowestRoot.root;
  12264. found = true;
  12265. this._edge.scaleInPlace(f);
  12266. p2.addToRef(this._edge, this._collisionPoint);
  12267. }
  12268. }
  12269. p1.subtractToRef(p3, this._edge);
  12270. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12271. edgeSquaredLength = this._edge.lengthSquared();
  12272. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12273. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12274. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12275. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12276. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12277. lowestRoot = getLowestRoot(a, b, c, t);
  12278. if (lowestRoot.found) {
  12279. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12280. if (f >= 0.0 && f <= 1.0) {
  12281. t = lowestRoot.root;
  12282. found = true;
  12283. this._edge.scaleInPlace(f);
  12284. p3.addToRef(this._edge, this._collisionPoint);
  12285. }
  12286. }
  12287. }
  12288. if (found) {
  12289. var distToCollision = t * this.velocity.length();
  12290. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12291. if (!this.intersectionPoint) {
  12292. this.intersectionPoint = this._collisionPoint.clone();
  12293. }
  12294. else {
  12295. this.intersectionPoint.copyFrom(this._collisionPoint);
  12296. }
  12297. this.nearestDistance = distToCollision;
  12298. this.collisionFound = true;
  12299. }
  12300. }
  12301. };
  12302. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12303. for (var i = indexStart; i < indexEnd; i += 3) {
  12304. var p1 = pts[indices[i] - decal];
  12305. var p2 = pts[indices[i + 1] - decal];
  12306. var p3 = pts[indices[i + 2] - decal];
  12307. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12308. }
  12309. };
  12310. Collider.prototype._getResponse = function (pos, vel) {
  12311. pos.addToRef(vel, this._destinationPoint);
  12312. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12313. this.basePoint.addToRef(vel, pos);
  12314. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12315. this._slidePlaneNormal.normalize();
  12316. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12317. pos.addInPlace(this._displacementVector);
  12318. this.intersectionPoint.addInPlace(this._displacementVector);
  12319. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12320. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12321. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12322. };
  12323. return Collider;
  12324. }());
  12325. BABYLON.Collider = Collider;
  12326. })(BABYLON || (BABYLON = {}));
  12327. var BABYLON;
  12328. (function (BABYLON) {
  12329. //WebWorker code will be inserted to this variable.
  12330. BABYLON.CollisionWorker = "";
  12331. (function (WorkerTaskType) {
  12332. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12333. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12334. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12335. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12336. var WorkerTaskType = BABYLON.WorkerTaskType;
  12337. (function (WorkerReplyType) {
  12338. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12339. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12340. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12341. var WorkerReplyType = BABYLON.WorkerReplyType;
  12342. var CollisionCoordinatorWorker = (function () {
  12343. function CollisionCoordinatorWorker() {
  12344. var _this = this;
  12345. this._scaledPosition = BABYLON.Vector3.Zero();
  12346. this._scaledVelocity = BABYLON.Vector3.Zero();
  12347. this.onMeshUpdated = function (mesh) {
  12348. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12349. };
  12350. this.onGeometryUpdated = function (geometry) {
  12351. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12352. };
  12353. this._afterRender = function () {
  12354. if (!_this._init)
  12355. return;
  12356. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12357. return;
  12358. }
  12359. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12360. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12361. if (_this._runningUpdated > 4) {
  12362. return;
  12363. }
  12364. ++_this._runningUpdated;
  12365. var payload = {
  12366. updatedMeshes: _this._addUpdateMeshesList,
  12367. updatedGeometries: _this._addUpdateGeometriesList,
  12368. removedGeometries: _this._toRemoveGeometryArray,
  12369. removedMeshes: _this._toRemoveMeshesArray
  12370. };
  12371. var message = {
  12372. payload: payload,
  12373. taskType: WorkerTaskType.UPDATE
  12374. };
  12375. var serializable = [];
  12376. for (var id in payload.updatedGeometries) {
  12377. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12378. //prepare transferables
  12379. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12380. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12381. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12382. }
  12383. }
  12384. _this._worker.postMessage(message, serializable);
  12385. _this._addUpdateMeshesList = {};
  12386. _this._addUpdateGeometriesList = {};
  12387. _this._toRemoveGeometryArray = [];
  12388. _this._toRemoveMeshesArray = [];
  12389. };
  12390. this._onMessageFromWorker = function (e) {
  12391. var returnData = e.data;
  12392. if (returnData.error != WorkerReplyType.SUCCESS) {
  12393. //TODO what errors can be returned from the worker?
  12394. BABYLON.Tools.Warn("error returned from worker!");
  12395. return;
  12396. }
  12397. switch (returnData.taskType) {
  12398. case WorkerTaskType.INIT:
  12399. _this._init = true;
  12400. //Update the worked with ALL of the scene's current state
  12401. _this._scene.meshes.forEach(function (mesh) {
  12402. _this.onMeshAdded(mesh);
  12403. });
  12404. _this._scene.getGeometries().forEach(function (geometry) {
  12405. _this.onGeometryAdded(geometry);
  12406. });
  12407. break;
  12408. case WorkerTaskType.UPDATE:
  12409. _this._runningUpdated--;
  12410. break;
  12411. case WorkerTaskType.COLLIDE:
  12412. _this._runningCollisionTask = false;
  12413. var returnPayload = returnData.payload;
  12414. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12415. return;
  12416. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12417. //cleanup
  12418. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12419. break;
  12420. }
  12421. };
  12422. this._collisionsCallbackArray = [];
  12423. this._init = false;
  12424. this._runningUpdated = 0;
  12425. this._runningCollisionTask = false;
  12426. this._addUpdateMeshesList = {};
  12427. this._addUpdateGeometriesList = {};
  12428. this._toRemoveGeometryArray = [];
  12429. this._toRemoveMeshesArray = [];
  12430. }
  12431. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12432. if (!this._init)
  12433. return;
  12434. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12435. return;
  12436. position.divideToRef(collider.radius, this._scaledPosition);
  12437. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12438. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12439. var payload = {
  12440. collider: {
  12441. position: this._scaledPosition.asArray(),
  12442. velocity: this._scaledVelocity.asArray(),
  12443. radius: collider.radius.asArray()
  12444. },
  12445. collisionId: collisionIndex,
  12446. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12447. maximumRetry: maximumRetry
  12448. };
  12449. var message = {
  12450. payload: payload,
  12451. taskType: WorkerTaskType.COLLIDE
  12452. };
  12453. this._worker.postMessage(message);
  12454. };
  12455. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12456. this._scene = scene;
  12457. this._scene.registerAfterRender(this._afterRender);
  12458. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12459. this._worker = new Worker(workerUrl);
  12460. this._worker.onmessage = this._onMessageFromWorker;
  12461. var message = {
  12462. payload: {},
  12463. taskType: WorkerTaskType.INIT
  12464. };
  12465. this._worker.postMessage(message);
  12466. };
  12467. CollisionCoordinatorWorker.prototype.destroy = function () {
  12468. this._scene.unregisterAfterRender(this._afterRender);
  12469. this._worker.terminate();
  12470. };
  12471. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12472. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12473. this.onMeshUpdated(mesh);
  12474. };
  12475. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12476. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12477. };
  12478. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12479. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12480. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12481. this.onGeometryUpdated(geometry);
  12482. };
  12483. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12484. this._toRemoveGeometryArray.push(geometry.id);
  12485. };
  12486. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12487. var submeshes = [];
  12488. if (mesh.subMeshes) {
  12489. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12490. return {
  12491. position: idx,
  12492. verticesStart: sm.verticesStart,
  12493. verticesCount: sm.verticesCount,
  12494. indexStart: sm.indexStart,
  12495. indexCount: sm.indexCount,
  12496. hasMaterial: !!sm.getMaterial(),
  12497. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12498. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12499. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12500. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12501. };
  12502. });
  12503. }
  12504. var geometryId = null;
  12505. if (mesh instanceof BABYLON.Mesh) {
  12506. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12507. }
  12508. else if (mesh instanceof BABYLON.InstancedMesh) {
  12509. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12510. }
  12511. return {
  12512. uniqueId: mesh.uniqueId,
  12513. id: mesh.id,
  12514. name: mesh.name,
  12515. geometryId: geometryId,
  12516. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12517. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12518. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12519. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12520. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12521. subMeshes: submeshes,
  12522. checkCollisions: mesh.checkCollisions
  12523. };
  12524. };
  12525. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12526. return {
  12527. id: geometry.id,
  12528. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12529. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12530. indices: new Int32Array(geometry.getIndices() || []),
  12531. };
  12532. };
  12533. return CollisionCoordinatorWorker;
  12534. }());
  12535. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12536. var CollisionCoordinatorLegacy = (function () {
  12537. function CollisionCoordinatorLegacy() {
  12538. this._scaledPosition = BABYLON.Vector3.Zero();
  12539. this._scaledVelocity = BABYLON.Vector3.Zero();
  12540. this._finalPosition = BABYLON.Vector3.Zero();
  12541. }
  12542. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12543. position.divideToRef(collider.radius, this._scaledPosition);
  12544. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12545. collider.collidedMesh = null;
  12546. collider.retry = 0;
  12547. collider.initialVelocity = this._scaledVelocity;
  12548. collider.initialPosition = this._scaledPosition;
  12549. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12550. this._finalPosition.multiplyInPlace(collider.radius);
  12551. //run the callback
  12552. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12553. };
  12554. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12555. this._scene = scene;
  12556. };
  12557. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12558. //Legacy need no destruction method.
  12559. };
  12560. //No update in legacy mode
  12561. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12562. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12563. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12564. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12565. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12566. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12567. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12568. if (excludedMesh === void 0) { excludedMesh = null; }
  12569. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12570. if (collider.retry >= maximumRetry) {
  12571. finalPosition.copyFrom(position);
  12572. return;
  12573. }
  12574. collider._initialize(position, velocity, closeDistance);
  12575. // Check all meshes
  12576. for (var index = 0; index < this._scene.meshes.length; index++) {
  12577. var mesh = this._scene.meshes[index];
  12578. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12579. mesh._checkCollision(collider);
  12580. }
  12581. }
  12582. if (!collider.collisionFound) {
  12583. position.addToRef(velocity, finalPosition);
  12584. return;
  12585. }
  12586. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12587. collider._getResponse(position, velocity);
  12588. }
  12589. if (velocity.length() <= closeDistance) {
  12590. finalPosition.copyFrom(position);
  12591. return;
  12592. }
  12593. collider.retry++;
  12594. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12595. };
  12596. return CollisionCoordinatorLegacy;
  12597. }());
  12598. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12599. })(BABYLON || (BABYLON = {}));
  12600. var BABYLON;
  12601. (function (BABYLON) {
  12602. var Camera = (function (_super) {
  12603. __extends(Camera, _super);
  12604. function Camera(name, position, scene) {
  12605. _super.call(this, name, scene);
  12606. this.upVector = BABYLON.Vector3.Up();
  12607. this.orthoLeft = null;
  12608. this.orthoRight = null;
  12609. this.orthoBottom = null;
  12610. this.orthoTop = null;
  12611. this.fov = 0.8;
  12612. this.minZ = 1.0;
  12613. this.maxZ = 10000.0;
  12614. this.inertia = 0.9;
  12615. this.mode = Camera.PERSPECTIVE_CAMERA;
  12616. this.isIntermediate = false;
  12617. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12618. this.layerMask = 0x0FFFFFFF;
  12619. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12620. // Camera rig members
  12621. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12622. this._rigCameras = new Array();
  12623. // Cache
  12624. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12625. this._projectionMatrix = new BABYLON.Matrix();
  12626. this._postProcesses = new Array();
  12627. this._transformMatrix = BABYLON.Matrix.Zero();
  12628. this._activeMeshes = new BABYLON.SmartArray(256);
  12629. this._globalPosition = BABYLON.Vector3.Zero();
  12630. this._refreshFrustumPlanes = true;
  12631. scene.addCamera(this);
  12632. if (!scene.activeCamera) {
  12633. scene.activeCamera = this;
  12634. }
  12635. this.position = position;
  12636. }
  12637. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12638. get: function () {
  12639. return Camera._PERSPECTIVE_CAMERA;
  12640. },
  12641. enumerable: true,
  12642. configurable: true
  12643. });
  12644. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12645. get: function () {
  12646. return Camera._ORTHOGRAPHIC_CAMERA;
  12647. },
  12648. enumerable: true,
  12649. configurable: true
  12650. });
  12651. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12652. get: function () {
  12653. return Camera._FOVMODE_VERTICAL_FIXED;
  12654. },
  12655. enumerable: true,
  12656. configurable: true
  12657. });
  12658. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12659. get: function () {
  12660. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12661. },
  12662. enumerable: true,
  12663. configurable: true
  12664. });
  12665. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12666. get: function () {
  12667. return Camera._RIG_MODE_NONE;
  12668. },
  12669. enumerable: true,
  12670. configurable: true
  12671. });
  12672. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12673. get: function () {
  12674. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12675. },
  12676. enumerable: true,
  12677. configurable: true
  12678. });
  12679. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12680. get: function () {
  12681. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12682. },
  12683. enumerable: true,
  12684. configurable: true
  12685. });
  12686. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12687. get: function () {
  12688. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12689. },
  12690. enumerable: true,
  12691. configurable: true
  12692. });
  12693. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12694. get: function () {
  12695. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12696. },
  12697. enumerable: true,
  12698. configurable: true
  12699. });
  12700. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12701. get: function () {
  12702. return Camera._RIG_MODE_VR;
  12703. },
  12704. enumerable: true,
  12705. configurable: true
  12706. });
  12707. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12708. get: function () {
  12709. return Camera._RIG_MODE_WEBVR;
  12710. },
  12711. enumerable: true,
  12712. configurable: true
  12713. });
  12714. /**
  12715. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12716. */
  12717. Camera.prototype.toString = function (fullDetails) {
  12718. var ret = "Name: " + this.name;
  12719. ret += ", type: " + this.getTypeName();
  12720. if (this.animations) {
  12721. for (var i = 0; i < this.animations.length; i++) {
  12722. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12723. }
  12724. }
  12725. if (fullDetails) {
  12726. }
  12727. return ret;
  12728. };
  12729. Object.defineProperty(Camera.prototype, "globalPosition", {
  12730. get: function () {
  12731. return this._globalPosition;
  12732. },
  12733. enumerable: true,
  12734. configurable: true
  12735. });
  12736. Camera.prototype.getActiveMeshes = function () {
  12737. return this._activeMeshes;
  12738. };
  12739. Camera.prototype.isActiveMesh = function (mesh) {
  12740. return (this._activeMeshes.indexOf(mesh) !== -1);
  12741. };
  12742. //Cache
  12743. Camera.prototype._initCache = function () {
  12744. _super.prototype._initCache.call(this);
  12745. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12746. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12747. this._cache.mode = undefined;
  12748. this._cache.minZ = undefined;
  12749. this._cache.maxZ = undefined;
  12750. this._cache.fov = undefined;
  12751. this._cache.fovMode = undefined;
  12752. this._cache.aspectRatio = undefined;
  12753. this._cache.orthoLeft = undefined;
  12754. this._cache.orthoRight = undefined;
  12755. this._cache.orthoBottom = undefined;
  12756. this._cache.orthoTop = undefined;
  12757. this._cache.renderWidth = undefined;
  12758. this._cache.renderHeight = undefined;
  12759. };
  12760. Camera.prototype._updateCache = function (ignoreParentClass) {
  12761. if (!ignoreParentClass) {
  12762. _super.prototype._updateCache.call(this);
  12763. }
  12764. var engine = this.getEngine();
  12765. this._cache.position.copyFrom(this.position);
  12766. this._cache.upVector.copyFrom(this.upVector);
  12767. this._cache.mode = this.mode;
  12768. this._cache.minZ = this.minZ;
  12769. this._cache.maxZ = this.maxZ;
  12770. this._cache.fov = this.fov;
  12771. this._cache.fovMode = this.fovMode;
  12772. this._cache.aspectRatio = engine.getAspectRatio(this);
  12773. this._cache.orthoLeft = this.orthoLeft;
  12774. this._cache.orthoRight = this.orthoRight;
  12775. this._cache.orthoBottom = this.orthoBottom;
  12776. this._cache.orthoTop = this.orthoTop;
  12777. this._cache.renderWidth = engine.getRenderWidth();
  12778. this._cache.renderHeight = engine.getRenderHeight();
  12779. };
  12780. Camera.prototype._updateFromScene = function () {
  12781. this.updateCache();
  12782. this.update();
  12783. };
  12784. // Synchronized
  12785. Camera.prototype._isSynchronized = function () {
  12786. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12787. };
  12788. Camera.prototype._isSynchronizedViewMatrix = function () {
  12789. if (!_super.prototype._isSynchronized.call(this))
  12790. return false;
  12791. return this._cache.position.equals(this.position)
  12792. && this._cache.upVector.equals(this.upVector)
  12793. && this.isSynchronizedWithParent();
  12794. };
  12795. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12796. var check = this._cache.mode === this.mode
  12797. && this._cache.minZ === this.minZ
  12798. && this._cache.maxZ === this.maxZ;
  12799. if (!check) {
  12800. return false;
  12801. }
  12802. var engine = this.getEngine();
  12803. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12804. check = this._cache.fov === this.fov
  12805. && this._cache.fovMode === this.fovMode
  12806. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12807. }
  12808. else {
  12809. check = this._cache.orthoLeft === this.orthoLeft
  12810. && this._cache.orthoRight === this.orthoRight
  12811. && this._cache.orthoBottom === this.orthoBottom
  12812. && this._cache.orthoTop === this.orthoTop
  12813. && this._cache.renderWidth === engine.getRenderWidth()
  12814. && this._cache.renderHeight === engine.getRenderHeight();
  12815. }
  12816. return check;
  12817. };
  12818. // Controls
  12819. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12820. };
  12821. Camera.prototype.detachControl = function (element) {
  12822. };
  12823. Camera.prototype.update = function () {
  12824. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12825. this._updateRigCameras();
  12826. }
  12827. this._checkInputs();
  12828. };
  12829. Camera.prototype._checkInputs = function () {
  12830. };
  12831. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12832. // invalidate framebuffer
  12833. if (this._postProcesses.length > 0) {
  12834. this._postProcesses[0].markTextureDirty();
  12835. }
  12836. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12837. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12838. var cam = this._rigCameras[i];
  12839. var rigPostProcess = cam._rigPostProcess;
  12840. // for VR rig, there does not have to be a post process
  12841. if (rigPostProcess) {
  12842. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12843. if (isPass) {
  12844. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12845. cam.isIntermediate = this._postProcesses.length === 0;
  12846. }
  12847. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12848. rigPostProcess.markTextureDirty();
  12849. }
  12850. else {
  12851. cam._postProcesses = this._postProcesses.slice(0);
  12852. }
  12853. }
  12854. };
  12855. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12856. if (insertAt === void 0) { insertAt = null; }
  12857. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12858. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12859. return 0;
  12860. }
  12861. if (insertAt == null || insertAt < 0) {
  12862. this._postProcesses.push(postProcess);
  12863. }
  12864. else {
  12865. this._postProcesses.splice(insertAt, 0, postProcess);
  12866. }
  12867. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12868. return this._postProcesses.indexOf(postProcess);
  12869. };
  12870. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12871. if (atIndices === void 0) { atIndices = null; }
  12872. var result = [];
  12873. var i;
  12874. var index;
  12875. if (!atIndices) {
  12876. var idx = this._postProcesses.indexOf(postProcess);
  12877. if (idx !== -1) {
  12878. this._postProcesses.splice(idx, 1);
  12879. }
  12880. }
  12881. else {
  12882. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12883. // iterate descending, so can just splice as we go
  12884. for (i = atIndices.length - 1; i >= 0; i--) {
  12885. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12886. result.push(i);
  12887. continue;
  12888. }
  12889. this._postProcesses.splice(index, 1);
  12890. }
  12891. }
  12892. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12893. return result;
  12894. };
  12895. Camera.prototype.getWorldMatrix = function () {
  12896. if (!this._worldMatrix) {
  12897. this._worldMatrix = BABYLON.Matrix.Identity();
  12898. }
  12899. var viewMatrix = this.getViewMatrix();
  12900. viewMatrix.invertToRef(this._worldMatrix);
  12901. return this._worldMatrix;
  12902. };
  12903. Camera.prototype._getViewMatrix = function () {
  12904. return BABYLON.Matrix.Identity();
  12905. };
  12906. Camera.prototype.getViewMatrix = function (force) {
  12907. this._computedViewMatrix = this._computeViewMatrix(force);
  12908. if (!force && this._isSynchronizedViewMatrix()) {
  12909. return this._computedViewMatrix;
  12910. }
  12911. this._refreshFrustumPlanes = true;
  12912. if (!this.parent || !this.parent.getWorldMatrix) {
  12913. this._globalPosition.copyFrom(this.position);
  12914. }
  12915. else {
  12916. if (!this._worldMatrix) {
  12917. this._worldMatrix = BABYLON.Matrix.Identity();
  12918. }
  12919. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12920. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12921. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12922. this._computedViewMatrix.invert();
  12923. this._markSyncedWithParent();
  12924. }
  12925. this._currentRenderId = this.getScene().getRenderId();
  12926. return this._computedViewMatrix;
  12927. };
  12928. Camera.prototype._computeViewMatrix = function (force) {
  12929. if (!force && this._isSynchronizedViewMatrix()) {
  12930. return this._computedViewMatrix;
  12931. }
  12932. this._computedViewMatrix = this._getViewMatrix();
  12933. this._currentRenderId = this.getScene().getRenderId();
  12934. return this._computedViewMatrix;
  12935. };
  12936. Camera.prototype.getProjectionMatrix = function (force) {
  12937. if (!force && this._isSynchronizedProjectionMatrix()) {
  12938. return this._projectionMatrix;
  12939. }
  12940. this._refreshFrustumPlanes = true;
  12941. var engine = this.getEngine();
  12942. var scene = this.getScene();
  12943. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12944. if (this.minZ <= 0) {
  12945. this.minZ = 0.1;
  12946. }
  12947. if (scene.useRightHandedSystem) {
  12948. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12949. }
  12950. else {
  12951. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12952. }
  12953. return this._projectionMatrix;
  12954. }
  12955. var halfWidth = engine.getRenderWidth() / 2.0;
  12956. var halfHeight = engine.getRenderHeight() / 2.0;
  12957. if (scene.useRightHandedSystem) {
  12958. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12959. }
  12960. else {
  12961. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12962. }
  12963. return this._projectionMatrix;
  12964. };
  12965. Camera.prototype.getTranformationMatrix = function () {
  12966. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12967. return this._transformMatrix;
  12968. };
  12969. Camera.prototype.updateFrustumPlanes = function () {
  12970. if (!this._refreshFrustumPlanes) {
  12971. return;
  12972. }
  12973. this.getTranformationMatrix();
  12974. if (!this._frustumPlanes) {
  12975. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12976. }
  12977. else {
  12978. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12979. }
  12980. this._refreshFrustumPlanes = false;
  12981. };
  12982. Camera.prototype.isInFrustum = function (target) {
  12983. this.updateFrustumPlanes();
  12984. return target.isInFrustum(this._frustumPlanes);
  12985. };
  12986. Camera.prototype.isCompletelyInFrustum = function (target) {
  12987. this.updateFrustumPlanes();
  12988. return target.isCompletelyInFrustum(this._frustumPlanes);
  12989. };
  12990. Camera.prototype.dispose = function () {
  12991. // Animations
  12992. this.getScene().stopAnimation(this);
  12993. // Remove from scene
  12994. this.getScene().removeCamera(this);
  12995. while (this._rigCameras.length > 0) {
  12996. this._rigCameras.pop().dispose();
  12997. }
  12998. // Postprocesses
  12999. for (var i = 0; i < this._postProcesses.length; ++i) {
  13000. this._postProcesses[i].dispose(this);
  13001. }
  13002. _super.prototype.dispose.call(this);
  13003. };
  13004. // ---- Camera rigs section ----
  13005. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13006. while (this._rigCameras.length > 0) {
  13007. this._rigCameras.pop().dispose();
  13008. }
  13009. this.cameraRigMode = mode;
  13010. this._cameraRigParams = {};
  13011. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13012. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13013. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13014. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13015. // create the rig cameras, unless none
  13016. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13017. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13018. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13019. }
  13020. switch (this.cameraRigMode) {
  13021. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13022. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13023. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13024. break;
  13025. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13026. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13027. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13028. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13029. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13030. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13031. break;
  13032. case Camera.RIG_MODE_VR:
  13033. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13034. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13035. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13036. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13037. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13038. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13039. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13040. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13041. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13042. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13043. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13044. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13045. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13046. if (metrics.compensateDistortion) {
  13047. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13048. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13049. }
  13050. break;
  13051. case Camera.RIG_MODE_WEBVR:
  13052. if (rigParams.vrDisplay) {
  13053. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13054. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13055. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13056. this._rigCameras[0].setCameraRigParameter("vrFieldOfView", leftEye.fieldOfView);
  13057. this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13058. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13059. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13060. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13061. this._rigCameras[1].setCameraRigParameter("vrFieldOfView", rightEye.fieldOfView);
  13062. this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13063. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13064. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13065. }
  13066. break;
  13067. }
  13068. this._cascadePostProcessesToRigCams();
  13069. this.
  13070. update();
  13071. };
  13072. Camera.prototype._getVRProjectionMatrix = function () {
  13073. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13074. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13075. return this._projectionMatrix;
  13076. };
  13077. Camera.prototype._getWebVRProjectionMatrix = function () {
  13078. BABYLON.Matrix.PerspectiveFovWebVRToRef(this._cameraRigParams['vrFieldOfView'], this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13079. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams['vrOffsetMatrix'], this._projectionMatrix);
  13080. return this._projectionMatrix;
  13081. };
  13082. Camera.prototype.setCameraRigParameter = function (name, value) {
  13083. if (!this._cameraRigParams) {
  13084. this._cameraRigParams = {};
  13085. }
  13086. this._cameraRigParams[name] = value;
  13087. //provisionnally:
  13088. if (name === "interaxialDistance") {
  13089. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13090. }
  13091. };
  13092. /**
  13093. * needs to be overridden by children so sub has required properties to be copied
  13094. */
  13095. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13096. return null;
  13097. };
  13098. /**
  13099. * May need to be overridden by children
  13100. */
  13101. Camera.prototype._updateRigCameras = function () {
  13102. for (var i = 0; i < this._rigCameras.length; i++) {
  13103. this._rigCameras[i].minZ = this.minZ;
  13104. this._rigCameras[i].maxZ = this.maxZ;
  13105. this._rigCameras[i].fov = this.fov;
  13106. }
  13107. // only update viewport when ANAGLYPH
  13108. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13109. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13110. }
  13111. };
  13112. Camera.prototype._setupInputs = function () {
  13113. };
  13114. Camera.prototype.serialize = function () {
  13115. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13116. // Type
  13117. serializationObject.type = this.getTypeName();
  13118. // Parent
  13119. if (this.parent) {
  13120. serializationObject.parentId = this.parent.id;
  13121. }
  13122. if (this.inputs) {
  13123. this.inputs.serialize(serializationObject);
  13124. }
  13125. // Animations
  13126. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13127. serializationObject.ranges = this.serializeAnimationRanges();
  13128. return serializationObject;
  13129. };
  13130. Camera.prototype.getTypeName = function () {
  13131. return "Camera";
  13132. };
  13133. Camera.prototype.clone = function (name) {
  13134. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13135. };
  13136. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13137. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13138. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13139. switch (type) {
  13140. case "ArcRotateCamera":
  13141. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13142. case "DeviceOrientationCamera":
  13143. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13144. case "FollowCamera":
  13145. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13146. case "ArcFollowCamera":
  13147. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13148. case "GamepadCamera":
  13149. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13150. case "TouchCamera":
  13151. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13152. case "VirtualJoysticksCamera":
  13153. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13154. case "WebVRFreeCamera":
  13155. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13156. case "VRDeviceOrientationFreeCamera":
  13157. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13158. case "AnaglyphArcRotateCamera":
  13159. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13160. case "AnaglyphFreeCamera":
  13161. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13162. case "AnaglyphGamepadCamera":
  13163. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13164. case "AnaglyphUniversalCamera":
  13165. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13166. case "StereoscopicArcRotateCamera":
  13167. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13168. case "StereoscopicFreeCamera":
  13169. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13170. case "StereoscopicGamepadCamera":
  13171. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13172. case "StereoscopicUniversalCamera":
  13173. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13174. case "FreeCamera":
  13175. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13176. default:
  13177. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13178. }
  13179. };
  13180. Camera.Parse = function (parsedCamera, scene) {
  13181. var type = parsedCamera.type;
  13182. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13183. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13184. // Parent
  13185. if (parsedCamera.parentId) {
  13186. camera._waitingParentId = parsedCamera.parentId;
  13187. }
  13188. //If camera has an input manager, let it parse inputs settings
  13189. if (camera.inputs) {
  13190. camera.inputs.parse(parsedCamera);
  13191. camera._setupInputs();
  13192. }
  13193. // Target
  13194. if (parsedCamera.target) {
  13195. if (camera.setTarget) {
  13196. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13197. }
  13198. }
  13199. // Apply 3d rig, when found
  13200. if (parsedCamera.cameraRigMode) {
  13201. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13202. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13203. }
  13204. // Animations
  13205. if (parsedCamera.animations) {
  13206. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13207. var parsedAnimation = parsedCamera.animations[animationIndex];
  13208. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13209. }
  13210. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13211. }
  13212. if (parsedCamera.autoAnimate) {
  13213. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13214. }
  13215. return camera;
  13216. };
  13217. // Statics
  13218. Camera._PERSPECTIVE_CAMERA = 0;
  13219. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13220. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13221. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13222. Camera._RIG_MODE_NONE = 0;
  13223. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13224. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13225. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13226. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13227. Camera._RIG_MODE_VR = 20;
  13228. Camera._RIG_MODE_WEBVR = 21;
  13229. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13230. __decorate([
  13231. BABYLON.serializeAsVector3()
  13232. ], Camera.prototype, "position", void 0);
  13233. __decorate([
  13234. BABYLON.serializeAsVector3()
  13235. ], Camera.prototype, "upVector", void 0);
  13236. __decorate([
  13237. BABYLON.serialize()
  13238. ], Camera.prototype, "orthoLeft", void 0);
  13239. __decorate([
  13240. BABYLON.serialize()
  13241. ], Camera.prototype, "orthoRight", void 0);
  13242. __decorate([
  13243. BABYLON.serialize()
  13244. ], Camera.prototype, "orthoBottom", void 0);
  13245. __decorate([
  13246. BABYLON.serialize()
  13247. ], Camera.prototype, "orthoTop", void 0);
  13248. __decorate([
  13249. BABYLON.serialize()
  13250. ], Camera.prototype, "fov", void 0);
  13251. __decorate([
  13252. BABYLON.serialize()
  13253. ], Camera.prototype, "minZ", void 0);
  13254. __decorate([
  13255. BABYLON.serialize()
  13256. ], Camera.prototype, "maxZ", void 0);
  13257. __decorate([
  13258. BABYLON.serialize()
  13259. ], Camera.prototype, "inertia", void 0);
  13260. __decorate([
  13261. BABYLON.serialize()
  13262. ], Camera.prototype, "mode", void 0);
  13263. __decorate([
  13264. BABYLON.serialize()
  13265. ], Camera.prototype, "layerMask", void 0);
  13266. __decorate([
  13267. BABYLON.serialize()
  13268. ], Camera.prototype, "fovMode", void 0);
  13269. __decorate([
  13270. BABYLON.serialize()
  13271. ], Camera.prototype, "cameraRigMode", void 0);
  13272. __decorate([
  13273. BABYLON.serialize()
  13274. ], Camera.prototype, "interaxialDistance", void 0);
  13275. __decorate([
  13276. BABYLON.serialize()
  13277. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13278. return Camera;
  13279. }(BABYLON.Node));
  13280. BABYLON.Camera = Camera;
  13281. })(BABYLON || (BABYLON = {}));
  13282. var BABYLON;
  13283. (function (BABYLON) {
  13284. BABYLON.CameraInputTypes = {};
  13285. var CameraInputsManager = (function () {
  13286. function CameraInputsManager(camera) {
  13287. this.attached = {};
  13288. this.camera = camera;
  13289. this.checkInputs = function () { };
  13290. }
  13291. CameraInputsManager.prototype.add = function (input) {
  13292. var type = input.getSimpleName();
  13293. if (this.attached[type]) {
  13294. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13295. return;
  13296. }
  13297. this.attached[type] = input;
  13298. input.camera = this.camera;
  13299. //for checkInputs, we are dynamically creating a function
  13300. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13301. if (input.checkInputs) {
  13302. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13303. }
  13304. if (this.attachedElement) {
  13305. input.attachControl(this.attachedElement);
  13306. }
  13307. };
  13308. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13309. for (var cam in this.attached) {
  13310. var input = this.attached[cam];
  13311. if (input === inputToRemove) {
  13312. input.detachControl(this.attachedElement);
  13313. delete this.attached[cam];
  13314. this.rebuildInputCheck();
  13315. }
  13316. }
  13317. };
  13318. CameraInputsManager.prototype.removeByType = function (inputType) {
  13319. for (var cam in this.attached) {
  13320. var input = this.attached[cam];
  13321. if (input.getTypeName() === inputType) {
  13322. input.detachControl(this.attachedElement);
  13323. delete this.attached[cam];
  13324. this.rebuildInputCheck();
  13325. }
  13326. }
  13327. };
  13328. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13329. var current = this.checkInputs;
  13330. return function () {
  13331. current();
  13332. fn();
  13333. };
  13334. };
  13335. CameraInputsManager.prototype.attachInput = function (input) {
  13336. input.attachControl(this.attachedElement, this.noPreventDefault);
  13337. };
  13338. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13339. if (this.attachedElement) {
  13340. return;
  13341. }
  13342. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13343. this.attachedElement = element;
  13344. this.noPreventDefault = noPreventDefault;
  13345. for (var cam in this.attached) {
  13346. var input = this.attached[cam];
  13347. this.attached[cam].attachControl(element, noPreventDefault);
  13348. }
  13349. };
  13350. CameraInputsManager.prototype.detachElement = function (element) {
  13351. if (this.attachedElement !== element) {
  13352. return;
  13353. }
  13354. for (var cam in this.attached) {
  13355. var input = this.attached[cam];
  13356. this.attached[cam].detachControl(element);
  13357. }
  13358. this.attachedElement = null;
  13359. };
  13360. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13361. this.checkInputs = function () { };
  13362. for (var cam in this.attached) {
  13363. var input = this.attached[cam];
  13364. if (input.checkInputs) {
  13365. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13366. }
  13367. }
  13368. };
  13369. CameraInputsManager.prototype.clear = function () {
  13370. if (this.attachedElement) {
  13371. this.detachElement(this.attachedElement);
  13372. }
  13373. this.attached = {};
  13374. this.attachedElement = null;
  13375. this.checkInputs = function () { };
  13376. };
  13377. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13378. var inputs = {};
  13379. for (var cam in this.attached) {
  13380. var input = this.attached[cam];
  13381. var res = BABYLON.SerializationHelper.Serialize(input);
  13382. inputs[input.getTypeName()] = res;
  13383. }
  13384. serializedCamera.inputsmgr = inputs;
  13385. };
  13386. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13387. var parsedInputs = parsedCamera.inputsmgr;
  13388. if (parsedInputs) {
  13389. this.clear();
  13390. for (var n in parsedInputs) {
  13391. var construct = BABYLON.CameraInputTypes[n];
  13392. if (construct) {
  13393. var parsedinput = parsedInputs[n];
  13394. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13395. this.add(input);
  13396. }
  13397. }
  13398. }
  13399. else {
  13400. //2016-03-08 this part is for managing backward compatibility
  13401. for (var n in this.attached) {
  13402. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13403. if (construct) {
  13404. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13405. this.remove(this.attached[n]);
  13406. this.add(input);
  13407. }
  13408. }
  13409. }
  13410. };
  13411. return CameraInputsManager;
  13412. }());
  13413. BABYLON.CameraInputsManager = CameraInputsManager;
  13414. })(BABYLON || (BABYLON = {}));
  13415. var BABYLON;
  13416. (function (BABYLON) {
  13417. var FreeCameraMouseInput = (function () {
  13418. function FreeCameraMouseInput(touchEnabled) {
  13419. if (touchEnabled === void 0) { touchEnabled = true; }
  13420. this.touchEnabled = touchEnabled;
  13421. this.angularSensibility = 2000.0;
  13422. }
  13423. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13424. var _this = this;
  13425. var engine = this.camera.getEngine();
  13426. if (!this._pointerInput) {
  13427. this._pointerInput = function (p, s) {
  13428. var evt = p.event;
  13429. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13430. return;
  13431. }
  13432. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13433. try {
  13434. evt.srcElement.setPointerCapture(evt.pointerId);
  13435. }
  13436. catch (e) {
  13437. }
  13438. _this.previousPosition = {
  13439. x: evt.clientX,
  13440. y: evt.clientY
  13441. };
  13442. if (!noPreventDefault) {
  13443. evt.preventDefault();
  13444. element.focus();
  13445. }
  13446. }
  13447. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13448. try {
  13449. evt.srcElement.releasePointerCapture(evt.pointerId);
  13450. }
  13451. catch (e) {
  13452. }
  13453. _this.previousPosition = null;
  13454. if (!noPreventDefault) {
  13455. evt.preventDefault();
  13456. }
  13457. }
  13458. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13459. if (!_this.previousPosition || engine.isPointerLock) {
  13460. return;
  13461. }
  13462. var offsetX = evt.clientX - _this.previousPosition.x;
  13463. var offsetY = evt.clientY - _this.previousPosition.y;
  13464. if (_this.camera.getScene().useRightHandedSystem) {
  13465. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13466. }
  13467. else {
  13468. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13469. }
  13470. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13471. _this.previousPosition = {
  13472. x: evt.clientX,
  13473. y: evt.clientY
  13474. };
  13475. if (!noPreventDefault) {
  13476. evt.preventDefault();
  13477. }
  13478. }
  13479. };
  13480. }
  13481. this._onMouseMove = function (evt) {
  13482. if (!engine.isPointerLock) {
  13483. return;
  13484. }
  13485. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13486. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13487. if (_this.camera.getScene().useRightHandedSystem) {
  13488. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13489. }
  13490. else {
  13491. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13492. }
  13493. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13494. _this.previousPosition = null;
  13495. if (!noPreventDefault) {
  13496. evt.preventDefault();
  13497. }
  13498. };
  13499. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13500. element.addEventListener("mousemove", this._onMouseMove, false);
  13501. };
  13502. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13503. if (this._observer && element) {
  13504. this.camera.getScene().onPointerObservable.remove(this._observer);
  13505. element.removeEventListener("mousemove", this._onMouseMove);
  13506. this._observer = null;
  13507. this._onMouseMove = null;
  13508. this.previousPosition = null;
  13509. }
  13510. };
  13511. FreeCameraMouseInput.prototype.getTypeName = function () {
  13512. return "FreeCameraMouseInput";
  13513. };
  13514. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13515. return "mouse";
  13516. };
  13517. __decorate([
  13518. BABYLON.serialize()
  13519. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13520. return FreeCameraMouseInput;
  13521. }());
  13522. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13523. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13524. })(BABYLON || (BABYLON = {}));
  13525. var BABYLON;
  13526. (function (BABYLON) {
  13527. var FreeCameraKeyboardMoveInput = (function () {
  13528. function FreeCameraKeyboardMoveInput() {
  13529. this._keys = [];
  13530. this.keysUp = [38];
  13531. this.keysDown = [40];
  13532. this.keysLeft = [37];
  13533. this.keysRight = [39];
  13534. }
  13535. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13536. var _this = this;
  13537. if (!this._onKeyDown) {
  13538. element.tabIndex = 1;
  13539. this._onKeyDown = function (evt) {
  13540. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13541. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13542. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13543. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13544. var index = _this._keys.indexOf(evt.keyCode);
  13545. if (index === -1) {
  13546. _this._keys.push(evt.keyCode);
  13547. }
  13548. if (!noPreventDefault) {
  13549. evt.preventDefault();
  13550. }
  13551. }
  13552. };
  13553. this._onKeyUp = function (evt) {
  13554. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13555. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13556. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13557. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13558. var index = _this._keys.indexOf(evt.keyCode);
  13559. if (index >= 0) {
  13560. _this._keys.splice(index, 1);
  13561. }
  13562. if (!noPreventDefault) {
  13563. evt.preventDefault();
  13564. }
  13565. }
  13566. };
  13567. element.addEventListener("keydown", this._onKeyDown, false);
  13568. element.addEventListener("keyup", this._onKeyUp, false);
  13569. BABYLON.Tools.RegisterTopRootEvents([
  13570. { name: "blur", handler: this._onLostFocus }
  13571. ]);
  13572. }
  13573. };
  13574. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13575. if (this._onKeyDown) {
  13576. element.removeEventListener("keydown", this._onKeyDown);
  13577. element.removeEventListener("keyup", this._onKeyUp);
  13578. BABYLON.Tools.UnregisterTopRootEvents([
  13579. { name: "blur", handler: this._onLostFocus }
  13580. ]);
  13581. this._keys = [];
  13582. this._onKeyDown = null;
  13583. this._onKeyUp = null;
  13584. }
  13585. };
  13586. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13587. if (this._onKeyDown) {
  13588. var camera = this.camera;
  13589. // Keyboard
  13590. for (var index = 0; index < this._keys.length; index++) {
  13591. var keyCode = this._keys[index];
  13592. var speed = camera._computeLocalCameraSpeed();
  13593. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13594. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13595. }
  13596. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13597. camera._localDirection.copyFromFloats(0, 0, speed);
  13598. }
  13599. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13600. camera._localDirection.copyFromFloats(speed, 0, 0);
  13601. }
  13602. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13603. camera._localDirection.copyFromFloats(0, 0, -speed);
  13604. }
  13605. if (camera.getScene().useRightHandedSystem) {
  13606. camera._localDirection.z *= -1;
  13607. }
  13608. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13609. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13610. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13611. }
  13612. }
  13613. };
  13614. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13615. return "FreeCameraKeyboardMoveInput";
  13616. };
  13617. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13618. this._keys = [];
  13619. };
  13620. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13621. return "keyboard";
  13622. };
  13623. __decorate([
  13624. BABYLON.serialize()
  13625. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13626. __decorate([
  13627. BABYLON.serialize()
  13628. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13629. __decorate([
  13630. BABYLON.serialize()
  13631. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13632. __decorate([
  13633. BABYLON.serialize()
  13634. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13635. return FreeCameraKeyboardMoveInput;
  13636. }());
  13637. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13638. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13639. })(BABYLON || (BABYLON = {}));
  13640. var BABYLON;
  13641. (function (BABYLON) {
  13642. var FreeCameraTouchInput = (function () {
  13643. function FreeCameraTouchInput() {
  13644. this._offsetX = null;
  13645. this._offsetY = null;
  13646. this._pointerCount = 0;
  13647. this._pointerPressed = [];
  13648. this.touchAngularSensibility = 200000.0;
  13649. this.touchMoveSensibility = 250.0;
  13650. }
  13651. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13652. var _this = this;
  13653. var previousPosition;
  13654. if (this._pointerInput === undefined) {
  13655. this._onLostFocus = function (evt) {
  13656. _this._offsetX = null;
  13657. _this._offsetY = null;
  13658. };
  13659. this._pointerInput = function (p, s) {
  13660. var evt = p.event;
  13661. if (evt.pointerType === "mouse") {
  13662. return;
  13663. }
  13664. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13665. if (!noPreventDefault) {
  13666. evt.preventDefault();
  13667. }
  13668. _this._pointerPressed.push(evt.pointerId);
  13669. if (_this._pointerPressed.length !== 1) {
  13670. return;
  13671. }
  13672. previousPosition = {
  13673. x: evt.clientX,
  13674. y: evt.clientY
  13675. };
  13676. }
  13677. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13678. if (!noPreventDefault) {
  13679. evt.preventDefault();
  13680. }
  13681. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13682. if (index === -1) {
  13683. return;
  13684. }
  13685. _this._pointerPressed.splice(index, 1);
  13686. if (index != 0) {
  13687. return;
  13688. }
  13689. previousPosition = null;
  13690. _this._offsetX = null;
  13691. _this._offsetY = null;
  13692. }
  13693. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13694. if (!noPreventDefault) {
  13695. evt.preventDefault();
  13696. }
  13697. if (!previousPosition) {
  13698. return;
  13699. }
  13700. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13701. if (index != 0) {
  13702. return;
  13703. }
  13704. _this._offsetX = evt.clientX - previousPosition.x;
  13705. _this._offsetY = -(evt.clientY - previousPosition.y);
  13706. }
  13707. };
  13708. }
  13709. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13710. element.addEventListener("blur", this._onLostFocus);
  13711. };
  13712. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13713. if (this._pointerInput && element) {
  13714. this.camera.getScene().onPointerObservable.remove(this._observer);
  13715. this._observer = null;
  13716. element.removeEventListener("blur", this._onLostFocus);
  13717. this._onLostFocus = null;
  13718. this._pointerPressed = [];
  13719. this._offsetX = null;
  13720. this._offsetY = null;
  13721. this._pointerCount = 0;
  13722. }
  13723. };
  13724. FreeCameraTouchInput.prototype.checkInputs = function () {
  13725. if (this._offsetX) {
  13726. var camera = this.camera;
  13727. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13728. if (this._pointerPressed.length > 1) {
  13729. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13730. }
  13731. else {
  13732. var speed = camera._computeLocalCameraSpeed();
  13733. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13734. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13735. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13736. }
  13737. }
  13738. };
  13739. FreeCameraTouchInput.prototype.getTypeName = function () {
  13740. return "FreeCameraTouchInput";
  13741. };
  13742. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13743. return "touch";
  13744. };
  13745. __decorate([
  13746. BABYLON.serialize()
  13747. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13748. __decorate([
  13749. BABYLON.serialize()
  13750. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13751. return FreeCameraTouchInput;
  13752. }());
  13753. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13754. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13755. })(BABYLON || (BABYLON = {}));
  13756. var BABYLON;
  13757. (function (BABYLON) {
  13758. var FreeCameraDeviceOrientationInput = (function () {
  13759. function FreeCameraDeviceOrientationInput() {
  13760. var _this = this;
  13761. this._screenOrientationAngle = 0;
  13762. this._screenQuaternion = new BABYLON.Quaternion();
  13763. this._alpha = 0;
  13764. this._beta = 0;
  13765. this._gamma = 0;
  13766. this._orientationChanged = function () {
  13767. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13768. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13769. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13770. };
  13771. this._deviceOrientation = function (evt) {
  13772. _this._alpha = evt.alpha;
  13773. _this._beta = evt.beta;
  13774. _this._gamma = evt.gamma;
  13775. };
  13776. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13777. this._orientationChanged();
  13778. }
  13779. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13780. get: function () {
  13781. return this._camera;
  13782. },
  13783. set: function (camera) {
  13784. this._camera = camera;
  13785. if (!this._camera.rotationQuaternion)
  13786. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13787. },
  13788. enumerable: true,
  13789. configurable: true
  13790. });
  13791. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13792. window.addEventListener("orientationchange", this._orientationChanged);
  13793. window.addEventListener("deviceorientation", this._deviceOrientation);
  13794. //In certain cases, the attach control is called AFTER orientation was changed,
  13795. //So this is needed.
  13796. this._orientationChanged();
  13797. };
  13798. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13799. window.removeEventListener("orientationchange", this._orientationChanged);
  13800. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13801. };
  13802. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13803. //if no device orientation provided, don't update the rotation.
  13804. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  13805. if (!this._alpha)
  13806. return;
  13807. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13808. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13809. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13810. //Mirror on XY Plane
  13811. this._camera.rotationQuaternion.z *= -1;
  13812. this._camera.rotationQuaternion.w *= -1;
  13813. };
  13814. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13815. return "FreeCameraDeviceOrientationInput";
  13816. };
  13817. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13818. return "deviceOrientation";
  13819. };
  13820. return FreeCameraDeviceOrientationInput;
  13821. }());
  13822. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13823. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13824. })(BABYLON || (BABYLON = {}));
  13825. var BABYLON;
  13826. (function (BABYLON) {
  13827. var FreeCameraGamepadInput = (function () {
  13828. function FreeCameraGamepadInput() {
  13829. this.gamepadAngularSensibility = 200;
  13830. this.gamepadMoveSensibility = 40;
  13831. }
  13832. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13833. var _this = this;
  13834. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13835. };
  13836. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13837. if (this._gamepads) {
  13838. this._gamepads.dispose();
  13839. }
  13840. this.gamepad = null;
  13841. };
  13842. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13843. if (this.gamepad) {
  13844. var camera = this.camera;
  13845. var LSValues = this.gamepad.leftStick;
  13846. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13847. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13848. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13849. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13850. var RSValues = this.gamepad.rightStick;
  13851. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13852. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13853. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13854. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13855. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13856. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13857. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13858. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13859. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13860. }
  13861. };
  13862. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13863. // Only the first gamepad can control the camera
  13864. if (gamepad.index === 0) {
  13865. this.gamepad = gamepad;
  13866. }
  13867. };
  13868. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13869. return "FreeCameraGamepadInput";
  13870. };
  13871. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13872. return "gamepad";
  13873. };
  13874. __decorate([
  13875. BABYLON.serialize()
  13876. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13877. __decorate([
  13878. BABYLON.serialize()
  13879. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13880. return FreeCameraGamepadInput;
  13881. }());
  13882. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13883. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13884. })(BABYLON || (BABYLON = {}));
  13885. var BABYLON;
  13886. (function (BABYLON) {
  13887. var ArcRotateCameraKeyboardMoveInput = (function () {
  13888. function ArcRotateCameraKeyboardMoveInput() {
  13889. this._keys = [];
  13890. this.keysUp = [38];
  13891. this.keysDown = [40];
  13892. this.keysLeft = [37];
  13893. this.keysRight = [39];
  13894. }
  13895. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13896. var _this = this;
  13897. element.tabIndex = 1;
  13898. this._onKeyDown = function (evt) {
  13899. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13900. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13901. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13902. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13903. var index = _this._keys.indexOf(evt.keyCode);
  13904. if (index === -1) {
  13905. _this._keys.push(evt.keyCode);
  13906. }
  13907. if (evt.preventDefault) {
  13908. if (!noPreventDefault) {
  13909. evt.preventDefault();
  13910. }
  13911. }
  13912. }
  13913. };
  13914. this._onKeyUp = function (evt) {
  13915. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13916. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13917. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13918. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13919. var index = _this._keys.indexOf(evt.keyCode);
  13920. if (index >= 0) {
  13921. _this._keys.splice(index, 1);
  13922. }
  13923. if (evt.preventDefault) {
  13924. if (!noPreventDefault) {
  13925. evt.preventDefault();
  13926. }
  13927. }
  13928. }
  13929. };
  13930. this._onLostFocus = function () {
  13931. _this._keys = [];
  13932. };
  13933. element.addEventListener("keydown", this._onKeyDown, false);
  13934. element.addEventListener("keyup", this._onKeyUp, false);
  13935. BABYLON.Tools.RegisterTopRootEvents([
  13936. { name: "blur", handler: this._onLostFocus }
  13937. ]);
  13938. };
  13939. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13940. if (element) {
  13941. element.removeEventListener("keydown", this._onKeyDown);
  13942. element.removeEventListener("keyup", this._onKeyUp);
  13943. }
  13944. BABYLON.Tools.UnregisterTopRootEvents([
  13945. { name: "blur", handler: this._onLostFocus }
  13946. ]);
  13947. this._keys = [];
  13948. this._onKeyDown = null;
  13949. this._onKeyUp = null;
  13950. this._onLostFocus = null;
  13951. };
  13952. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13953. if (this._onKeyDown) {
  13954. var camera = this.camera;
  13955. for (var index = 0; index < this._keys.length; index++) {
  13956. var keyCode = this._keys[index];
  13957. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13958. camera.inertialAlphaOffset -= 0.01;
  13959. }
  13960. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13961. camera.inertialBetaOffset -= 0.01;
  13962. }
  13963. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13964. camera.inertialAlphaOffset += 0.01;
  13965. }
  13966. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13967. camera.inertialBetaOffset += 0.01;
  13968. }
  13969. }
  13970. }
  13971. };
  13972. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13973. return "ArcRotateCameraKeyboardMoveInput";
  13974. };
  13975. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13976. return "keyboard";
  13977. };
  13978. __decorate([
  13979. BABYLON.serialize()
  13980. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13981. __decorate([
  13982. BABYLON.serialize()
  13983. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13984. __decorate([
  13985. BABYLON.serialize()
  13986. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13987. __decorate([
  13988. BABYLON.serialize()
  13989. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13990. return ArcRotateCameraKeyboardMoveInput;
  13991. }());
  13992. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13993. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13994. })(BABYLON || (BABYLON = {}));
  13995. var BABYLON;
  13996. (function (BABYLON) {
  13997. var ArcRotateCameraMouseWheelInput = (function () {
  13998. function ArcRotateCameraMouseWheelInput() {
  13999. this.wheelPrecision = 3.0;
  14000. }
  14001. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14002. var _this = this;
  14003. this._wheel = function (p, s) {
  14004. //sanity check - this should be a PointerWheel event.
  14005. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14006. return;
  14007. var event = p.event;
  14008. var delta = 0;
  14009. if (event.wheelDelta) {
  14010. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14011. }
  14012. else if (event.detail) {
  14013. delta = -event.detail / _this.wheelPrecision;
  14014. }
  14015. if (delta)
  14016. _this.camera.inertialRadiusOffset += delta;
  14017. if (event.preventDefault) {
  14018. if (!noPreventDefault) {
  14019. event.preventDefault();
  14020. }
  14021. }
  14022. };
  14023. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14024. };
  14025. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14026. if (this._observer && element) {
  14027. this.camera.getScene().onPointerObservable.remove(this._observer);
  14028. this._observer = null;
  14029. this._wheel = null;
  14030. }
  14031. };
  14032. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14033. return "ArcRotateCameraMouseWheelInput";
  14034. };
  14035. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14036. return "mousewheel";
  14037. };
  14038. __decorate([
  14039. BABYLON.serialize()
  14040. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14041. return ArcRotateCameraMouseWheelInput;
  14042. }());
  14043. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14044. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14045. })(BABYLON || (BABYLON = {}));
  14046. var BABYLON;
  14047. (function (BABYLON) {
  14048. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14049. var ArcRotateCameraPointersInput = (function () {
  14050. function ArcRotateCameraPointersInput() {
  14051. this.angularSensibilityX = 1000.0;
  14052. this.angularSensibilityY = 1000.0;
  14053. this.pinchPrecision = 6.0;
  14054. this.panningSensibility = 50.0;
  14055. this._isPanClick = false;
  14056. this.pinchInwards = true;
  14057. }
  14058. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14059. var _this = this;
  14060. var engine = this.camera.getEngine();
  14061. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14062. var pointA, pointB;
  14063. var previousPinchDistance = 0;
  14064. this._pointerInput = function (p, s) {
  14065. var evt = p.event;
  14066. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14067. try {
  14068. evt.srcElement.setPointerCapture(evt.pointerId);
  14069. }
  14070. catch (e) {
  14071. }
  14072. // Manage panning with pan button click
  14073. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14074. // manage pointers
  14075. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14076. if (pointA === undefined) {
  14077. pointA = cacheSoloPointer;
  14078. }
  14079. else if (pointB === undefined) {
  14080. pointB = cacheSoloPointer;
  14081. }
  14082. if (!noPreventDefault) {
  14083. evt.preventDefault();
  14084. element.focus();
  14085. }
  14086. }
  14087. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14088. try {
  14089. evt.srcElement.releasePointerCapture(evt.pointerId);
  14090. }
  14091. catch (e) {
  14092. }
  14093. cacheSoloPointer = null;
  14094. previousPinchDistance = 0;
  14095. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14096. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14097. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14098. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14099. pointA = pointB = undefined;
  14100. if (!noPreventDefault) {
  14101. evt.preventDefault();
  14102. }
  14103. }
  14104. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14105. if (!noPreventDefault) {
  14106. evt.preventDefault();
  14107. }
  14108. // One button down
  14109. if (pointA && pointB === undefined) {
  14110. if (_this.panningSensibility !== 0 &&
  14111. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14112. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14113. _this.camera
  14114. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14115. _this.camera
  14116. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14117. }
  14118. else {
  14119. var offsetX = evt.clientX - cacheSoloPointer.x;
  14120. var offsetY = evt.clientY - cacheSoloPointer.y;
  14121. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14122. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14123. }
  14124. cacheSoloPointer.x = evt.clientX;
  14125. cacheSoloPointer.y = evt.clientY;
  14126. }
  14127. else if (pointA && pointB) {
  14128. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14129. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14130. ed.x = evt.clientX;
  14131. ed.y = evt.clientY;
  14132. var direction = _this.pinchInwards ? 1 : -1;
  14133. var distX = pointA.x - pointB.x;
  14134. var distY = pointA.y - pointB.y;
  14135. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14136. if (previousPinchDistance === 0) {
  14137. previousPinchDistance = pinchSquaredDistance;
  14138. return;
  14139. }
  14140. if (pinchSquaredDistance !== previousPinchDistance) {
  14141. _this.camera
  14142. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14143. (_this.pinchPrecision *
  14144. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14145. direction);
  14146. previousPinchDistance = pinchSquaredDistance;
  14147. }
  14148. }
  14149. }
  14150. };
  14151. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14152. this._onContextMenu = function (evt) {
  14153. evt.preventDefault();
  14154. };
  14155. if (!this.camera._useCtrlForPanning) {
  14156. element.addEventListener("contextmenu", this._onContextMenu, false);
  14157. }
  14158. this._onLostFocus = function () {
  14159. //this._keys = [];
  14160. pointA = pointB = undefined;
  14161. previousPinchDistance = 0;
  14162. cacheSoloPointer = null;
  14163. };
  14164. this._onMouseMove = function (evt) {
  14165. if (!engine.isPointerLock) {
  14166. return;
  14167. }
  14168. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14169. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14170. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14171. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14172. if (!noPreventDefault) {
  14173. evt.preventDefault();
  14174. }
  14175. };
  14176. this._onGestureStart = function (e) {
  14177. if (window.MSGesture === undefined) {
  14178. return;
  14179. }
  14180. if (!_this._MSGestureHandler) {
  14181. _this._MSGestureHandler = new MSGesture();
  14182. _this._MSGestureHandler.target = element;
  14183. }
  14184. _this._MSGestureHandler.addPointer(e.pointerId);
  14185. };
  14186. this._onGesture = function (e) {
  14187. _this.camera.radius *= e.scale;
  14188. if (e.preventDefault) {
  14189. if (!noPreventDefault) {
  14190. e.stopPropagation();
  14191. e.preventDefault();
  14192. }
  14193. }
  14194. };
  14195. element.addEventListener("mousemove", this._onMouseMove, false);
  14196. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14197. element.addEventListener("MSGestureChange", this._onGesture, false);
  14198. element.addEventListener("keydown", this._onKeyDown, false);
  14199. element.addEventListener("keyup", this._onKeyUp, false);
  14200. BABYLON.Tools.RegisterTopRootEvents([
  14201. { name: "blur", handler: this._onLostFocus }
  14202. ]);
  14203. };
  14204. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14205. if (element && this._observer) {
  14206. this.camera.getScene().onPointerObservable.remove(this._observer);
  14207. this._observer = null;
  14208. element.removeEventListener("contextmenu", this._onContextMenu);
  14209. element.removeEventListener("mousemove", this._onMouseMove);
  14210. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14211. element.removeEventListener("MSGestureChange", this._onGesture);
  14212. element.removeEventListener("keydown", this._onKeyDown);
  14213. element.removeEventListener("keyup", this._onKeyUp);
  14214. this._isPanClick = false;
  14215. this.pinchInwards = true;
  14216. this._onKeyDown = null;
  14217. this._onKeyUp = null;
  14218. this._onMouseMove = null;
  14219. this._onGestureStart = null;
  14220. this._onGesture = null;
  14221. this._MSGestureHandler = null;
  14222. this._onLostFocus = null;
  14223. this._onContextMenu = null;
  14224. }
  14225. BABYLON.Tools.UnregisterTopRootEvents([
  14226. { name: "blur", handler: this._onLostFocus }
  14227. ]);
  14228. };
  14229. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14230. return "ArcRotateCameraPointersInput";
  14231. };
  14232. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14233. return "pointers";
  14234. };
  14235. __decorate([
  14236. BABYLON.serialize()
  14237. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14238. __decorate([
  14239. BABYLON.serialize()
  14240. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14241. __decorate([
  14242. BABYLON.serialize()
  14243. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14244. __decorate([
  14245. BABYLON.serialize()
  14246. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14247. return ArcRotateCameraPointersInput;
  14248. }());
  14249. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14250. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14251. })(BABYLON || (BABYLON = {}));
  14252. var BABYLON;
  14253. (function (BABYLON) {
  14254. var ArcRotateCameraGamepadInput = (function () {
  14255. function ArcRotateCameraGamepadInput() {
  14256. this.gamepadRotationSensibility = 80;
  14257. this.gamepadMoveSensibility = 40;
  14258. }
  14259. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14260. var _this = this;
  14261. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14262. };
  14263. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14264. if (this._gamepads) {
  14265. this._gamepads.dispose();
  14266. }
  14267. this.gamepad = null;
  14268. };
  14269. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14270. if (this.gamepad) {
  14271. var camera = this.camera;
  14272. var RSValues = this.gamepad.rightStick;
  14273. if (RSValues.x != 0) {
  14274. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14275. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14276. camera.inertialAlphaOffset += normalizedRX;
  14277. }
  14278. }
  14279. if (RSValues.y != 0) {
  14280. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14281. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14282. camera.inertialBetaOffset += normalizedRY;
  14283. }
  14284. }
  14285. var LSValues = this.gamepad.leftStick;
  14286. if (LSValues.y != 0) {
  14287. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14288. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14289. this.camera.inertialRadiusOffset -= normalizedLY;
  14290. }
  14291. }
  14292. }
  14293. };
  14294. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14295. // Only the first gamepad can control the camera
  14296. if (gamepad.index === 0) {
  14297. this.gamepad = gamepad;
  14298. }
  14299. };
  14300. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14301. return "ArcRotateCameraGamepadInput";
  14302. };
  14303. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14304. return "gamepad";
  14305. };
  14306. __decorate([
  14307. BABYLON.serialize()
  14308. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14309. __decorate([
  14310. BABYLON.serialize()
  14311. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14312. return ArcRotateCameraGamepadInput;
  14313. }());
  14314. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14315. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14316. })(BABYLON || (BABYLON = {}));
  14317. var BABYLON;
  14318. (function (BABYLON) {
  14319. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14320. function ArcRotateCameraVRDeviceOrientationInput() {
  14321. this.alphaCorrection = 1;
  14322. this.betaCorrection = 1;
  14323. this.gammaCorrection = 1;
  14324. this._alpha = 0;
  14325. this._beta = 0;
  14326. this._gamma = 0;
  14327. this._dirty = false;
  14328. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14329. }
  14330. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14331. this.camera.attachControl(element, noPreventDefault);
  14332. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14333. };
  14334. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14335. var camera = this.camera;
  14336. this._alpha = +evt.alpha | 0;
  14337. this._beta = +evt.beta | 0;
  14338. this._gamma = +evt.gamma | 0;
  14339. this._dirty = true;
  14340. };
  14341. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14342. if (this._dirty) {
  14343. this._dirty = false;
  14344. if (this._gamma < 0) {
  14345. this._gamma = 180 + this._gamma;
  14346. }
  14347. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14348. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14349. }
  14350. };
  14351. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14352. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14353. };
  14354. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14355. return "ArcRotateCameraVRDeviceOrientationInput";
  14356. };
  14357. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14358. return "VRDeviceOrientation";
  14359. };
  14360. return ArcRotateCameraVRDeviceOrientationInput;
  14361. }());
  14362. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14363. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14364. })(BABYLON || (BABYLON = {}));
  14365. var BABYLON;
  14366. (function (BABYLON) {
  14367. var TargetCamera = (function (_super) {
  14368. __extends(TargetCamera, _super);
  14369. function TargetCamera(name, position, scene) {
  14370. _super.call(this, name, position, scene);
  14371. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14372. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14373. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14374. this.speed = 2.0;
  14375. this.noRotationConstraint = false;
  14376. this.lockedTarget = null;
  14377. this._currentTarget = BABYLON.Vector3.Zero();
  14378. this._viewMatrix = BABYLON.Matrix.Zero();
  14379. this._camMatrix = BABYLON.Matrix.Zero();
  14380. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14381. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14382. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14383. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14384. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14385. this._lookAtTemp = BABYLON.Matrix.Zero();
  14386. this._tempMatrix = BABYLON.Matrix.Zero();
  14387. }
  14388. TargetCamera.prototype.getFrontPosition = function (distance) {
  14389. var direction = this.getTarget().subtract(this.position);
  14390. direction.normalize();
  14391. direction.scaleInPlace(distance);
  14392. return this.globalPosition.add(direction);
  14393. };
  14394. TargetCamera.prototype._getLockedTargetPosition = function () {
  14395. if (!this.lockedTarget) {
  14396. return null;
  14397. }
  14398. return this.lockedTarget.position || this.lockedTarget;
  14399. };
  14400. // Cache
  14401. TargetCamera.prototype._initCache = function () {
  14402. _super.prototype._initCache.call(this);
  14403. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14404. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14405. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14406. };
  14407. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14408. if (!ignoreParentClass) {
  14409. _super.prototype._updateCache.call(this);
  14410. }
  14411. var lockedTargetPosition = this._getLockedTargetPosition();
  14412. if (!lockedTargetPosition) {
  14413. this._cache.lockedTarget = null;
  14414. }
  14415. else {
  14416. if (!this._cache.lockedTarget) {
  14417. this._cache.lockedTarget = lockedTargetPosition.clone();
  14418. }
  14419. else {
  14420. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14421. }
  14422. }
  14423. this._cache.rotation.copyFrom(this.rotation);
  14424. if (this.rotationQuaternion)
  14425. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14426. };
  14427. // Synchronized
  14428. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14429. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14430. return false;
  14431. }
  14432. var lockedTargetPosition = this._getLockedTargetPosition();
  14433. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14434. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14435. };
  14436. // Methods
  14437. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14438. var engine = this.getEngine();
  14439. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14440. };
  14441. // Target
  14442. TargetCamera.prototype.setTarget = function (target) {
  14443. this.upVector.normalize();
  14444. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14445. this._camMatrix.invert();
  14446. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14447. var vDir = target.subtract(this.position);
  14448. if (vDir.x >= 0.0) {
  14449. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14450. }
  14451. else {
  14452. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14453. }
  14454. this.rotation.z = 0;
  14455. if (isNaN(this.rotation.x)) {
  14456. this.rotation.x = 0;
  14457. }
  14458. if (isNaN(this.rotation.y)) {
  14459. this.rotation.y = 0;
  14460. }
  14461. if (isNaN(this.rotation.z)) {
  14462. this.rotation.z = 0;
  14463. }
  14464. if (this.rotationQuaternion) {
  14465. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14466. }
  14467. };
  14468. TargetCamera.prototype.getTarget = function () {
  14469. return this._currentTarget;
  14470. };
  14471. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14472. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14473. };
  14474. TargetCamera.prototype._updatePosition = function () {
  14475. this.position.addInPlace(this.cameraDirection);
  14476. };
  14477. TargetCamera.prototype._checkInputs = function () {
  14478. var needToMove = this._decideIfNeedsToMove();
  14479. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14480. // Move
  14481. if (needToMove) {
  14482. this._updatePosition();
  14483. }
  14484. // Rotate
  14485. if (needToRotate) {
  14486. this.rotation.x += this.cameraRotation.x;
  14487. this.rotation.y += this.cameraRotation.y;
  14488. if (!this.noRotationConstraint) {
  14489. var limit = (Math.PI / 2) * 0.95;
  14490. if (this.rotation.x > limit)
  14491. this.rotation.x = limit;
  14492. if (this.rotation.x < -limit)
  14493. this.rotation.x = -limit;
  14494. }
  14495. }
  14496. // Inertia
  14497. if (needToMove) {
  14498. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14499. this.cameraDirection.x = 0;
  14500. }
  14501. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14502. this.cameraDirection.y = 0;
  14503. }
  14504. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14505. this.cameraDirection.z = 0;
  14506. }
  14507. this.cameraDirection.scaleInPlace(this.inertia);
  14508. }
  14509. if (needToRotate) {
  14510. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14511. this.cameraRotation.x = 0;
  14512. }
  14513. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14514. this.cameraRotation.y = 0;
  14515. }
  14516. this.cameraRotation.scaleInPlace(this.inertia);
  14517. }
  14518. _super.prototype._checkInputs.call(this);
  14519. };
  14520. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14521. if (this.rotationQuaternion) {
  14522. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14523. //update the up vector!
  14524. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14525. }
  14526. else {
  14527. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14528. }
  14529. };
  14530. TargetCamera.prototype._getViewMatrix = function () {
  14531. if (!this.lockedTarget) {
  14532. // Compute
  14533. this._updateCameraRotationMatrix();
  14534. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14535. // Computing target and final matrix
  14536. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14537. }
  14538. else {
  14539. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14540. }
  14541. if (this.getScene().useRightHandedSystem) {
  14542. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14543. }
  14544. else {
  14545. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14546. }
  14547. return this._viewMatrix;
  14548. };
  14549. /**
  14550. * @override
  14551. * Override Camera.createRigCamera
  14552. */
  14553. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14554. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14555. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14556. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14557. if (!this.rotationQuaternion) {
  14558. this.rotationQuaternion = new BABYLON.Quaternion();
  14559. }
  14560. rigCamera._cameraRigParams = {};
  14561. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14562. }
  14563. return rigCamera;
  14564. }
  14565. return null;
  14566. };
  14567. /**
  14568. * @override
  14569. * Override Camera._updateRigCameras
  14570. */
  14571. TargetCamera.prototype._updateRigCameras = function () {
  14572. var camLeft = this._rigCameras[0];
  14573. var camRight = this._rigCameras[1];
  14574. switch (this.cameraRigMode) {
  14575. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14576. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14577. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14578. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14579. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14580. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14581. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14582. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14583. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14584. camLeft.setTarget(this.getTarget());
  14585. camRight.setTarget(this.getTarget());
  14586. break;
  14587. case BABYLON.Camera.RIG_MODE_VR:
  14588. case BABYLON.Camera.RIG_MODE_WEBVR:
  14589. if (camLeft.rotationQuaternion) {
  14590. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14591. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14592. }
  14593. else {
  14594. camLeft.rotation.copyFrom(this.rotation);
  14595. camRight.rotation.copyFrom(this.rotation);
  14596. }
  14597. camLeft.position.copyFrom(this.position);
  14598. camRight.position.copyFrom(this.position);
  14599. break;
  14600. }
  14601. _super.prototype._updateRigCameras.call(this);
  14602. };
  14603. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14604. if (!this._rigCamTransformMatrix) {
  14605. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14606. }
  14607. var target = this.getTarget();
  14608. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14609. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14610. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14611. };
  14612. TargetCamera.prototype.getTypeName = function () {
  14613. return "TargetCamera";
  14614. };
  14615. __decorate([
  14616. BABYLON.serializeAsVector3()
  14617. ], TargetCamera.prototype, "rotation", void 0);
  14618. __decorate([
  14619. BABYLON.serialize()
  14620. ], TargetCamera.prototype, "speed", void 0);
  14621. __decorate([
  14622. BABYLON.serializeAsMeshReference("lockedTargetId")
  14623. ], TargetCamera.prototype, "lockedTarget", void 0);
  14624. return TargetCamera;
  14625. }(BABYLON.Camera));
  14626. BABYLON.TargetCamera = TargetCamera;
  14627. })(BABYLON || (BABYLON = {}));
  14628. var BABYLON;
  14629. (function (BABYLON) {
  14630. var FreeCamera = (function (_super) {
  14631. __extends(FreeCamera, _super);
  14632. function FreeCamera(name, position, scene) {
  14633. var _this = this;
  14634. _super.call(this, name, position, scene);
  14635. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14636. this.checkCollisions = false;
  14637. this.applyGravity = false;
  14638. this._collider = new BABYLON.Collider();
  14639. this._needMoveForGravity = false;
  14640. this._oldPosition = BABYLON.Vector3.Zero();
  14641. this._diffPosition = BABYLON.Vector3.Zero();
  14642. this._newPosition = BABYLON.Vector3.Zero();
  14643. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14644. if (collidedMesh === void 0) { collidedMesh = null; }
  14645. //TODO move this to the collision coordinator!
  14646. if (_this.getScene().workerCollisions)
  14647. newPosition.multiplyInPlace(_this._collider.radius);
  14648. var updatePosition = function (newPos) {
  14649. _this._newPosition.copyFrom(newPos);
  14650. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14651. var oldPosition = _this.position.clone();
  14652. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14653. _this.position.addInPlace(_this._diffPosition);
  14654. if (_this.onCollide && collidedMesh) {
  14655. _this.onCollide(collidedMesh);
  14656. }
  14657. }
  14658. };
  14659. updatePosition(newPosition);
  14660. };
  14661. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14662. this.inputs.addKeyboard().addMouse();
  14663. }
  14664. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14665. //-- begin properties for backward compatibility for inputs
  14666. get: function () {
  14667. var mouse = this.inputs.attached["mouse"];
  14668. if (mouse)
  14669. return mouse.angularSensibility;
  14670. },
  14671. set: function (value) {
  14672. var mouse = this.inputs.attached["mouse"];
  14673. if (mouse)
  14674. mouse.angularSensibility = value;
  14675. },
  14676. enumerable: true,
  14677. configurable: true
  14678. });
  14679. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14680. get: function () {
  14681. var keyboard = this.inputs.attached["keyboard"];
  14682. if (keyboard)
  14683. return keyboard.keysUp;
  14684. },
  14685. set: function (value) {
  14686. var keyboard = this.inputs.attached["keyboard"];
  14687. if (keyboard)
  14688. keyboard.keysUp = value;
  14689. },
  14690. enumerable: true,
  14691. configurable: true
  14692. });
  14693. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14694. get: function () {
  14695. var keyboard = this.inputs.attached["keyboard"];
  14696. if (keyboard)
  14697. return keyboard.keysDown;
  14698. },
  14699. set: function (value) {
  14700. var keyboard = this.inputs.attached["keyboard"];
  14701. if (keyboard)
  14702. keyboard.keysDown = value;
  14703. },
  14704. enumerable: true,
  14705. configurable: true
  14706. });
  14707. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14708. get: function () {
  14709. var keyboard = this.inputs.attached["keyboard"];
  14710. if (keyboard)
  14711. return keyboard.keysLeft;
  14712. },
  14713. set: function (value) {
  14714. var keyboard = this.inputs.attached["keyboard"];
  14715. if (keyboard)
  14716. keyboard.keysLeft = value;
  14717. },
  14718. enumerable: true,
  14719. configurable: true
  14720. });
  14721. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14722. get: function () {
  14723. var keyboard = this.inputs.attached["keyboard"];
  14724. if (keyboard)
  14725. return keyboard.keysRight;
  14726. },
  14727. set: function (value) {
  14728. var keyboard = this.inputs.attached["keyboard"];
  14729. if (keyboard)
  14730. keyboard.keysRight = value;
  14731. },
  14732. enumerable: true,
  14733. configurable: true
  14734. });
  14735. // Controls
  14736. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14737. this.inputs.attachElement(element, noPreventDefault);
  14738. };
  14739. FreeCamera.prototype.detachControl = function (element) {
  14740. this.inputs.detachElement(element);
  14741. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14742. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14743. };
  14744. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14745. var globalPosition;
  14746. if (this.parent) {
  14747. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14748. }
  14749. else {
  14750. globalPosition = this.position;
  14751. }
  14752. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14753. this._collider.radius = this.ellipsoid;
  14754. //no need for clone, as long as gravity is not on.
  14755. var actualVelocity = velocity;
  14756. //add gravity to the velocity to prevent the dual-collision checking
  14757. if (this.applyGravity) {
  14758. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14759. actualVelocity = velocity.add(this.getScene().gravity);
  14760. }
  14761. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14762. };
  14763. FreeCamera.prototype._checkInputs = function () {
  14764. if (!this._localDirection) {
  14765. this._localDirection = BABYLON.Vector3.Zero();
  14766. this._transformedDirection = BABYLON.Vector3.Zero();
  14767. }
  14768. this.inputs.checkInputs();
  14769. _super.prototype._checkInputs.call(this);
  14770. };
  14771. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14772. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14773. };
  14774. FreeCamera.prototype._updatePosition = function () {
  14775. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14776. this._collideWithWorld(this.cameraDirection);
  14777. }
  14778. else {
  14779. this.position.addInPlace(this.cameraDirection);
  14780. }
  14781. };
  14782. FreeCamera.prototype.dispose = function () {
  14783. this.inputs.clear();
  14784. _super.prototype.dispose.call(this);
  14785. };
  14786. FreeCamera.prototype.getTypeName = function () {
  14787. return "FreeCamera";
  14788. };
  14789. __decorate([
  14790. BABYLON.serializeAsVector3()
  14791. ], FreeCamera.prototype, "ellipsoid", void 0);
  14792. __decorate([
  14793. BABYLON.serialize()
  14794. ], FreeCamera.prototype, "checkCollisions", void 0);
  14795. __decorate([
  14796. BABYLON.serialize()
  14797. ], FreeCamera.prototype, "applyGravity", void 0);
  14798. return FreeCamera;
  14799. }(BABYLON.TargetCamera));
  14800. BABYLON.FreeCamera = FreeCamera;
  14801. })(BABYLON || (BABYLON = {}));
  14802. var BABYLON;
  14803. (function (BABYLON) {
  14804. var FreeCameraInputsManager = (function (_super) {
  14805. __extends(FreeCameraInputsManager, _super);
  14806. function FreeCameraInputsManager(camera) {
  14807. _super.call(this, camera);
  14808. }
  14809. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14810. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14811. return this;
  14812. };
  14813. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14814. if (touchEnabled === void 0) { touchEnabled = true; }
  14815. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14816. return this;
  14817. };
  14818. FreeCameraInputsManager.prototype.addGamepad = function () {
  14819. this.add(new BABYLON.FreeCameraGamepadInput());
  14820. return this;
  14821. };
  14822. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14823. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14824. return this;
  14825. };
  14826. FreeCameraInputsManager.prototype.addTouch = function () {
  14827. this.add(new BABYLON.FreeCameraTouchInput());
  14828. return this;
  14829. };
  14830. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14831. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14832. return this;
  14833. };
  14834. return FreeCameraInputsManager;
  14835. }(BABYLON.CameraInputsManager));
  14836. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14837. })(BABYLON || (BABYLON = {}));
  14838. var BABYLON;
  14839. (function (BABYLON) {
  14840. var FollowCamera = (function (_super) {
  14841. __extends(FollowCamera, _super);
  14842. function FollowCamera(name, position, scene, target) {
  14843. _super.call(this, name, position, scene);
  14844. this.radius = 12;
  14845. this.rotationOffset = 0;
  14846. this.heightOffset = 4;
  14847. this.cameraAcceleration = 0.05;
  14848. this.maxCameraSpeed = 20;
  14849. this.target = target;
  14850. }
  14851. FollowCamera.prototype.getRadians = function (degrees) {
  14852. return degrees * Math.PI / 180;
  14853. };
  14854. FollowCamera.prototype.follow = function (cameraTarget) {
  14855. if (!cameraTarget)
  14856. return;
  14857. var yRotation;
  14858. if (cameraTarget.rotationQuaternion) {
  14859. var rotMatrix = new BABYLON.Matrix();
  14860. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14861. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14862. }
  14863. else {
  14864. yRotation = cameraTarget.rotation.y;
  14865. }
  14866. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14867. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14868. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14869. var dx = targetX - this.position.x;
  14870. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14871. var dz = (targetZ) - this.position.z;
  14872. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14873. var vy = dy * this.cameraAcceleration;
  14874. var vz = dz * this.cameraAcceleration * 2;
  14875. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14876. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14877. }
  14878. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14879. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14880. }
  14881. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14882. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14883. }
  14884. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14885. this.setTarget(cameraTarget.position);
  14886. };
  14887. FollowCamera.prototype._checkInputs = function () {
  14888. _super.prototype._checkInputs.call(this);
  14889. this.follow(this.target);
  14890. };
  14891. FollowCamera.prototype.getTypeName = function () {
  14892. return "FollowCamera";
  14893. };
  14894. __decorate([
  14895. BABYLON.serialize()
  14896. ], FollowCamera.prototype, "radius", void 0);
  14897. __decorate([
  14898. BABYLON.serialize()
  14899. ], FollowCamera.prototype, "rotationOffset", void 0);
  14900. __decorate([
  14901. BABYLON.serialize()
  14902. ], FollowCamera.prototype, "heightOffset", void 0);
  14903. __decorate([
  14904. BABYLON.serialize()
  14905. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14906. __decorate([
  14907. BABYLON.serialize()
  14908. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14909. __decorate([
  14910. BABYLON.serializeAsMeshReference("lockedTargetId")
  14911. ], FollowCamera.prototype, "target", void 0);
  14912. return FollowCamera;
  14913. }(BABYLON.TargetCamera));
  14914. BABYLON.FollowCamera = FollowCamera;
  14915. var ArcFollowCamera = (function (_super) {
  14916. __extends(ArcFollowCamera, _super);
  14917. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14918. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14919. this.alpha = alpha;
  14920. this.beta = beta;
  14921. this.radius = radius;
  14922. this.target = target;
  14923. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14924. this.follow();
  14925. }
  14926. ArcFollowCamera.prototype.follow = function () {
  14927. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14928. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14929. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14930. this.position = this.target.position.add(this._cartesianCoordinates);
  14931. this.setTarget(this.target.position);
  14932. };
  14933. ArcFollowCamera.prototype._checkInputs = function () {
  14934. _super.prototype._checkInputs.call(this);
  14935. this.follow();
  14936. };
  14937. ArcFollowCamera.prototype.getTypeName = function () {
  14938. return "ArcFollowCamera";
  14939. };
  14940. return ArcFollowCamera;
  14941. }(BABYLON.TargetCamera));
  14942. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14943. })(BABYLON || (BABYLON = {}));
  14944. var BABYLON;
  14945. (function (BABYLON) {
  14946. // We're mainly based on the logic defined into the FreeCamera code
  14947. var TouchCamera = (function (_super) {
  14948. __extends(TouchCamera, _super);
  14949. //-- end properties for backward compatibility for inputs
  14950. function TouchCamera(name, position, scene) {
  14951. _super.call(this, name, position, scene);
  14952. this.inputs.addTouch();
  14953. this._setupInputs();
  14954. }
  14955. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14956. //-- Begin properties for backward compatibility for inputs
  14957. get: function () {
  14958. var touch = this.inputs.attached["touch"];
  14959. if (touch)
  14960. return touch.touchAngularSensibility;
  14961. },
  14962. set: function (value) {
  14963. var touch = this.inputs.attached["touch"];
  14964. if (touch)
  14965. touch.touchAngularSensibility = value;
  14966. },
  14967. enumerable: true,
  14968. configurable: true
  14969. });
  14970. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14971. get: function () {
  14972. var touch = this.inputs.attached["touch"];
  14973. if (touch)
  14974. return touch.touchMoveSensibility;
  14975. },
  14976. set: function (value) {
  14977. var touch = this.inputs.attached["touch"];
  14978. if (touch)
  14979. touch.touchMoveSensibility = value;
  14980. },
  14981. enumerable: true,
  14982. configurable: true
  14983. });
  14984. TouchCamera.prototype.getTypeName = function () {
  14985. return "TouchCamera";
  14986. };
  14987. TouchCamera.prototype._setupInputs = function () {
  14988. var mouse = this.inputs.attached["mouse"];
  14989. if (mouse) {
  14990. mouse.touchEnabled = false;
  14991. }
  14992. };
  14993. return TouchCamera;
  14994. }(BABYLON.FreeCamera));
  14995. BABYLON.TouchCamera = TouchCamera;
  14996. })(BABYLON || (BABYLON = {}));
  14997. var BABYLON;
  14998. (function (BABYLON) {
  14999. var ArcRotateCamera = (function (_super) {
  15000. __extends(ArcRotateCamera, _super);
  15001. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15002. var _this = this;
  15003. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15004. this.inertialAlphaOffset = 0;
  15005. this.inertialBetaOffset = 0;
  15006. this.inertialRadiusOffset = 0;
  15007. this.lowerAlphaLimit = null;
  15008. this.upperAlphaLimit = null;
  15009. this.lowerBetaLimit = 0.01;
  15010. this.upperBetaLimit = Math.PI;
  15011. this.lowerRadiusLimit = null;
  15012. this.upperRadiusLimit = null;
  15013. this.inertialPanningX = 0;
  15014. this.inertialPanningY = 0;
  15015. //-- end properties for backward compatibility for inputs
  15016. this.zoomOnFactor = 1;
  15017. this.targetScreenOffset = BABYLON.Vector2.Zero();
  15018. this.allowUpsideDown = true;
  15019. this._viewMatrix = new BABYLON.Matrix();
  15020. // Panning
  15021. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15022. this.checkCollisions = false;
  15023. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15024. this._collider = new BABYLON.Collider();
  15025. this._previousPosition = BABYLON.Vector3.Zero();
  15026. this._collisionVelocity = BABYLON.Vector3.Zero();
  15027. this._newPosition = BABYLON.Vector3.Zero();
  15028. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15029. if (collidedMesh === void 0) { collidedMesh = null; }
  15030. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15031. newPosition.multiplyInPlace(_this._collider.radius);
  15032. }
  15033. if (!collidedMesh) {
  15034. _this._previousPosition.copyFrom(_this.position);
  15035. }
  15036. else {
  15037. _this.setPosition(newPosition);
  15038. if (_this.onCollide) {
  15039. _this.onCollide(collidedMesh);
  15040. }
  15041. }
  15042. // Recompute because of constraints
  15043. var cosa = Math.cos(_this.alpha);
  15044. var sina = Math.sin(_this.alpha);
  15045. var cosb = Math.cos(_this.beta);
  15046. var sinb = Math.sin(_this.beta);
  15047. if (sinb === 0) {
  15048. sinb = 0.0001;
  15049. }
  15050. var target = _this._getTargetPosition();
  15051. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15052. _this.position.copyFrom(_this._newPosition);
  15053. var up = _this.upVector;
  15054. if (_this.allowUpsideDown && _this.beta < 0) {
  15055. up = up.clone();
  15056. up = up.negate();
  15057. }
  15058. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15059. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15060. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15061. _this._collisionTriggered = false;
  15062. };
  15063. if (!target) {
  15064. this.target = BABYLON.Vector3.Zero();
  15065. }
  15066. else {
  15067. this.target = target;
  15068. }
  15069. this.alpha = alpha;
  15070. this.beta = beta;
  15071. this.radius = radius;
  15072. this.getViewMatrix();
  15073. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15074. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15075. }
  15076. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15077. //-- begin properties for backward compatibility for inputs
  15078. get: function () {
  15079. var pointers = this.inputs.attached["pointers"];
  15080. if (pointers)
  15081. return pointers.angularSensibilityX;
  15082. },
  15083. set: function (value) {
  15084. var pointers = this.inputs.attached["pointers"];
  15085. if (pointers) {
  15086. pointers.angularSensibilityX = value;
  15087. }
  15088. },
  15089. enumerable: true,
  15090. configurable: true
  15091. });
  15092. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15093. get: function () {
  15094. var pointers = this.inputs.attached["pointers"];
  15095. if (pointers)
  15096. return pointers.angularSensibilityY;
  15097. },
  15098. set: function (value) {
  15099. var pointers = this.inputs.attached["pointers"];
  15100. if (pointers) {
  15101. pointers.angularSensibilityY = value;
  15102. }
  15103. },
  15104. enumerable: true,
  15105. configurable: true
  15106. });
  15107. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15108. get: function () {
  15109. var pointers = this.inputs.attached["pointers"];
  15110. if (pointers)
  15111. return pointers.pinchPrecision;
  15112. },
  15113. set: function (value) {
  15114. var pointers = this.inputs.attached["pointers"];
  15115. if (pointers) {
  15116. pointers.pinchPrecision = value;
  15117. }
  15118. },
  15119. enumerable: true,
  15120. configurable: true
  15121. });
  15122. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15123. get: function () {
  15124. var pointers = this.inputs.attached["pointers"];
  15125. if (pointers)
  15126. return pointers.panningSensibility;
  15127. },
  15128. set: function (value) {
  15129. var pointers = this.inputs.attached["pointers"];
  15130. if (pointers) {
  15131. pointers.panningSensibility = value;
  15132. }
  15133. },
  15134. enumerable: true,
  15135. configurable: true
  15136. });
  15137. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15138. get: function () {
  15139. var keyboard = this.inputs.attached["keyboard"];
  15140. if (keyboard)
  15141. return keyboard.keysUp;
  15142. },
  15143. set: function (value) {
  15144. var keyboard = this.inputs.attached["keyboard"];
  15145. if (keyboard)
  15146. keyboard.keysUp = value;
  15147. },
  15148. enumerable: true,
  15149. configurable: true
  15150. });
  15151. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15152. get: function () {
  15153. var keyboard = this.inputs.attached["keyboard"];
  15154. if (keyboard)
  15155. return keyboard.keysDown;
  15156. },
  15157. set: function (value) {
  15158. var keyboard = this.inputs.attached["keyboard"];
  15159. if (keyboard)
  15160. keyboard.keysDown = value;
  15161. },
  15162. enumerable: true,
  15163. configurable: true
  15164. });
  15165. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15166. get: function () {
  15167. var keyboard = this.inputs.attached["keyboard"];
  15168. if (keyboard)
  15169. return keyboard.keysLeft;
  15170. },
  15171. set: function (value) {
  15172. var keyboard = this.inputs.attached["keyboard"];
  15173. if (keyboard)
  15174. keyboard.keysLeft = value;
  15175. },
  15176. enumerable: true,
  15177. configurable: true
  15178. });
  15179. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15180. get: function () {
  15181. var keyboard = this.inputs.attached["keyboard"];
  15182. if (keyboard)
  15183. return keyboard.keysRight;
  15184. },
  15185. set: function (value) {
  15186. var keyboard = this.inputs.attached["keyboard"];
  15187. if (keyboard)
  15188. keyboard.keysRight = value;
  15189. },
  15190. enumerable: true,
  15191. configurable: true
  15192. });
  15193. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15194. get: function () {
  15195. var mousewheel = this.inputs.attached["mousewheel"];
  15196. if (mousewheel)
  15197. return mousewheel.wheelPrecision;
  15198. },
  15199. set: function (value) {
  15200. var mousewheel = this.inputs.attached["mousewheel"];
  15201. if (mousewheel)
  15202. mousewheel.wheelPrecision = value;
  15203. },
  15204. enumerable: true,
  15205. configurable: true
  15206. });
  15207. // Cache
  15208. ArcRotateCamera.prototype._initCache = function () {
  15209. _super.prototype._initCache.call(this);
  15210. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15211. this._cache.alpha = undefined;
  15212. this._cache.beta = undefined;
  15213. this._cache.radius = undefined;
  15214. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15215. };
  15216. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15217. if (!ignoreParentClass) {
  15218. _super.prototype._updateCache.call(this);
  15219. }
  15220. this._cache.target.copyFrom(this._getTargetPosition());
  15221. this._cache.alpha = this.alpha;
  15222. this._cache.beta = this.beta;
  15223. this._cache.radius = this.radius;
  15224. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15225. };
  15226. ArcRotateCamera.prototype._getTargetPosition = function () {
  15227. if (this.target.getAbsolutePosition) {
  15228. var pos = this.target.getAbsolutePosition();
  15229. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15230. }
  15231. return this.target;
  15232. };
  15233. // Synchronized
  15234. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15235. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15236. return false;
  15237. return this._cache.target.equals(this.target)
  15238. && this._cache.alpha === this.alpha
  15239. && this._cache.beta === this.beta
  15240. && this._cache.radius === this.radius
  15241. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15242. };
  15243. // Methods
  15244. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15245. var _this = this;
  15246. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15247. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15248. this._useCtrlForPanning = useCtrlForPanning;
  15249. this._panningMouseButton = panningMouseButton;
  15250. this.inputs.attachElement(element, noPreventDefault);
  15251. this._reset = function () {
  15252. _this.inertialAlphaOffset = 0;
  15253. _this.inertialBetaOffset = 0;
  15254. _this.inertialRadiusOffset = 0;
  15255. };
  15256. };
  15257. ArcRotateCamera.prototype.detachControl = function (element) {
  15258. this.inputs.detachElement(element);
  15259. if (this._reset) {
  15260. this._reset();
  15261. }
  15262. };
  15263. ArcRotateCamera.prototype._checkInputs = function () {
  15264. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15265. if (this._collisionTriggered) {
  15266. return;
  15267. }
  15268. this.inputs.checkInputs();
  15269. // Inertia
  15270. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15271. this.beta += this.inertialBetaOffset;
  15272. if (this.getScene().useRightHandedSystem) {
  15273. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15274. }
  15275. else {
  15276. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15277. }
  15278. this.radius -= this.inertialRadiusOffset;
  15279. this.inertialAlphaOffset *= this.inertia;
  15280. this.inertialBetaOffset *= this.inertia;
  15281. this.inertialRadiusOffset *= this.inertia;
  15282. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15283. this.inertialAlphaOffset = 0;
  15284. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15285. this.inertialBetaOffset = 0;
  15286. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15287. this.inertialRadiusOffset = 0;
  15288. }
  15289. // Panning inertia
  15290. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15291. if (!this._localDirection) {
  15292. this._localDirection = BABYLON.Vector3.Zero();
  15293. this._transformedDirection = BABYLON.Vector3.Zero();
  15294. }
  15295. this.inertialPanningX *= this.inertia;
  15296. this.inertialPanningY *= this.inertia;
  15297. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15298. this.inertialPanningX = 0;
  15299. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15300. this.inertialPanningY = 0;
  15301. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15302. this._localDirection.multiplyInPlace(this.panningAxis);
  15303. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15304. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15305. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15306. if (!this.panningAxis.y) {
  15307. this._transformedDirection.y = 0;
  15308. }
  15309. if (!this.target.getAbsolutePosition) {
  15310. this.target.addInPlace(this._transformedDirection);
  15311. }
  15312. }
  15313. // Limits
  15314. this._checkLimits();
  15315. _super.prototype._checkInputs.call(this);
  15316. };
  15317. ArcRotateCamera.prototype._checkLimits = function () {
  15318. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15319. if (this.allowUpsideDown && this.beta > Math.PI) {
  15320. this.beta = this.beta - (2 * Math.PI);
  15321. }
  15322. }
  15323. else {
  15324. if (this.beta < this.lowerBetaLimit) {
  15325. this.beta = this.lowerBetaLimit;
  15326. }
  15327. }
  15328. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15329. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15330. this.beta = this.beta + (2 * Math.PI);
  15331. }
  15332. }
  15333. else {
  15334. if (this.beta > this.upperBetaLimit) {
  15335. this.beta = this.upperBetaLimit;
  15336. }
  15337. }
  15338. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15339. this.alpha = this.lowerAlphaLimit;
  15340. }
  15341. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15342. this.alpha = this.upperAlphaLimit;
  15343. }
  15344. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15345. this.radius = this.lowerRadiusLimit;
  15346. }
  15347. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15348. this.radius = this.upperRadiusLimit;
  15349. }
  15350. };
  15351. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15352. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15353. this.radius = radiusv3.length();
  15354. // Alpha
  15355. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15356. if (radiusv3.z < 0) {
  15357. this.alpha = 2 * Math.PI - this.alpha;
  15358. }
  15359. // Beta
  15360. this.beta = Math.acos(radiusv3.y / this.radius);
  15361. this._checkLimits();
  15362. };
  15363. ArcRotateCamera.prototype.setPosition = function (position) {
  15364. if (this.position.equals(position)) {
  15365. return;
  15366. }
  15367. this.position.copyFrom(position);
  15368. this.rebuildAnglesAndRadius();
  15369. };
  15370. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15371. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15372. if (this._getTargetPosition().equals(target)) {
  15373. return;
  15374. }
  15375. if (toBoundingCenter && target.getBoundingInfo) {
  15376. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15377. }
  15378. else {
  15379. this._targetBoundingCenter = null;
  15380. }
  15381. this.target = target;
  15382. this.rebuildAnglesAndRadius();
  15383. };
  15384. ArcRotateCamera.prototype._getViewMatrix = function () {
  15385. // Compute
  15386. var cosa = Math.cos(this.alpha);
  15387. var sina = Math.sin(this.alpha);
  15388. var cosb = Math.cos(this.beta);
  15389. var sinb = Math.sin(this.beta);
  15390. if (sinb === 0) {
  15391. sinb = 0.0001;
  15392. }
  15393. var target = this._getTargetPosition();
  15394. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15395. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15396. this._collider.radius = this.collisionRadius;
  15397. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15398. this._collisionTriggered = true;
  15399. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15400. }
  15401. else {
  15402. this.position.copyFrom(this._newPosition);
  15403. var up = this.upVector;
  15404. if (this.allowUpsideDown && this.beta < 0) {
  15405. up = up.clone();
  15406. up = up.negate();
  15407. }
  15408. if (this.getScene().useRightHandedSystem) {
  15409. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15410. }
  15411. else {
  15412. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15413. }
  15414. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15415. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15416. }
  15417. return this._viewMatrix;
  15418. };
  15419. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15420. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15421. meshes = meshes || this.getScene().meshes;
  15422. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15423. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15424. this.radius = distance * this.zoomOnFactor;
  15425. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15426. };
  15427. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15428. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15429. var meshesOrMinMaxVector;
  15430. var distance;
  15431. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15432. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15433. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15434. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15435. }
  15436. else {
  15437. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15438. distance = meshesOrMinMaxVectorAndDistance.distance;
  15439. }
  15440. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15441. if (!doNotUpdateMaxZ) {
  15442. this.maxZ = distance * 2;
  15443. }
  15444. };
  15445. /**
  15446. * @override
  15447. * Override Camera.createRigCamera
  15448. */
  15449. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15450. var alphaShift;
  15451. switch (this.cameraRigMode) {
  15452. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15453. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15454. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15455. case BABYLON.Camera.RIG_MODE_VR:
  15456. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15457. break;
  15458. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15459. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15460. break;
  15461. }
  15462. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15463. rigCam._cameraRigParams = {};
  15464. return rigCam;
  15465. };
  15466. /**
  15467. * @override
  15468. * Override Camera._updateRigCameras
  15469. */
  15470. ArcRotateCamera.prototype._updateRigCameras = function () {
  15471. var camLeft = this._rigCameras[0];
  15472. var camRight = this._rigCameras[1];
  15473. camLeft.beta = camRight.beta = this.beta;
  15474. camLeft.radius = camRight.radius = this.radius;
  15475. switch (this.cameraRigMode) {
  15476. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15477. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15478. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15479. case BABYLON.Camera.RIG_MODE_VR:
  15480. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15481. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15482. break;
  15483. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15484. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15485. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15486. break;
  15487. }
  15488. _super.prototype._updateRigCameras.call(this);
  15489. };
  15490. ArcRotateCamera.prototype.dispose = function () {
  15491. this.inputs.clear();
  15492. _super.prototype.dispose.call(this);
  15493. };
  15494. ArcRotateCamera.prototype.getTypeName = function () {
  15495. return "ArcRotateCamera";
  15496. };
  15497. __decorate([
  15498. BABYLON.serialize()
  15499. ], ArcRotateCamera.prototype, "alpha", void 0);
  15500. __decorate([
  15501. BABYLON.serialize()
  15502. ], ArcRotateCamera.prototype, "beta", void 0);
  15503. __decorate([
  15504. BABYLON.serialize()
  15505. ], ArcRotateCamera.prototype, "radius", void 0);
  15506. __decorate([
  15507. BABYLON.serializeAsVector3()
  15508. ], ArcRotateCamera.prototype, "target", void 0);
  15509. __decorate([
  15510. BABYLON.serialize()
  15511. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15512. __decorate([
  15513. BABYLON.serialize()
  15514. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15515. __decorate([
  15516. BABYLON.serialize()
  15517. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15518. __decorate([
  15519. BABYLON.serialize()
  15520. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15521. __decorate([
  15522. BABYLON.serialize()
  15523. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15524. __decorate([
  15525. BABYLON.serialize()
  15526. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15527. __decorate([
  15528. BABYLON.serialize()
  15529. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15530. __decorate([
  15531. BABYLON.serialize()
  15532. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15533. __decorate([
  15534. BABYLON.serialize()
  15535. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15536. __decorate([
  15537. BABYLON.serialize()
  15538. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15539. __decorate([
  15540. BABYLON.serialize()
  15541. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15542. __decorate([
  15543. BABYLON.serialize()
  15544. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15545. __decorate([
  15546. BABYLON.serialize()
  15547. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15548. return ArcRotateCamera;
  15549. }(BABYLON.TargetCamera));
  15550. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15551. })(BABYLON || (BABYLON = {}));
  15552. var BABYLON;
  15553. (function (BABYLON) {
  15554. var ArcRotateCameraInputsManager = (function (_super) {
  15555. __extends(ArcRotateCameraInputsManager, _super);
  15556. function ArcRotateCameraInputsManager(camera) {
  15557. _super.call(this, camera);
  15558. }
  15559. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15560. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15561. return this;
  15562. };
  15563. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15564. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15565. return this;
  15566. };
  15567. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15568. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15569. return this;
  15570. };
  15571. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15572. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15573. return this;
  15574. };
  15575. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15576. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15577. return this;
  15578. };
  15579. return ArcRotateCameraInputsManager;
  15580. }(BABYLON.CameraInputsManager));
  15581. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15582. })(BABYLON || (BABYLON = {}));
  15583. var BABYLON;
  15584. (function (BABYLON) {
  15585. var RenderingManager = (function () {
  15586. function RenderingManager(scene) {
  15587. this._renderingGroups = new Array();
  15588. this._autoClearDepthStencil = {};
  15589. this._customOpaqueSortCompareFn = {};
  15590. this._customAlphaTestSortCompareFn = {};
  15591. this._customTransparentSortCompareFn = {};
  15592. this._scene = scene;
  15593. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15594. this._autoClearDepthStencil[i] = true;
  15595. }
  15596. }
  15597. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15598. if (this._scene._activeParticleSystems.length === 0) {
  15599. return;
  15600. }
  15601. // Particles
  15602. var activeCamera = this._scene.activeCamera;
  15603. this._scene._particlesDuration.beginMonitoring();
  15604. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15605. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15606. if (particleSystem.renderingGroupId !== index) {
  15607. continue;
  15608. }
  15609. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15610. continue;
  15611. }
  15612. this._clearDepthStencilBuffer();
  15613. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15614. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15615. }
  15616. }
  15617. this._scene._particlesDuration.endMonitoring(false);
  15618. };
  15619. RenderingManager.prototype._renderSprites = function (index) {
  15620. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15621. return;
  15622. }
  15623. // Sprites
  15624. var activeCamera = this._scene.activeCamera;
  15625. this._scene._spritesDuration.beginMonitoring();
  15626. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15627. var spriteManager = this._scene.spriteManagers[id];
  15628. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15629. this._clearDepthStencilBuffer();
  15630. spriteManager.render();
  15631. }
  15632. }
  15633. this._scene._spritesDuration.endMonitoring(false);
  15634. };
  15635. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15636. if (this._depthStencilBufferAlreadyCleaned) {
  15637. return;
  15638. }
  15639. this._scene.getEngine().clear(0, false, true, true);
  15640. this._depthStencilBufferAlreadyCleaned = true;
  15641. };
  15642. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15643. if (this._currentRenderSprites) {
  15644. this._renderSprites(this._currentIndex);
  15645. }
  15646. if (this._currentRenderParticles) {
  15647. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15648. }
  15649. };
  15650. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15651. this._currentActiveMeshes = activeMeshes;
  15652. this._currentRenderParticles = renderParticles;
  15653. this._currentRenderSprites = renderSprites;
  15654. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15655. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15656. var renderingGroup = this._renderingGroups[index];
  15657. var needToStepBack = false;
  15658. this._currentIndex = index;
  15659. if (renderingGroup) {
  15660. if (this._autoClearDepthStencil[index]) {
  15661. this._clearDepthStencilBuffer();
  15662. }
  15663. if (!renderingGroup.onBeforeTransparentRendering) {
  15664. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15665. }
  15666. if (!renderingGroup.render(customRenderFunction)) {
  15667. this._renderingGroups.splice(index, 1);
  15668. needToStepBack = true;
  15669. this._renderSpritesAndParticles();
  15670. }
  15671. }
  15672. else {
  15673. this._renderSpritesAndParticles();
  15674. }
  15675. if (needToStepBack) {
  15676. index--;
  15677. }
  15678. }
  15679. };
  15680. RenderingManager.prototype.reset = function () {
  15681. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15682. var renderingGroup = this._renderingGroups[index];
  15683. if (renderingGroup) {
  15684. renderingGroup.prepare();
  15685. }
  15686. }
  15687. };
  15688. RenderingManager.prototype.dispatch = function (subMesh) {
  15689. var mesh = subMesh.getMesh();
  15690. var renderingGroupId = mesh.renderingGroupId || 0;
  15691. if (!this._renderingGroups[renderingGroupId]) {
  15692. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15693. }
  15694. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15695. };
  15696. /**
  15697. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15698. * This allowed control for front to back rendering or reversly depending of the special needs.
  15699. *
  15700. * @param renderingGroupId The rendering group id corresponding to its index
  15701. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15702. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15703. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15704. */
  15705. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15706. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15707. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15708. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15709. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15710. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15711. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15712. if (this._renderingGroups[renderingGroupId]) {
  15713. var group = this._renderingGroups[renderingGroupId];
  15714. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15715. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15716. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15717. }
  15718. };
  15719. /**
  15720. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15721. *
  15722. * @param renderingGroupId The rendering group id corresponding to its index
  15723. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15724. */
  15725. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15726. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15727. };
  15728. /**
  15729. * The max id used for rendering groups (not included)
  15730. */
  15731. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15732. /**
  15733. * The min id used for rendering groups (included)
  15734. */
  15735. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15736. return RenderingManager;
  15737. }());
  15738. BABYLON.RenderingManager = RenderingManager;
  15739. })(BABYLON || (BABYLON = {}));
  15740. var BABYLON;
  15741. (function (BABYLON) {
  15742. var RenderingGroup = (function () {
  15743. /**
  15744. * Creates a new rendering group.
  15745. * @param index The rendering group index
  15746. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15747. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15748. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15749. */
  15750. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15751. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15752. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15753. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15754. this.index = index;
  15755. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15756. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15757. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15758. this._scene = scene;
  15759. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15760. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15761. this.transparentSortCompareFn = transparentSortCompareFn;
  15762. }
  15763. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15764. /**
  15765. * Set the opaque sort comparison function.
  15766. * If null the sub meshes will be render in the order they were created
  15767. */
  15768. set: function (value) {
  15769. this._opaqueSortCompareFn = value;
  15770. if (value) {
  15771. this._renderOpaque = this.renderOpaqueSorted;
  15772. }
  15773. else {
  15774. this._renderOpaque = RenderingGroup.renderUnsorted;
  15775. }
  15776. },
  15777. enumerable: true,
  15778. configurable: true
  15779. });
  15780. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15781. /**
  15782. * Set the alpha test sort comparison function.
  15783. * If null the sub meshes will be render in the order they were created
  15784. */
  15785. set: function (value) {
  15786. this._alphaTestSortCompareFn = value;
  15787. if (value) {
  15788. this._renderAlphaTest = this.renderAlphaTestSorted;
  15789. }
  15790. else {
  15791. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15792. }
  15793. },
  15794. enumerable: true,
  15795. configurable: true
  15796. });
  15797. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15798. /**
  15799. * Set the transparent sort comparison function.
  15800. * If null the sub meshes will be render in the order they were created
  15801. */
  15802. set: function (value) {
  15803. if (value) {
  15804. this._transparentSortCompareFn = value;
  15805. }
  15806. else {
  15807. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15808. }
  15809. this._renderTransparent = this.renderTransparentSorted;
  15810. },
  15811. enumerable: true,
  15812. configurable: true
  15813. });
  15814. /**
  15815. * Render all the sub meshes contained in the group.
  15816. * @param customRenderFunction Used to override the default render behaviour of the group.
  15817. * @returns true if rendered some submeshes.
  15818. */
  15819. RenderingGroup.prototype.render = function (customRenderFunction) {
  15820. if (customRenderFunction) {
  15821. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15822. return true;
  15823. }
  15824. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15825. if (this.onBeforeTransparentRendering) {
  15826. this.onBeforeTransparentRendering();
  15827. }
  15828. return false;
  15829. }
  15830. var engine = this._scene.getEngine();
  15831. // Opaque
  15832. this._renderOpaque(this._opaqueSubMeshes);
  15833. // Alpha test
  15834. engine.setAlphaTesting(true);
  15835. this._renderAlphaTest(this._alphaTestSubMeshes);
  15836. engine.setAlphaTesting(false);
  15837. if (this.onBeforeTransparentRendering) {
  15838. this.onBeforeTransparentRendering();
  15839. }
  15840. // Transparent
  15841. this._renderTransparent(this._transparentSubMeshes);
  15842. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15843. return true;
  15844. };
  15845. /**
  15846. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15847. * @param subMeshes The submeshes to render
  15848. */
  15849. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15850. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15851. };
  15852. /**
  15853. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15854. * @param subMeshes The submeshes to render
  15855. */
  15856. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15857. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15858. };
  15859. /**
  15860. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15861. * @param subMeshes The submeshes to render
  15862. */
  15863. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15864. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15865. };
  15866. /**
  15867. * Renders the submeshes in a specified order.
  15868. * @param subMeshes The submeshes to sort before render
  15869. * @param sortCompareFn The comparison function use to sort
  15870. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15871. * @param transparent Specifies to activate blending if true
  15872. */
  15873. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15874. var subIndex = 0;
  15875. var subMesh;
  15876. for (; subIndex < subMeshes.length; subIndex++) {
  15877. subMesh = subMeshes.data[subIndex];
  15878. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15879. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15880. }
  15881. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15882. sortedArray.sort(sortCompareFn);
  15883. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15884. subMesh = sortedArray[subIndex];
  15885. subMesh.render(transparent);
  15886. }
  15887. };
  15888. /**
  15889. * Renders the submeshes in the order they were dispatched (no sort applied).
  15890. * @param subMeshes The submeshes to render
  15891. */
  15892. RenderingGroup.renderUnsorted = function (subMeshes) {
  15893. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15894. var submesh = subMeshes.data[subIndex];
  15895. submesh.render(false);
  15896. }
  15897. };
  15898. /**
  15899. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15900. * are rendered back to front if in the same alpha index.
  15901. *
  15902. * @param a The first submesh
  15903. * @param b The second submesh
  15904. * @returns The result of the comparison
  15905. */
  15906. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15907. // Alpha index first
  15908. if (a._alphaIndex > b._alphaIndex) {
  15909. return 1;
  15910. }
  15911. if (a._alphaIndex < b._alphaIndex) {
  15912. return -1;
  15913. }
  15914. // Then distance to camera
  15915. return RenderingGroup.backToFrontSortCompare(a, b);
  15916. };
  15917. /**
  15918. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15919. * are rendered back to front.
  15920. *
  15921. * @param a The first submesh
  15922. * @param b The second submesh
  15923. * @returns The result of the comparison
  15924. */
  15925. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15926. // Then distance to camera
  15927. if (a._distanceToCamera < b._distanceToCamera) {
  15928. return 1;
  15929. }
  15930. if (a._distanceToCamera > b._distanceToCamera) {
  15931. return -1;
  15932. }
  15933. return 0;
  15934. };
  15935. /**
  15936. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15937. * are rendered front to back (prevent overdraw).
  15938. *
  15939. * @param a The first submesh
  15940. * @param b The second submesh
  15941. * @returns The result of the comparison
  15942. */
  15943. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15944. // Then distance to camera
  15945. if (a._distanceToCamera < b._distanceToCamera) {
  15946. return -1;
  15947. }
  15948. if (a._distanceToCamera > b._distanceToCamera) {
  15949. return 1;
  15950. }
  15951. return 0;
  15952. };
  15953. /**
  15954. * Resets the different lists of submeshes to prepare a new frame.
  15955. */
  15956. RenderingGroup.prototype.prepare = function () {
  15957. this._opaqueSubMeshes.reset();
  15958. this._transparentSubMeshes.reset();
  15959. this._alphaTestSubMeshes.reset();
  15960. };
  15961. /**
  15962. * Inserts the submesh in its correct queue depending on its material.
  15963. * @param subMesh The submesh to dispatch
  15964. */
  15965. RenderingGroup.prototype.dispatch = function (subMesh) {
  15966. var material = subMesh.getMaterial();
  15967. var mesh = subMesh.getMesh();
  15968. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15969. this._transparentSubMeshes.push(subMesh);
  15970. }
  15971. else if (material.needAlphaTesting()) {
  15972. this._alphaTestSubMeshes.push(subMesh);
  15973. }
  15974. else {
  15975. this._opaqueSubMeshes.push(subMesh); // Opaque
  15976. }
  15977. };
  15978. return RenderingGroup;
  15979. }());
  15980. BABYLON.RenderingGroup = RenderingGroup;
  15981. })(BABYLON || (BABYLON = {}));
  15982. var BABYLON;
  15983. (function (BABYLON) {
  15984. var PointerEventTypes = (function () {
  15985. function PointerEventTypes() {
  15986. }
  15987. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15988. get: function () {
  15989. return PointerEventTypes._POINTERDOWN;
  15990. },
  15991. enumerable: true,
  15992. configurable: true
  15993. });
  15994. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15995. get: function () {
  15996. return PointerEventTypes._POINTERUP;
  15997. },
  15998. enumerable: true,
  15999. configurable: true
  16000. });
  16001. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16002. get: function () {
  16003. return PointerEventTypes._POINTERMOVE;
  16004. },
  16005. enumerable: true,
  16006. configurable: true
  16007. });
  16008. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16009. get: function () {
  16010. return PointerEventTypes._POINTERWHEEL;
  16011. },
  16012. enumerable: true,
  16013. configurable: true
  16014. });
  16015. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16016. get: function () {
  16017. return PointerEventTypes._POINTERPICK;
  16018. },
  16019. enumerable: true,
  16020. configurable: true
  16021. });
  16022. PointerEventTypes._POINTERDOWN = 0x01;
  16023. PointerEventTypes._POINTERUP = 0x02;
  16024. PointerEventTypes._POINTERMOVE = 0x04;
  16025. PointerEventTypes._POINTERWHEEL = 0x08;
  16026. PointerEventTypes._POINTERPICK = 0x10;
  16027. return PointerEventTypes;
  16028. }());
  16029. BABYLON.PointerEventTypes = PointerEventTypes;
  16030. var PointerInfoBase = (function () {
  16031. function PointerInfoBase(type, event) {
  16032. this.type = type;
  16033. this.event = event;
  16034. }
  16035. return PointerInfoBase;
  16036. }());
  16037. BABYLON.PointerInfoBase = PointerInfoBase;
  16038. /**
  16039. * This class is used to store pointer related info for the onPrePointerObservable event.
  16040. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16041. */
  16042. var PointerInfoPre = (function (_super) {
  16043. __extends(PointerInfoPre, _super);
  16044. function PointerInfoPre(type, event, localX, localY) {
  16045. _super.call(this, type, event);
  16046. this.skipOnPointerObservable = false;
  16047. this.localPosition = new BABYLON.Vector2(localX, localY);
  16048. }
  16049. return PointerInfoPre;
  16050. }(PointerInfoBase));
  16051. BABYLON.PointerInfoPre = PointerInfoPre;
  16052. /**
  16053. * This type contains all the data related to a pointer event in Babylon.js.
  16054. * 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.
  16055. */
  16056. var PointerInfo = (function (_super) {
  16057. __extends(PointerInfo, _super);
  16058. function PointerInfo(type, event, pickInfo) {
  16059. _super.call(this, type, event);
  16060. this.pickInfo = pickInfo;
  16061. }
  16062. return PointerInfo;
  16063. }(PointerInfoBase));
  16064. BABYLON.PointerInfo = PointerInfo;
  16065. /**
  16066. * Represents a scene to be rendered by the engine.
  16067. * @see http://doc.babylonjs.com/page.php?p=21911
  16068. */
  16069. var Scene = (function () {
  16070. /**
  16071. * @constructor
  16072. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16073. */
  16074. function Scene(engine) {
  16075. // Members
  16076. this.autoClear = true;
  16077. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16078. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16079. this.forceWireframe = false;
  16080. this.forcePointsCloud = false;
  16081. this.forceShowBoundingBoxes = false;
  16082. this.animationsEnabled = true;
  16083. this.constantlyUpdateMeshUnderPointer = false;
  16084. this.useRightHandedSystem = false;
  16085. this.hoverCursor = "pointer";
  16086. // Events
  16087. /**
  16088. * An event triggered when the scene is disposed.
  16089. * @type {BABYLON.Observable}
  16090. */
  16091. this.onDisposeObservable = new BABYLON.Observable();
  16092. /**
  16093. * An event triggered before rendering the scene
  16094. * @type {BABYLON.Observable}
  16095. */
  16096. this.onBeforeRenderObservable = new BABYLON.Observable();
  16097. /**
  16098. * An event triggered after rendering the scene
  16099. * @type {BABYLON.Observable}
  16100. */
  16101. this.onAfterRenderObservable = new BABYLON.Observable();
  16102. /**
  16103. * An event triggered when the scene is ready
  16104. * @type {BABYLON.Observable}
  16105. */
  16106. this.onReadyObservable = new BABYLON.Observable();
  16107. /**
  16108. * An event triggered before rendering a camera
  16109. * @type {BABYLON.Observable}
  16110. */
  16111. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16112. /**
  16113. * An event triggered after rendering a camera
  16114. * @type {BABYLON.Observable}
  16115. */
  16116. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16117. /**
  16118. * An event triggered when a camera is created
  16119. * @type {BABYLON.Observable}
  16120. */
  16121. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16122. /**
  16123. * An event triggered when a camera is removed
  16124. * @type {BABYLON.Observable}
  16125. */
  16126. this.onCameraRemovedObservable = new BABYLON.Observable();
  16127. /**
  16128. * An event triggered when a light is created
  16129. * @type {BABYLON.Observable}
  16130. */
  16131. this.onNewLightAddedObservable = new BABYLON.Observable();
  16132. /**
  16133. * An event triggered when a light is removed
  16134. * @type {BABYLON.Observable}
  16135. */
  16136. this.onLightRemovedObservable = new BABYLON.Observable();
  16137. /**
  16138. * An event triggered when a geometry is created
  16139. * @type {BABYLON.Observable}
  16140. */
  16141. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16142. /**
  16143. * An event triggered when a geometry is removed
  16144. * @type {BABYLON.Observable}
  16145. */
  16146. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16147. /**
  16148. * An event triggered when a mesh is created
  16149. * @type {BABYLON.Observable}
  16150. */
  16151. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16152. /**
  16153. * An event triggered when a mesh is removed
  16154. * @type {BABYLON.Observable}
  16155. */
  16156. this.onMeshRemovedObservable = new BABYLON.Observable();
  16157. // Animations
  16158. this.animations = [];
  16159. /**
  16160. * 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).
  16161. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16162. */
  16163. this.onPrePointerObservable = new BABYLON.Observable();
  16164. /**
  16165. * Observable event triggered each time an input event is received from the rendering canvas
  16166. */
  16167. this.onPointerObservable = new BABYLON.Observable();
  16168. 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
  16169. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16170. this._startingPointerTime = 0;
  16171. // Fog
  16172. /**
  16173. * is fog enabled on this scene.
  16174. * @type {boolean}
  16175. */
  16176. this.fogEnabled = true;
  16177. this.fogMode = Scene.FOGMODE_NONE;
  16178. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16179. this.fogDensity = 0.1;
  16180. this.fogStart = 0;
  16181. this.fogEnd = 1000.0;
  16182. // Lights
  16183. /**
  16184. * is shadow enabled on this scene.
  16185. * @type {boolean}
  16186. */
  16187. this.shadowsEnabled = true;
  16188. /**
  16189. * is light enabled on this scene.
  16190. * @type {boolean}
  16191. */
  16192. this.lightsEnabled = true;
  16193. /**
  16194. * All of the lights added to this scene.
  16195. * @see BABYLON.Light
  16196. * @type {BABYLON.Light[]}
  16197. */
  16198. this.lights = new Array();
  16199. // Cameras
  16200. /**
  16201. * All of the cameras added to this scene.
  16202. * @see BABYLON.Camera
  16203. * @type {BABYLON.Camera[]}
  16204. */
  16205. this.cameras = new Array();
  16206. this.activeCameras = new Array();
  16207. // Meshes
  16208. /**
  16209. * All of the (abstract) meshes added to this scene.
  16210. * @see BABYLON.AbstractMesh
  16211. * @type {BABYLON.AbstractMesh[]}
  16212. */
  16213. this.meshes = new Array();
  16214. // Geometries
  16215. this._geometries = new Array();
  16216. this.materials = new Array();
  16217. this.multiMaterials = new Array();
  16218. // Textures
  16219. this.texturesEnabled = true;
  16220. this.textures = new Array();
  16221. // Particles
  16222. this.particlesEnabled = true;
  16223. this.particleSystems = new Array();
  16224. // Sprites
  16225. this.spritesEnabled = true;
  16226. this.spriteManagers = new Array();
  16227. // Layers
  16228. this.layers = new Array();
  16229. this.highlightLayers = new Array();
  16230. // Skeletons
  16231. this.skeletonsEnabled = true;
  16232. this.skeletons = new Array();
  16233. // Lens flares
  16234. this.lensFlaresEnabled = true;
  16235. this.lensFlareSystems = new Array();
  16236. // Collisions
  16237. this.collisionsEnabled = true;
  16238. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16239. // Postprocesses
  16240. this.postProcessesEnabled = true;
  16241. // Customs render targets
  16242. this.renderTargetsEnabled = true;
  16243. this.dumpNextRenderTargets = false;
  16244. this.customRenderTargets = new Array();
  16245. // Imported meshes
  16246. this.importedMeshesFiles = new Array();
  16247. // Probes
  16248. this.probesEnabled = true;
  16249. this.reflectionProbes = new Array();
  16250. this._actionManagers = new Array();
  16251. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16252. // Procedural textures
  16253. this.proceduralTexturesEnabled = true;
  16254. this._proceduralTextures = new Array();
  16255. this.soundTracks = new Array();
  16256. this._audioEnabled = true;
  16257. this._headphone = false;
  16258. // Performance counters
  16259. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16260. this._totalLightsCounter = new BABYLON.PerfCounter();
  16261. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16262. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16263. this._totalVertices = new BABYLON.PerfCounter();
  16264. this._activeIndices = new BABYLON.PerfCounter();
  16265. this._activeParticles = new BABYLON.PerfCounter();
  16266. this._lastFrameDuration = new BABYLON.PerfCounter();
  16267. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16268. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16269. this._particlesDuration = new BABYLON.PerfCounter();
  16270. this._renderDuration = new BABYLON.PerfCounter();
  16271. this._spritesDuration = new BABYLON.PerfCounter();
  16272. this._activeBones = new BABYLON.PerfCounter();
  16273. this._renderId = 0;
  16274. this._executeWhenReadyTimeoutId = -1;
  16275. this._intermediateRendering = false;
  16276. this._toBeDisposed = new BABYLON.SmartArray(256);
  16277. this._pendingData = []; //ANY
  16278. this._activeMeshes = new BABYLON.SmartArray(256);
  16279. this._processedMaterials = new BABYLON.SmartArray(256);
  16280. this._renderTargets = new BABYLON.SmartArray(256);
  16281. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16282. this._activeSkeletons = new BABYLON.SmartArray(32);
  16283. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16284. this._activeAnimatables = new Array();
  16285. this._transformMatrix = BABYLON.Matrix.Zero();
  16286. this._edgesRenderers = new BABYLON.SmartArray(16);
  16287. this._uniqueIdCounter = 0;
  16288. this._engine = engine;
  16289. engine.scenes.push(this);
  16290. this._renderingManager = new BABYLON.RenderingManager(this);
  16291. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16292. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16293. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16294. if (BABYLON.OutlineRenderer) {
  16295. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16296. }
  16297. this.attachControl();
  16298. if (BABYLON.SoundTrack) {
  16299. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16300. }
  16301. //simplification queue
  16302. if (BABYLON.SimplificationQueue) {
  16303. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16304. }
  16305. //collision coordinator initialization. For now legacy per default.
  16306. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16307. }
  16308. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16309. get: function () {
  16310. return Scene._FOGMODE_NONE;
  16311. },
  16312. enumerable: true,
  16313. configurable: true
  16314. });
  16315. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16316. get: function () {
  16317. return Scene._FOGMODE_EXP;
  16318. },
  16319. enumerable: true,
  16320. configurable: true
  16321. });
  16322. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16323. get: function () {
  16324. return Scene._FOGMODE_EXP2;
  16325. },
  16326. enumerable: true,
  16327. configurable: true
  16328. });
  16329. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16330. get: function () {
  16331. return Scene._FOGMODE_LINEAR;
  16332. },
  16333. enumerable: true,
  16334. configurable: true
  16335. });
  16336. Object.defineProperty(Scene.prototype, "onDispose", {
  16337. set: function (callback) {
  16338. if (this._onDisposeObserver) {
  16339. this.onDisposeObservable.remove(this._onDisposeObserver);
  16340. }
  16341. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16342. },
  16343. enumerable: true,
  16344. configurable: true
  16345. });
  16346. Object.defineProperty(Scene.prototype, "beforeRender", {
  16347. set: function (callback) {
  16348. if (this._onBeforeRenderObserver) {
  16349. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16350. }
  16351. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16352. },
  16353. enumerable: true,
  16354. configurable: true
  16355. });
  16356. Object.defineProperty(Scene.prototype, "afterRender", {
  16357. set: function (callback) {
  16358. if (this._onAfterRenderObserver) {
  16359. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16360. }
  16361. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16362. },
  16363. enumerable: true,
  16364. configurable: true
  16365. });
  16366. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16367. set: function (callback) {
  16368. if (this._onBeforeCameraRenderObserver) {
  16369. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16370. }
  16371. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16372. },
  16373. enumerable: true,
  16374. configurable: true
  16375. });
  16376. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16377. set: function (callback) {
  16378. if (this._onAfterCameraRenderObserver) {
  16379. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16380. }
  16381. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16382. },
  16383. enumerable: true,
  16384. configurable: true
  16385. });
  16386. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16387. get: function () {
  16388. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16389. },
  16390. enumerable: true,
  16391. configurable: true
  16392. });
  16393. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16394. get: function () {
  16395. if (!this._defaultMaterial) {
  16396. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16397. }
  16398. return this._defaultMaterial;
  16399. },
  16400. enumerable: true,
  16401. configurable: true
  16402. });
  16403. Object.defineProperty(Scene.prototype, "debugLayer", {
  16404. // Properties
  16405. get: function () {
  16406. if (!this._debugLayer) {
  16407. this._debugLayer = new BABYLON.DebugLayer(this);
  16408. }
  16409. return this._debugLayer;
  16410. },
  16411. enumerable: true,
  16412. configurable: true
  16413. });
  16414. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16415. get: function () {
  16416. return this._workerCollisions;
  16417. },
  16418. set: function (enabled) {
  16419. enabled = (enabled && !!Worker);
  16420. this._workerCollisions = enabled;
  16421. if (this.collisionCoordinator) {
  16422. this.collisionCoordinator.destroy();
  16423. }
  16424. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16425. this.collisionCoordinator.init(this);
  16426. },
  16427. enumerable: true,
  16428. configurable: true
  16429. });
  16430. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16431. get: function () {
  16432. return this._selectionOctree;
  16433. },
  16434. enumerable: true,
  16435. configurable: true
  16436. });
  16437. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16438. /**
  16439. * The mesh that is currently under the pointer.
  16440. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16441. */
  16442. get: function () {
  16443. return this._pointerOverMesh;
  16444. },
  16445. enumerable: true,
  16446. configurable: true
  16447. });
  16448. Object.defineProperty(Scene.prototype, "pointerX", {
  16449. /**
  16450. * Current on-screen X position of the pointer
  16451. * @return {number} X position of the pointer
  16452. */
  16453. get: function () {
  16454. return this._pointerX;
  16455. },
  16456. enumerable: true,
  16457. configurable: true
  16458. });
  16459. Object.defineProperty(Scene.prototype, "pointerY", {
  16460. /**
  16461. * Current on-screen Y position of the pointer
  16462. * @return {number} Y position of the pointer
  16463. */
  16464. get: function () {
  16465. return this._pointerY;
  16466. },
  16467. enumerable: true,
  16468. configurable: true
  16469. });
  16470. Scene.prototype.getCachedMaterial = function () {
  16471. return this._cachedMaterial;
  16472. };
  16473. Scene.prototype.getBoundingBoxRenderer = function () {
  16474. return this._boundingBoxRenderer;
  16475. };
  16476. Scene.prototype.getOutlineRenderer = function () {
  16477. return this._outlineRenderer;
  16478. };
  16479. Scene.prototype.getEngine = function () {
  16480. return this._engine;
  16481. };
  16482. Scene.prototype.getTotalVertices = function () {
  16483. return this._totalVertices.current;
  16484. };
  16485. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16486. get: function () {
  16487. return this._totalVertices;
  16488. },
  16489. enumerable: true,
  16490. configurable: true
  16491. });
  16492. Scene.prototype.getActiveIndices = function () {
  16493. return this._activeIndices.current;
  16494. };
  16495. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16496. get: function () {
  16497. return this._activeIndices;
  16498. },
  16499. enumerable: true,
  16500. configurable: true
  16501. });
  16502. Scene.prototype.getActiveParticles = function () {
  16503. return this._activeParticles.current;
  16504. };
  16505. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16506. get: function () {
  16507. return this._activeParticles;
  16508. },
  16509. enumerable: true,
  16510. configurable: true
  16511. });
  16512. Scene.prototype.getActiveBones = function () {
  16513. return this._activeBones.current;
  16514. };
  16515. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16516. get: function () {
  16517. return this._activeBones;
  16518. },
  16519. enumerable: true,
  16520. configurable: true
  16521. });
  16522. // Stats
  16523. Scene.prototype.getLastFrameDuration = function () {
  16524. return this._lastFrameDuration.current;
  16525. };
  16526. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16527. get: function () {
  16528. return this._lastFrameDuration;
  16529. },
  16530. enumerable: true,
  16531. configurable: true
  16532. });
  16533. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16534. return this._evaluateActiveMeshesDuration.current;
  16535. };
  16536. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16537. get: function () {
  16538. return this._evaluateActiveMeshesDuration;
  16539. },
  16540. enumerable: true,
  16541. configurable: true
  16542. });
  16543. Scene.prototype.getActiveMeshes = function () {
  16544. return this._activeMeshes;
  16545. };
  16546. Scene.prototype.getRenderTargetsDuration = function () {
  16547. return this._renderTargetsDuration.current;
  16548. };
  16549. Scene.prototype.getRenderDuration = function () {
  16550. return this._renderDuration.current;
  16551. };
  16552. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16553. get: function () {
  16554. return this._renderDuration;
  16555. },
  16556. enumerable: true,
  16557. configurable: true
  16558. });
  16559. Scene.prototype.getParticlesDuration = function () {
  16560. return this._particlesDuration.current;
  16561. };
  16562. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16563. get: function () {
  16564. return this._particlesDuration;
  16565. },
  16566. enumerable: true,
  16567. configurable: true
  16568. });
  16569. Scene.prototype.getSpritesDuration = function () {
  16570. return this._spritesDuration.current;
  16571. };
  16572. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16573. get: function () {
  16574. return this._spritesDuration;
  16575. },
  16576. enumerable: true,
  16577. configurable: true
  16578. });
  16579. Scene.prototype.getAnimationRatio = function () {
  16580. return this._animationRatio;
  16581. };
  16582. Scene.prototype.getRenderId = function () {
  16583. return this._renderId;
  16584. };
  16585. Scene.prototype.incrementRenderId = function () {
  16586. this._renderId++;
  16587. };
  16588. Scene.prototype._updatePointerPosition = function (evt) {
  16589. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16590. this._pointerX = evt.clientX - canvasRect.left;
  16591. this._pointerY = evt.clientY - canvasRect.top;
  16592. this._unTranslatedPointerX = this._pointerX;
  16593. this._unTranslatedPointerY = this._pointerY;
  16594. if (this.cameraToUseForPointers) {
  16595. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16596. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16597. }
  16598. };
  16599. // Pointers handling
  16600. /**
  16601. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16602. * @param attachUp defines if you want to attach events to pointerup
  16603. * @param attachDown defines if you want to attach events to pointerdown
  16604. * @param attachMove defines if you want to attach events to pointermove
  16605. */
  16606. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16607. var _this = this;
  16608. if (attachUp === void 0) { attachUp = true; }
  16609. if (attachDown === void 0) { attachDown = true; }
  16610. if (attachMove === void 0) { attachMove = true; }
  16611. var spritePredicate = function (sprite) {
  16612. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16613. };
  16614. this._onPointerMove = function (evt) {
  16615. _this._updatePointerPosition(evt);
  16616. // PreObservable support
  16617. if (_this.onPrePointerObservable.hasObservers()) {
  16618. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16619. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16620. _this.onPrePointerObservable.notifyObservers(pi, type);
  16621. if (pi.skipOnPointerObservable) {
  16622. return;
  16623. }
  16624. }
  16625. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16626. return;
  16627. }
  16628. var canvas = _this._engine.getRenderingCanvas();
  16629. if (!_this.pointerMovePredicate) {
  16630. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16631. }
  16632. // Meshes
  16633. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16634. if (pickResult.hit && pickResult.pickedMesh) {
  16635. _this.setPointerOverSprite(null);
  16636. _this.setPointerOverMesh(pickResult.pickedMesh);
  16637. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16638. canvas.style.cursor = _this.hoverCursor;
  16639. }
  16640. else {
  16641. canvas.style.cursor = "";
  16642. }
  16643. }
  16644. else {
  16645. _this.setPointerOverMesh(null);
  16646. // Sprites
  16647. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16648. if (pickResult.hit && pickResult.pickedSprite) {
  16649. canvas.style.cursor = _this.hoverCursor;
  16650. _this.setPointerOverSprite(pickResult.pickedSprite);
  16651. }
  16652. else {
  16653. _this.setPointerOverSprite(null);
  16654. // Restore pointer
  16655. canvas.style.cursor = "";
  16656. }
  16657. }
  16658. if (_this.onPointerMove) {
  16659. _this.onPointerMove(evt, pickResult);
  16660. }
  16661. if (_this.onPointerObservable.hasObservers()) {
  16662. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16663. var pi = new PointerInfo(type, evt, pickResult);
  16664. _this.onPointerObservable.notifyObservers(pi, type);
  16665. }
  16666. };
  16667. this._onPointerDown = function (evt) {
  16668. _this._updatePointerPosition(evt);
  16669. // PreObservable support
  16670. if (_this.onPrePointerObservable.hasObservers()) {
  16671. var type = PointerEventTypes.POINTERDOWN;
  16672. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16673. _this.onPrePointerObservable.notifyObservers(pi, type);
  16674. if (pi.skipOnPointerObservable) {
  16675. return;
  16676. }
  16677. }
  16678. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16679. return;
  16680. }
  16681. _this._startingPointerPosition.x = _this._pointerX;
  16682. _this._startingPointerPosition.y = _this._pointerY;
  16683. _this._startingPointerTime = new Date().getTime();
  16684. if (!_this.pointerDownPredicate) {
  16685. _this.pointerDownPredicate = function (mesh) {
  16686. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16687. };
  16688. }
  16689. // Meshes
  16690. _this._pickedDownMesh = null;
  16691. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16692. if (pickResult.hit && pickResult.pickedMesh) {
  16693. if (pickResult.pickedMesh.actionManager) {
  16694. _this._pickedDownMesh = pickResult.pickedMesh;
  16695. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16696. switch (evt.button) {
  16697. case 0:
  16698. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16699. break;
  16700. case 1:
  16701. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16702. break;
  16703. case 2:
  16704. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16705. break;
  16706. }
  16707. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16708. }
  16709. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16710. var that = _this;
  16711. window.setTimeout(function () {
  16712. 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);
  16713. if (pickResult.hit && pickResult.pickedMesh) {
  16714. if (pickResult.pickedMesh.actionManager) {
  16715. 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)) {
  16716. that._startingPointerTime = 0;
  16717. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16718. }
  16719. }
  16720. }
  16721. }, BABYLON.ActionManager.LongPressDelay);
  16722. }
  16723. }
  16724. }
  16725. if (_this.onPointerDown) {
  16726. _this.onPointerDown(evt, pickResult);
  16727. }
  16728. if (_this.onPointerObservable.hasObservers()) {
  16729. var type = PointerEventTypes.POINTERDOWN;
  16730. var pi = new PointerInfo(type, evt, pickResult);
  16731. _this.onPointerObservable.notifyObservers(pi, type);
  16732. }
  16733. // Sprites
  16734. _this._pickedDownSprite = null;
  16735. if (_this.spriteManagers.length > 0) {
  16736. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16737. if (pickResult.hit && pickResult.pickedSprite) {
  16738. if (pickResult.pickedSprite.actionManager) {
  16739. _this._pickedDownSprite = pickResult.pickedSprite;
  16740. switch (evt.button) {
  16741. case 0:
  16742. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16743. break;
  16744. case 1:
  16745. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16746. break;
  16747. case 2:
  16748. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16749. break;
  16750. }
  16751. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16752. }
  16753. }
  16754. }
  16755. };
  16756. this._onPointerUp = function (evt) {
  16757. _this._updatePointerPosition(evt);
  16758. // PreObservable support
  16759. if (_this.onPrePointerObservable.hasObservers()) {
  16760. var type = PointerEventTypes.POINTERUP;
  16761. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16762. _this.onPrePointerObservable.notifyObservers(pi, type);
  16763. if (pi.skipOnPointerObservable) {
  16764. return;
  16765. }
  16766. }
  16767. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16768. return;
  16769. }
  16770. if (!_this.pointerUpPredicate) {
  16771. _this.pointerUpPredicate = function (mesh) {
  16772. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16773. };
  16774. }
  16775. // Meshes
  16776. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16777. if (pickResult.hit && pickResult.pickedMesh) {
  16778. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16779. if (_this.onPointerPick) {
  16780. _this.onPointerPick(evt, pickResult);
  16781. }
  16782. if (_this.onPointerObservable.hasObservers()) {
  16783. var type = PointerEventTypes.POINTERPICK;
  16784. var pi = new PointerInfo(type, evt, pickResult);
  16785. _this.onPointerObservable.notifyObservers(pi, type);
  16786. }
  16787. }
  16788. if (pickResult.pickedMesh.actionManager) {
  16789. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16790. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16791. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16792. }
  16793. }
  16794. }
  16795. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16796. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16797. }
  16798. if (_this.onPointerUp) {
  16799. _this.onPointerUp(evt, pickResult);
  16800. }
  16801. if (_this.onPointerObservable.hasObservers()) {
  16802. var type = PointerEventTypes.POINTERUP;
  16803. var pi = new PointerInfo(type, evt, pickResult);
  16804. _this.onPointerObservable.notifyObservers(pi, type);
  16805. }
  16806. _this._startingPointerTime = 0;
  16807. // Sprites
  16808. if (_this.spriteManagers.length > 0) {
  16809. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16810. if (pickResult.hit && pickResult.pickedSprite) {
  16811. if (pickResult.pickedSprite.actionManager) {
  16812. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16813. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16814. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16815. }
  16816. }
  16817. }
  16818. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16819. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16820. }
  16821. }
  16822. };
  16823. this._onKeyDown = function (evt) {
  16824. if (_this.actionManager) {
  16825. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16826. }
  16827. };
  16828. this._onKeyUp = function (evt) {
  16829. if (_this.actionManager) {
  16830. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16831. }
  16832. };
  16833. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16834. var canvas = this._engine.getRenderingCanvas();
  16835. if (attachMove) {
  16836. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16837. // Wheel
  16838. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16839. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16840. }
  16841. if (attachDown) {
  16842. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16843. }
  16844. if (attachUp) {
  16845. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16846. }
  16847. canvas.tabIndex = 1;
  16848. canvas.addEventListener("keydown", this._onKeyDown, false);
  16849. canvas.addEventListener("keyup", this._onKeyUp, false);
  16850. };
  16851. Scene.prototype.detachControl = function () {
  16852. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16853. var canvas = this._engine.getRenderingCanvas();
  16854. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16855. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16856. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16857. // Wheel
  16858. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16859. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16860. canvas.removeEventListener("keydown", this._onKeyDown);
  16861. canvas.removeEventListener("keyup", this._onKeyUp);
  16862. };
  16863. // Ready
  16864. Scene.prototype.isReady = function () {
  16865. if (this._pendingData.length > 0) {
  16866. return false;
  16867. }
  16868. var index;
  16869. for (index = 0; index < this._geometries.length; index++) {
  16870. var geometry = this._geometries[index];
  16871. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16872. return false;
  16873. }
  16874. }
  16875. for (index = 0; index < this.meshes.length; index++) {
  16876. var mesh = this.meshes[index];
  16877. if (!mesh.isReady()) {
  16878. return false;
  16879. }
  16880. var mat = mesh.material;
  16881. if (mat) {
  16882. if (!mat.isReady(mesh)) {
  16883. return false;
  16884. }
  16885. }
  16886. }
  16887. return true;
  16888. };
  16889. Scene.prototype.resetCachedMaterial = function () {
  16890. this._cachedMaterial = null;
  16891. };
  16892. Scene.prototype.registerBeforeRender = function (func) {
  16893. this.onBeforeRenderObservable.add(func);
  16894. };
  16895. Scene.prototype.unregisterBeforeRender = function (func) {
  16896. this.onBeforeRenderObservable.removeCallback(func);
  16897. };
  16898. Scene.prototype.registerAfterRender = function (func) {
  16899. this.onAfterRenderObservable.add(func);
  16900. };
  16901. Scene.prototype.unregisterAfterRender = function (func) {
  16902. this.onAfterRenderObservable.removeCallback(func);
  16903. };
  16904. Scene.prototype._addPendingData = function (data) {
  16905. this._pendingData.push(data);
  16906. };
  16907. Scene.prototype._removePendingData = function (data) {
  16908. var index = this._pendingData.indexOf(data);
  16909. if (index !== -1) {
  16910. this._pendingData.splice(index, 1);
  16911. }
  16912. };
  16913. Scene.prototype.getWaitingItemsCount = function () {
  16914. return this._pendingData.length;
  16915. };
  16916. /**
  16917. * Registers a function to be executed when the scene is ready.
  16918. * @param {Function} func - the function to be executed.
  16919. */
  16920. Scene.prototype.executeWhenReady = function (func) {
  16921. var _this = this;
  16922. this.onReadyObservable.add(func);
  16923. if (this._executeWhenReadyTimeoutId !== -1) {
  16924. return;
  16925. }
  16926. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16927. _this._checkIsReady();
  16928. }, 150);
  16929. };
  16930. Scene.prototype._checkIsReady = function () {
  16931. var _this = this;
  16932. if (this.isReady()) {
  16933. this.onReadyObservable.notifyObservers(this);
  16934. this.onReadyObservable.clear();
  16935. this._executeWhenReadyTimeoutId = -1;
  16936. return;
  16937. }
  16938. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16939. _this._checkIsReady();
  16940. }, 150);
  16941. };
  16942. // Animations
  16943. /**
  16944. * Will start the animation sequence of a given target
  16945. * @param target - the target
  16946. * @param {number} from - from which frame should animation start
  16947. * @param {number} to - till which frame should animation run.
  16948. * @param {boolean} [loop] - should the animation loop
  16949. * @param {number} [speedRatio] - the speed in which to run the animation
  16950. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16951. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16952. * @return {BABYLON.Animatable} the animatable object created for this animation
  16953. * @see BABYLON.Animatable
  16954. * @see http://doc.babylonjs.com/page.php?p=22081
  16955. */
  16956. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16957. if (speedRatio === void 0) { speedRatio = 1.0; }
  16958. this.stopAnimation(target);
  16959. if (!animatable) {
  16960. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16961. }
  16962. // Local animations
  16963. if (target.animations) {
  16964. animatable.appendAnimations(target, target.animations);
  16965. }
  16966. // Children animations
  16967. if (target.getAnimatables) {
  16968. var animatables = target.getAnimatables();
  16969. for (var index = 0; index < animatables.length; index++) {
  16970. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16971. }
  16972. }
  16973. animatable.reset();
  16974. return animatable;
  16975. };
  16976. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16977. if (speedRatio === undefined) {
  16978. speedRatio = 1.0;
  16979. }
  16980. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16981. return animatable;
  16982. };
  16983. Scene.prototype.getAnimatableByTarget = function (target) {
  16984. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16985. if (this._activeAnimatables[index].target === target) {
  16986. return this._activeAnimatables[index];
  16987. }
  16988. }
  16989. return null;
  16990. };
  16991. Object.defineProperty(Scene.prototype, "Animatables", {
  16992. get: function () {
  16993. return this._activeAnimatables;
  16994. },
  16995. enumerable: true,
  16996. configurable: true
  16997. });
  16998. /**
  16999. * Will stop the animation of the given target
  17000. * @param target - the target
  17001. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17002. * @see beginAnimation
  17003. */
  17004. Scene.prototype.stopAnimation = function (target, animationName) {
  17005. var animatable = this.getAnimatableByTarget(target);
  17006. if (animatable) {
  17007. animatable.stop(animationName);
  17008. }
  17009. };
  17010. Scene.prototype._animate = function () {
  17011. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17012. return;
  17013. }
  17014. if (!this._animationStartDate) {
  17015. if (this._pendingData.length > 0) {
  17016. return;
  17017. }
  17018. this._animationStartDate = BABYLON.Tools.Now;
  17019. }
  17020. // Getting time
  17021. var now = BABYLON.Tools.Now;
  17022. var delay = now - this._animationStartDate;
  17023. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17024. this._activeAnimatables[index]._animate(delay);
  17025. }
  17026. };
  17027. // Matrix
  17028. Scene.prototype.getViewMatrix = function () {
  17029. return this._viewMatrix;
  17030. };
  17031. Scene.prototype.getProjectionMatrix = function () {
  17032. return this._projectionMatrix;
  17033. };
  17034. Scene.prototype.getTransformMatrix = function () {
  17035. return this._transformMatrix;
  17036. };
  17037. Scene.prototype.setTransformMatrix = function (view, projection) {
  17038. this._viewMatrix = view;
  17039. this._projectionMatrix = projection;
  17040. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17041. // Update frustum
  17042. if (!this._frustumPlanes) {
  17043. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17044. }
  17045. else {
  17046. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17047. }
  17048. };
  17049. // Methods
  17050. Scene.prototype.addMesh = function (newMesh) {
  17051. newMesh.uniqueId = this._uniqueIdCounter++;
  17052. var position = this.meshes.push(newMesh);
  17053. //notify the collision coordinator
  17054. this.collisionCoordinator.onMeshAdded(newMesh);
  17055. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17056. };
  17057. Scene.prototype.removeMesh = function (toRemove) {
  17058. var index = this.meshes.indexOf(toRemove);
  17059. if (index !== -1) {
  17060. // Remove from the scene if mesh found
  17061. this.meshes.splice(index, 1);
  17062. }
  17063. //notify the collision coordinator
  17064. this.collisionCoordinator.onMeshRemoved(toRemove);
  17065. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17066. return index;
  17067. };
  17068. Scene.prototype.removeSkeleton = function (toRemove) {
  17069. var index = this.skeletons.indexOf(toRemove);
  17070. if (index !== -1) {
  17071. // Remove from the scene if mesh found
  17072. this.skeletons.splice(index, 1);
  17073. }
  17074. return index;
  17075. };
  17076. Scene.prototype.removeLight = function (toRemove) {
  17077. var index = this.lights.indexOf(toRemove);
  17078. if (index !== -1) {
  17079. // Remove from the scene if mesh found
  17080. this.lights.splice(index, 1);
  17081. }
  17082. this.onLightRemovedObservable.notifyObservers(toRemove);
  17083. return index;
  17084. };
  17085. Scene.prototype.removeCamera = function (toRemove) {
  17086. var index = this.cameras.indexOf(toRemove);
  17087. if (index !== -1) {
  17088. // Remove from the scene if mesh found
  17089. this.cameras.splice(index, 1);
  17090. }
  17091. // Remove from activeCameras
  17092. var index2 = this.activeCameras.indexOf(toRemove);
  17093. if (index2 !== -1) {
  17094. // Remove from the scene if mesh found
  17095. this.activeCameras.splice(index2, 1);
  17096. }
  17097. // Reset the activeCamera
  17098. if (this.activeCamera === toRemove) {
  17099. if (this.cameras.length > 0) {
  17100. this.activeCamera = this.cameras[0];
  17101. }
  17102. else {
  17103. this.activeCamera = null;
  17104. }
  17105. }
  17106. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17107. return index;
  17108. };
  17109. Scene.prototype.addLight = function (newLight) {
  17110. newLight.uniqueId = this._uniqueIdCounter++;
  17111. var position = this.lights.push(newLight);
  17112. this.onNewLightAddedObservable.notifyObservers(newLight);
  17113. };
  17114. Scene.prototype.addCamera = function (newCamera) {
  17115. newCamera.uniqueId = this._uniqueIdCounter++;
  17116. var position = this.cameras.push(newCamera);
  17117. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17118. };
  17119. /**
  17120. * Switch active camera
  17121. * @param {Camera} newCamera - new active camera
  17122. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17123. */
  17124. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17125. if (attachControl === void 0) { attachControl = true; }
  17126. var canvas = this._engine.getRenderingCanvas();
  17127. this.activeCamera.detachControl(canvas);
  17128. this.activeCamera = newCamera;
  17129. if (attachControl) {
  17130. newCamera.attachControl(canvas);
  17131. }
  17132. };
  17133. /**
  17134. * sets the active camera of the scene using its ID
  17135. * @param {string} id - the camera's ID
  17136. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17137. * @see activeCamera
  17138. */
  17139. Scene.prototype.setActiveCameraByID = function (id) {
  17140. var camera = this.getCameraByID(id);
  17141. if (camera) {
  17142. this.activeCamera = camera;
  17143. return camera;
  17144. }
  17145. return null;
  17146. };
  17147. /**
  17148. * sets the active camera of the scene using its name
  17149. * @param {string} name - the camera's name
  17150. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17151. * @see activeCamera
  17152. */
  17153. Scene.prototype.setActiveCameraByName = function (name) {
  17154. var camera = this.getCameraByName(name);
  17155. if (camera) {
  17156. this.activeCamera = camera;
  17157. return camera;
  17158. }
  17159. return null;
  17160. };
  17161. /**
  17162. * get a material using its id
  17163. * @param {string} the material's ID
  17164. * @return {BABYLON.Material|null} the material or null if none found.
  17165. */
  17166. Scene.prototype.getMaterialByID = function (id) {
  17167. for (var index = 0; index < this.materials.length; index++) {
  17168. if (this.materials[index].id === id) {
  17169. return this.materials[index];
  17170. }
  17171. }
  17172. return null;
  17173. };
  17174. /**
  17175. * get a material using its name
  17176. * @param {string} the material's name
  17177. * @return {BABYLON.Material|null} the material or null if none found.
  17178. */
  17179. Scene.prototype.getMaterialByName = function (name) {
  17180. for (var index = 0; index < this.materials.length; index++) {
  17181. if (this.materials[index].name === name) {
  17182. return this.materials[index];
  17183. }
  17184. }
  17185. return null;
  17186. };
  17187. Scene.prototype.getLensFlareSystemByName = function (name) {
  17188. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17189. if (this.lensFlareSystems[index].name === name) {
  17190. return this.lensFlareSystems[index];
  17191. }
  17192. }
  17193. return null;
  17194. };
  17195. Scene.prototype.getLensFlareSystemByID = function (id) {
  17196. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17197. if (this.lensFlareSystems[index].id === id) {
  17198. return this.lensFlareSystems[index];
  17199. }
  17200. }
  17201. return null;
  17202. };
  17203. Scene.prototype.getCameraByID = function (id) {
  17204. for (var index = 0; index < this.cameras.length; index++) {
  17205. if (this.cameras[index].id === id) {
  17206. return this.cameras[index];
  17207. }
  17208. }
  17209. return null;
  17210. };
  17211. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17212. for (var index = 0; index < this.cameras.length; index++) {
  17213. if (this.cameras[index].uniqueId === uniqueId) {
  17214. return this.cameras[index];
  17215. }
  17216. }
  17217. return null;
  17218. };
  17219. /**
  17220. * get a camera using its name
  17221. * @param {string} the camera's name
  17222. * @return {BABYLON.Camera|null} the camera or null if none found.
  17223. */
  17224. Scene.prototype.getCameraByName = function (name) {
  17225. for (var index = 0; index < this.cameras.length; index++) {
  17226. if (this.cameras[index].name === name) {
  17227. return this.cameras[index];
  17228. }
  17229. }
  17230. return null;
  17231. };
  17232. /**
  17233. * get a bone using its id
  17234. * @param {string} the bone's id
  17235. * @return {BABYLON.Bone|null} the bone or null if not found
  17236. */
  17237. Scene.prototype.getBoneByID = function (id) {
  17238. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17239. var skeleton = this.skeletons[skeletonIndex];
  17240. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17241. if (skeleton.bones[boneIndex].id === id) {
  17242. return skeleton.bones[boneIndex];
  17243. }
  17244. }
  17245. }
  17246. return null;
  17247. };
  17248. /**
  17249. * get a bone using its id
  17250. * @param {string} the bone's name
  17251. * @return {BABYLON.Bone|null} the bone or null if not found
  17252. */
  17253. Scene.prototype.getBoneByName = function (name) {
  17254. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17255. var skeleton = this.skeletons[skeletonIndex];
  17256. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17257. if (skeleton.bones[boneIndex].name === name) {
  17258. return skeleton.bones[boneIndex];
  17259. }
  17260. }
  17261. }
  17262. return null;
  17263. };
  17264. /**
  17265. * get a light node using its name
  17266. * @param {string} the light's name
  17267. * @return {BABYLON.Light|null} the light or null if none found.
  17268. */
  17269. Scene.prototype.getLightByName = function (name) {
  17270. for (var index = 0; index < this.lights.length; index++) {
  17271. if (this.lights[index].name === name) {
  17272. return this.lights[index];
  17273. }
  17274. }
  17275. return null;
  17276. };
  17277. /**
  17278. * get a light node using its ID
  17279. * @param {string} the light's id
  17280. * @return {BABYLON.Light|null} the light or null if none found.
  17281. */
  17282. Scene.prototype.getLightByID = function (id) {
  17283. for (var index = 0; index < this.lights.length; index++) {
  17284. if (this.lights[index].id === id) {
  17285. return this.lights[index];
  17286. }
  17287. }
  17288. return null;
  17289. };
  17290. /**
  17291. * get a light node using its scene-generated unique ID
  17292. * @param {number} the light's unique id
  17293. * @return {BABYLON.Light|null} the light or null if none found.
  17294. */
  17295. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17296. for (var index = 0; index < this.lights.length; index++) {
  17297. if (this.lights[index].uniqueId === uniqueId) {
  17298. return this.lights[index];
  17299. }
  17300. }
  17301. return null;
  17302. };
  17303. /**
  17304. * get a particle system by id
  17305. * @param id {number} the particle system id
  17306. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17307. */
  17308. Scene.prototype.getParticleSystemByID = function (id) {
  17309. for (var index = 0; index < this.particleSystems.length; index++) {
  17310. if (this.particleSystems[index].id === id) {
  17311. return this.particleSystems[index];
  17312. }
  17313. }
  17314. return null;
  17315. };
  17316. /**
  17317. * get a geometry using its ID
  17318. * @param {string} the geometry's id
  17319. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17320. */
  17321. Scene.prototype.getGeometryByID = function (id) {
  17322. for (var index = 0; index < this._geometries.length; index++) {
  17323. if (this._geometries[index].id === id) {
  17324. return this._geometries[index];
  17325. }
  17326. }
  17327. return null;
  17328. };
  17329. /**
  17330. * add a new geometry to this scene.
  17331. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17332. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17333. * @return {boolean} was the geometry added or not
  17334. */
  17335. Scene.prototype.pushGeometry = function (geometry, force) {
  17336. if (!force && this.getGeometryByID(geometry.id)) {
  17337. return false;
  17338. }
  17339. this._geometries.push(geometry);
  17340. //notify the collision coordinator
  17341. this.collisionCoordinator.onGeometryAdded(geometry);
  17342. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17343. return true;
  17344. };
  17345. /**
  17346. * Removes an existing geometry
  17347. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17348. * @return {boolean} was the geometry removed or not
  17349. */
  17350. Scene.prototype.removeGeometry = function (geometry) {
  17351. var index = this._geometries.indexOf(geometry);
  17352. if (index > -1) {
  17353. this._geometries.splice(index, 1);
  17354. //notify the collision coordinator
  17355. this.collisionCoordinator.onGeometryDeleted(geometry);
  17356. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17357. return true;
  17358. }
  17359. return false;
  17360. };
  17361. Scene.prototype.getGeometries = function () {
  17362. return this._geometries;
  17363. };
  17364. /**
  17365. * Get the first added mesh found of a given ID
  17366. * @param {string} id - the id to search for
  17367. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17368. */
  17369. Scene.prototype.getMeshByID = function (id) {
  17370. for (var index = 0; index < this.meshes.length; index++) {
  17371. if (this.meshes[index].id === id) {
  17372. return this.meshes[index];
  17373. }
  17374. }
  17375. return null;
  17376. };
  17377. Scene.prototype.getMeshesByID = function (id) {
  17378. return this.meshes.filter(function (m) {
  17379. return m.id === id;
  17380. });
  17381. };
  17382. /**
  17383. * Get a mesh with its auto-generated unique id
  17384. * @param {number} uniqueId - the unique id to search for
  17385. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17386. */
  17387. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17388. for (var index = 0; index < this.meshes.length; index++) {
  17389. if (this.meshes[index].uniqueId === uniqueId) {
  17390. return this.meshes[index];
  17391. }
  17392. }
  17393. return null;
  17394. };
  17395. /**
  17396. * Get a the last added mesh found of a given ID
  17397. * @param {string} id - the id to search for
  17398. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17399. */
  17400. Scene.prototype.getLastMeshByID = function (id) {
  17401. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17402. if (this.meshes[index].id === id) {
  17403. return this.meshes[index];
  17404. }
  17405. }
  17406. return null;
  17407. };
  17408. /**
  17409. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17410. * @param {string} id - the id to search for
  17411. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17412. */
  17413. Scene.prototype.getLastEntryByID = function (id) {
  17414. var index;
  17415. for (index = this.meshes.length - 1; index >= 0; index--) {
  17416. if (this.meshes[index].id === id) {
  17417. return this.meshes[index];
  17418. }
  17419. }
  17420. for (index = this.cameras.length - 1; index >= 0; index--) {
  17421. if (this.cameras[index].id === id) {
  17422. return this.cameras[index];
  17423. }
  17424. }
  17425. for (index = this.lights.length - 1; index >= 0; index--) {
  17426. if (this.lights[index].id === id) {
  17427. return this.lights[index];
  17428. }
  17429. }
  17430. return null;
  17431. };
  17432. Scene.prototype.getNodeByID = function (id) {
  17433. var mesh = this.getMeshByID(id);
  17434. if (mesh) {
  17435. return mesh;
  17436. }
  17437. var light = this.getLightByID(id);
  17438. if (light) {
  17439. return light;
  17440. }
  17441. var camera = this.getCameraByID(id);
  17442. if (camera) {
  17443. return camera;
  17444. }
  17445. var bone = this.getBoneByID(id);
  17446. return bone;
  17447. };
  17448. Scene.prototype.getNodeByName = function (name) {
  17449. var mesh = this.getMeshByName(name);
  17450. if (mesh) {
  17451. return mesh;
  17452. }
  17453. var light = this.getLightByName(name);
  17454. if (light) {
  17455. return light;
  17456. }
  17457. var camera = this.getCameraByName(name);
  17458. if (camera) {
  17459. return camera;
  17460. }
  17461. var bone = this.getBoneByName(name);
  17462. return bone;
  17463. };
  17464. Scene.prototype.getMeshByName = function (name) {
  17465. for (var index = 0; index < this.meshes.length; index++) {
  17466. if (this.meshes[index].name === name) {
  17467. return this.meshes[index];
  17468. }
  17469. }
  17470. return null;
  17471. };
  17472. Scene.prototype.getSoundByName = function (name) {
  17473. var index;
  17474. if (BABYLON.AudioEngine) {
  17475. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17476. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17477. return this.mainSoundTrack.soundCollection[index];
  17478. }
  17479. }
  17480. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17481. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17482. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17483. return this.soundTracks[sdIndex].soundCollection[index];
  17484. }
  17485. }
  17486. }
  17487. }
  17488. return null;
  17489. };
  17490. Scene.prototype.getLastSkeletonByID = function (id) {
  17491. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17492. if (this.skeletons[index].id === id) {
  17493. return this.skeletons[index];
  17494. }
  17495. }
  17496. return null;
  17497. };
  17498. Scene.prototype.getSkeletonById = function (id) {
  17499. for (var index = 0; index < this.skeletons.length; index++) {
  17500. if (this.skeletons[index].id === id) {
  17501. return this.skeletons[index];
  17502. }
  17503. }
  17504. return null;
  17505. };
  17506. Scene.prototype.getSkeletonByName = function (name) {
  17507. for (var index = 0; index < this.skeletons.length; index++) {
  17508. if (this.skeletons[index].name === name) {
  17509. return this.skeletons[index];
  17510. }
  17511. }
  17512. return null;
  17513. };
  17514. Scene.prototype.isActiveMesh = function (mesh) {
  17515. return (this._activeMeshes.indexOf(mesh) !== -1);
  17516. };
  17517. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17518. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17519. var material = subMesh.getMaterial();
  17520. if (mesh.showSubMeshesBoundingBox) {
  17521. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17522. }
  17523. if (material) {
  17524. // Render targets
  17525. if (material.getRenderTargetTextures) {
  17526. if (this._processedMaterials.indexOf(material) === -1) {
  17527. this._processedMaterials.push(material);
  17528. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17529. }
  17530. }
  17531. // Dispatch
  17532. this._activeIndices.addCount(subMesh.indexCount, false);
  17533. this._renderingManager.dispatch(subMesh);
  17534. }
  17535. }
  17536. };
  17537. Scene.prototype._isInIntermediateRendering = function () {
  17538. return this._intermediateRendering;
  17539. };
  17540. Scene.prototype._evaluateActiveMeshes = function () {
  17541. this.activeCamera._activeMeshes.reset();
  17542. this._activeMeshes.reset();
  17543. this._renderingManager.reset();
  17544. this._processedMaterials.reset();
  17545. this._activeParticleSystems.reset();
  17546. this._activeSkeletons.reset();
  17547. this._softwareSkinnedMeshes.reset();
  17548. this._boundingBoxRenderer.reset();
  17549. this._edgesRenderers.reset();
  17550. // Meshes
  17551. var meshes;
  17552. var len;
  17553. if (this._selectionOctree) {
  17554. var selection = this._selectionOctree.select(this._frustumPlanes);
  17555. meshes = selection.data;
  17556. len = selection.length;
  17557. }
  17558. else {
  17559. len = this.meshes.length;
  17560. meshes = this.meshes;
  17561. }
  17562. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17563. var mesh = meshes[meshIndex];
  17564. if (mesh.isBlocked) {
  17565. continue;
  17566. }
  17567. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17568. if (!mesh.isReady() || !mesh.isEnabled()) {
  17569. continue;
  17570. }
  17571. mesh.computeWorldMatrix();
  17572. // Intersections
  17573. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17574. this._meshesForIntersections.pushNoDuplicate(mesh);
  17575. }
  17576. // Switch to current LOD
  17577. var meshLOD = mesh.getLOD(this.activeCamera);
  17578. if (!meshLOD) {
  17579. continue;
  17580. }
  17581. mesh._preActivate();
  17582. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17583. this._activeMeshes.push(mesh);
  17584. this.activeCamera._activeMeshes.push(mesh);
  17585. mesh._activate(this._renderId);
  17586. this._activeMesh(mesh, meshLOD);
  17587. }
  17588. }
  17589. // Particle systems
  17590. this._particlesDuration.beginMonitoring();
  17591. var beforeParticlesDate = BABYLON.Tools.Now;
  17592. if (this.particlesEnabled) {
  17593. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17594. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17595. var particleSystem = this.particleSystems[particleIndex];
  17596. if (!particleSystem.isStarted()) {
  17597. continue;
  17598. }
  17599. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17600. this._activeParticleSystems.push(particleSystem);
  17601. particleSystem.animate();
  17602. }
  17603. }
  17604. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17605. }
  17606. this._particlesDuration.endMonitoring(false);
  17607. };
  17608. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17609. if (mesh.skeleton && this.skeletonsEnabled) {
  17610. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17611. mesh.skeleton.prepare();
  17612. }
  17613. if (!mesh.computeBonesUsingShaders) {
  17614. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17615. }
  17616. }
  17617. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17618. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17619. }
  17620. if (sourceMesh._edgesRenderer) {
  17621. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17622. }
  17623. if (mesh && mesh.subMeshes) {
  17624. // Submeshes Octrees
  17625. var len;
  17626. var subMeshes;
  17627. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17628. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17629. len = intersections.length;
  17630. subMeshes = intersections.data;
  17631. }
  17632. else {
  17633. subMeshes = mesh.subMeshes;
  17634. len = subMeshes.length;
  17635. }
  17636. for (var subIndex = 0; subIndex < len; subIndex++) {
  17637. var subMesh = subMeshes[subIndex];
  17638. this._evaluateSubMesh(subMesh, mesh);
  17639. }
  17640. }
  17641. };
  17642. Scene.prototype.updateTransformMatrix = function (force) {
  17643. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17644. };
  17645. Scene.prototype._renderForCamera = function (camera) {
  17646. var engine = this._engine;
  17647. var startTime = BABYLON.Tools.Now;
  17648. this.activeCamera = camera;
  17649. if (!this.activeCamera)
  17650. throw new Error("Active camera not set");
  17651. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17652. // Viewport
  17653. engine.setViewport(this.activeCamera.viewport);
  17654. // Camera
  17655. this.resetCachedMaterial();
  17656. this._renderId++;
  17657. this.updateTransformMatrix();
  17658. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17659. // Meshes
  17660. this._evaluateActiveMeshesDuration.beginMonitoring();
  17661. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17662. this._evaluateActiveMeshes();
  17663. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17664. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17665. // Software skinning
  17666. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17667. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17668. mesh.applySkeleton(mesh.skeleton);
  17669. }
  17670. // Render targets
  17671. this._renderTargetsDuration.beginMonitoring();
  17672. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17673. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17674. this._intermediateRendering = true;
  17675. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17676. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17677. var renderTarget = this._renderTargets.data[renderIndex];
  17678. if (renderTarget._shouldRender()) {
  17679. this._renderId++;
  17680. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17681. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17682. }
  17683. }
  17684. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17685. this._intermediateRendering = false;
  17686. this._renderId++;
  17687. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17688. }
  17689. this._renderTargetsDuration.endMonitoring(false);
  17690. // Prepare Frame
  17691. this.postProcessManager._prepareFrame();
  17692. this._renderDuration.beginMonitoring();
  17693. // Backgrounds
  17694. var layerIndex;
  17695. var layer;
  17696. if (this.layers.length) {
  17697. engine.setDepthBuffer(false);
  17698. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17699. layer = this.layers[layerIndex];
  17700. if (layer.isBackground) {
  17701. layer.render();
  17702. }
  17703. }
  17704. engine.setDepthBuffer(true);
  17705. }
  17706. // Render
  17707. BABYLON.Tools.StartPerformanceCounter("Main render");
  17708. // Activate HighlightLayer stencil
  17709. var stencilState = this._engine.getStencilBuffer();
  17710. var renderhighlights = false;
  17711. if (this.highlightLayers && this.highlightLayers.length > 0) {
  17712. for (var i = 0; i < this.highlightLayers.length; i++) {
  17713. var highlightLayer = this.highlightLayers[i];
  17714. if ((!highlightLayer.camera || camera == highlightLayer.camera) && highlightLayer.shouldRender()) {
  17715. renderhighlights = true;
  17716. this._engine.setStencilBuffer(true);
  17717. break;
  17718. }
  17719. }
  17720. }
  17721. this._renderingManager.render(null, null, true, true);
  17722. // Restore HighlightLayer stencil
  17723. if (renderhighlights) {
  17724. this._engine.setStencilBuffer(stencilState);
  17725. }
  17726. BABYLON.Tools.EndPerformanceCounter("Main render");
  17727. // Bounding boxes
  17728. this._boundingBoxRenderer.render();
  17729. // Edges
  17730. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17731. this._edgesRenderers.data[edgesRendererIndex].render();
  17732. }
  17733. // Lens flares
  17734. if (this.lensFlaresEnabled) {
  17735. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17736. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17737. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17738. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17739. lensFlareSystem.render();
  17740. }
  17741. }
  17742. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17743. }
  17744. // Foregrounds
  17745. if (this.layers.length) {
  17746. engine.setDepthBuffer(false);
  17747. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17748. layer = this.layers[layerIndex];
  17749. if (!layer.isBackground) {
  17750. layer.render();
  17751. }
  17752. }
  17753. engine.setDepthBuffer(true);
  17754. }
  17755. // Highlight Layer
  17756. if (renderhighlights) {
  17757. engine.setDepthBuffer(false);
  17758. for (var i = 0; i < this.highlightLayers.length; i++) {
  17759. if (this.highlightLayers[i].shouldRender()) {
  17760. this.highlightLayers[i].render();
  17761. }
  17762. }
  17763. engine.setDepthBuffer(true);
  17764. }
  17765. this._renderDuration.endMonitoring(false);
  17766. // Finalize frame
  17767. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17768. // Update camera
  17769. this.activeCamera._updateFromScene();
  17770. // Reset some special arrays
  17771. this._renderTargets.reset();
  17772. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17773. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17774. };
  17775. Scene.prototype._processSubCameras = function (camera) {
  17776. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17777. this._renderForCamera(camera);
  17778. return;
  17779. }
  17780. // rig cameras
  17781. for (var index = 0; index < camera._rigCameras.length; index++) {
  17782. this._renderForCamera(camera._rigCameras[index]);
  17783. }
  17784. this.activeCamera = camera;
  17785. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17786. // Update camera
  17787. this.activeCamera._updateFromScene();
  17788. };
  17789. Scene.prototype._checkIntersections = function () {
  17790. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17791. var sourceMesh = this._meshesForIntersections.data[index];
  17792. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17793. var action = sourceMesh.actionManager.actions[actionIndex];
  17794. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17795. var parameters = action.getTriggerParameter();
  17796. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17797. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17798. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17799. if (areIntersecting && currentIntersectionInProgress === -1) {
  17800. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17801. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17802. sourceMesh._intersectionsInProgress.push(otherMesh);
  17803. }
  17804. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17805. sourceMesh._intersectionsInProgress.push(otherMesh);
  17806. }
  17807. }
  17808. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17809. //They intersected, and now they don't.
  17810. //is this trigger an exit trigger? execute an event.
  17811. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17812. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17813. }
  17814. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17815. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17816. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17817. }
  17818. }
  17819. }
  17820. }
  17821. }
  17822. };
  17823. Scene.prototype.render = function () {
  17824. this._lastFrameDuration.beginMonitoring();
  17825. this._particlesDuration.fetchNewFrame();
  17826. this._spritesDuration.fetchNewFrame();
  17827. this._activeParticles.fetchNewFrame();
  17828. this._renderDuration.fetchNewFrame();
  17829. this._renderTargetsDuration.fetchNewFrame();
  17830. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17831. this._totalVertices.fetchNewFrame();
  17832. this._activeIndices.fetchNewFrame();
  17833. this._activeBones.fetchNewFrame();
  17834. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17835. this._meshesForIntersections.reset();
  17836. this.resetCachedMaterial();
  17837. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17838. // Actions
  17839. if (this.actionManager) {
  17840. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17841. }
  17842. //Simplification Queue
  17843. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17844. this.simplificationQueue.executeNext();
  17845. }
  17846. // Animations
  17847. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17848. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17849. this._animate();
  17850. // Physics
  17851. if (this._physicsEngine) {
  17852. BABYLON.Tools.StartPerformanceCounter("Physics");
  17853. this._physicsEngine._step(deltaTime / 1000.0);
  17854. BABYLON.Tools.EndPerformanceCounter("Physics");
  17855. }
  17856. // Before render
  17857. this.onBeforeRenderObservable.notifyObservers(this);
  17858. // Customs render targets
  17859. this._renderTargetsDuration.beginMonitoring();
  17860. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17861. var engine = this.getEngine();
  17862. var currentActiveCamera = this.activeCamera;
  17863. if (this.renderTargetsEnabled) {
  17864. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17865. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17866. var renderTarget = this.customRenderTargets[customIndex];
  17867. if (renderTarget._shouldRender()) {
  17868. this._renderId++;
  17869. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17870. if (!this.activeCamera)
  17871. throw new Error("Active camera not set");
  17872. // Viewport
  17873. engine.setViewport(this.activeCamera.viewport);
  17874. // Camera
  17875. this.updateTransformMatrix();
  17876. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17877. }
  17878. }
  17879. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17880. this._renderId++;
  17881. }
  17882. if (this.customRenderTargets.length > 0) {
  17883. engine.restoreDefaultFramebuffer();
  17884. }
  17885. this._renderTargetsDuration.endMonitoring();
  17886. this.activeCamera = currentActiveCamera;
  17887. // Procedural textures
  17888. if (this.proceduralTexturesEnabled) {
  17889. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17890. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17891. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17892. if (proceduralTexture._shouldRender()) {
  17893. proceduralTexture.render();
  17894. }
  17895. }
  17896. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17897. }
  17898. // Clear
  17899. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  17900. // Shadows
  17901. if (this.shadowsEnabled) {
  17902. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17903. var light = this.lights[lightIndex];
  17904. var shadowGenerator = light.getShadowGenerator();
  17905. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  17906. this._renderTargets.push(shadowGenerator.getShadowMap());
  17907. }
  17908. }
  17909. }
  17910. // Depth renderer
  17911. if (this._depthRenderer) {
  17912. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17913. }
  17914. // HighlightLayer
  17915. if (this.highlightLayers && this.highlightLayers.length > 0) {
  17916. for (var i = 0; i < this.highlightLayers.length; i++) {
  17917. if (this.highlightLayers[i].shouldRender()) {
  17918. this._renderTargets.push(this.highlightLayers[i]._mainTexture);
  17919. }
  17920. }
  17921. }
  17922. // RenderPipeline
  17923. this.postProcessRenderPipelineManager.update();
  17924. // Multi-cameras?
  17925. if (this.activeCameras.length > 0) {
  17926. var currentRenderId = this._renderId;
  17927. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17928. this._renderId = currentRenderId;
  17929. if (cameraIndex > 0) {
  17930. this._engine.clear(0, false, true, true);
  17931. }
  17932. this._processSubCameras(this.activeCameras[cameraIndex]);
  17933. }
  17934. }
  17935. else {
  17936. if (!this.activeCamera) {
  17937. throw new Error("No camera defined");
  17938. }
  17939. this._processSubCameras(this.activeCamera);
  17940. }
  17941. // Intersection checks
  17942. this._checkIntersections();
  17943. // Update the audio listener attached to the camera
  17944. if (BABYLON.AudioEngine) {
  17945. this._updateAudioParameters();
  17946. }
  17947. // After render
  17948. if (this.afterRender) {
  17949. this.afterRender();
  17950. }
  17951. this.onAfterRenderObservable.notifyObservers(this);
  17952. // Cleaning
  17953. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17954. this._toBeDisposed.data[index].dispose();
  17955. this._toBeDisposed[index] = null;
  17956. }
  17957. this._toBeDisposed.reset();
  17958. if (this.dumpNextRenderTargets) {
  17959. this.dumpNextRenderTargets = false;
  17960. }
  17961. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17962. this._lastFrameDuration.endMonitoring();
  17963. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17964. this._totalLightsCounter.addCount(this.lights.length, true);
  17965. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17966. this._totalTexturesCounter.addCount(this.textures.length, true);
  17967. this._activeBones.addCount(0, true);
  17968. this._activeIndices.addCount(0, true);
  17969. this._activeParticles.addCount(0, true);
  17970. };
  17971. Scene.prototype._updateAudioParameters = function () {
  17972. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17973. return;
  17974. }
  17975. var listeningCamera;
  17976. var audioEngine = BABYLON.Engine.audioEngine;
  17977. if (this.activeCameras.length > 0) {
  17978. listeningCamera = this.activeCameras[0];
  17979. }
  17980. else {
  17981. listeningCamera = this.activeCamera;
  17982. }
  17983. if (listeningCamera && audioEngine.canUseWebAudio) {
  17984. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17985. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17986. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17987. cameraDirection.normalize();
  17988. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17989. var i;
  17990. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17991. var sound = this.mainSoundTrack.soundCollection[i];
  17992. if (sound.useCustomAttenuation) {
  17993. sound.updateDistanceFromListener();
  17994. }
  17995. }
  17996. for (i = 0; i < this.soundTracks.length; i++) {
  17997. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17998. sound = this.soundTracks[i].soundCollection[j];
  17999. if (sound.useCustomAttenuation) {
  18000. sound.updateDistanceFromListener();
  18001. }
  18002. }
  18003. }
  18004. }
  18005. };
  18006. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18007. // Audio
  18008. get: function () {
  18009. return this._audioEnabled;
  18010. },
  18011. set: function (value) {
  18012. this._audioEnabled = value;
  18013. if (BABYLON.AudioEngine) {
  18014. if (this._audioEnabled) {
  18015. this._enableAudio();
  18016. }
  18017. else {
  18018. this._disableAudio();
  18019. }
  18020. }
  18021. },
  18022. enumerable: true,
  18023. configurable: true
  18024. });
  18025. Scene.prototype._disableAudio = function () {
  18026. var i;
  18027. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18028. this.mainSoundTrack.soundCollection[i].pause();
  18029. }
  18030. for (i = 0; i < this.soundTracks.length; i++) {
  18031. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18032. this.soundTracks[i].soundCollection[j].pause();
  18033. }
  18034. }
  18035. };
  18036. Scene.prototype._enableAudio = function () {
  18037. var i;
  18038. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18039. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18040. this.mainSoundTrack.soundCollection[i].play();
  18041. }
  18042. }
  18043. for (i = 0; i < this.soundTracks.length; i++) {
  18044. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18045. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18046. this.soundTracks[i].soundCollection[j].play();
  18047. }
  18048. }
  18049. }
  18050. };
  18051. Object.defineProperty(Scene.prototype, "headphone", {
  18052. get: function () {
  18053. return this._headphone;
  18054. },
  18055. set: function (value) {
  18056. this._headphone = value;
  18057. if (BABYLON.AudioEngine) {
  18058. if (this._headphone) {
  18059. this._switchAudioModeForHeadphones();
  18060. }
  18061. else {
  18062. this._switchAudioModeForNormalSpeakers();
  18063. }
  18064. }
  18065. },
  18066. enumerable: true,
  18067. configurable: true
  18068. });
  18069. Scene.prototype._switchAudioModeForHeadphones = function () {
  18070. this.mainSoundTrack.switchPanningModelToHRTF();
  18071. for (var i = 0; i < this.soundTracks.length; i++) {
  18072. this.soundTracks[i].switchPanningModelToHRTF();
  18073. }
  18074. };
  18075. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18076. this.mainSoundTrack.switchPanningModelToEqualPower();
  18077. for (var i = 0; i < this.soundTracks.length; i++) {
  18078. this.soundTracks[i].switchPanningModelToEqualPower();
  18079. }
  18080. };
  18081. Scene.prototype.enableDepthRenderer = function () {
  18082. if (this._depthRenderer) {
  18083. return this._depthRenderer;
  18084. }
  18085. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18086. return this._depthRenderer;
  18087. };
  18088. Scene.prototype.disableDepthRenderer = function () {
  18089. if (!this._depthRenderer) {
  18090. return;
  18091. }
  18092. this._depthRenderer.dispose();
  18093. this._depthRenderer = null;
  18094. };
  18095. Scene.prototype.freezeMaterials = function () {
  18096. for (var i = 0; i < this.materials.length; i++) {
  18097. this.materials[i].freeze();
  18098. }
  18099. };
  18100. Scene.prototype.unfreezeMaterials = function () {
  18101. for (var i = 0; i < this.materials.length; i++) {
  18102. this.materials[i].unfreeze();
  18103. }
  18104. };
  18105. Scene.prototype.dispose = function () {
  18106. this.beforeRender = null;
  18107. this.afterRender = null;
  18108. this.skeletons = [];
  18109. this._boundingBoxRenderer.dispose();
  18110. if (this._depthRenderer) {
  18111. this._depthRenderer.dispose();
  18112. }
  18113. // Debug layer
  18114. if (this._debugLayer) {
  18115. this._debugLayer.hide();
  18116. }
  18117. // Events
  18118. this.onDisposeObservable.notifyObservers(this);
  18119. this.onDisposeObservable.clear();
  18120. this.onBeforeRenderObservable.clear();
  18121. this.onAfterRenderObservable.clear();
  18122. this.detachControl();
  18123. // Release sounds & sounds tracks
  18124. if (BABYLON.AudioEngine) {
  18125. this.disposeSounds();
  18126. }
  18127. // Detach cameras
  18128. var canvas = this._engine.getRenderingCanvas();
  18129. var index;
  18130. for (index = 0; index < this.cameras.length; index++) {
  18131. this.cameras[index].detachControl(canvas);
  18132. }
  18133. // Release lights
  18134. while (this.lights.length) {
  18135. this.lights[0].dispose();
  18136. }
  18137. // Release meshes
  18138. while (this.meshes.length) {
  18139. this.meshes[0].dispose(true);
  18140. }
  18141. // Release cameras
  18142. while (this.cameras.length) {
  18143. this.cameras[0].dispose();
  18144. }
  18145. // Release materials
  18146. while (this.materials.length) {
  18147. this.materials[0].dispose();
  18148. }
  18149. // Release particles
  18150. while (this.particleSystems.length) {
  18151. this.particleSystems[0].dispose();
  18152. }
  18153. // Release sprites
  18154. while (this.spriteManagers.length) {
  18155. this.spriteManagers[0].dispose();
  18156. }
  18157. // Release layers
  18158. while (this.layers.length) {
  18159. this.layers[0].dispose();
  18160. }
  18161. while (this.highlightLayers.length) {
  18162. this.highlightLayers[0].dispose();
  18163. }
  18164. // Release textures
  18165. while (this.textures.length) {
  18166. this.textures[0].dispose();
  18167. }
  18168. // Post-processes
  18169. this.postProcessManager.dispose();
  18170. // Physics
  18171. if (this._physicsEngine) {
  18172. this.disablePhysicsEngine();
  18173. }
  18174. // Remove from engine
  18175. index = this._engine.scenes.indexOf(this);
  18176. if (index > -1) {
  18177. this._engine.scenes.splice(index, 1);
  18178. }
  18179. this._engine.wipeCaches();
  18180. };
  18181. // Release sounds & sounds tracks
  18182. Scene.prototype.disposeSounds = function () {
  18183. this.mainSoundTrack.dispose();
  18184. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18185. this.soundTracks[scIndex].dispose();
  18186. }
  18187. };
  18188. // Octrees
  18189. Scene.prototype.getWorldExtends = function () {
  18190. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18191. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18192. for (var index = 0; index < this.meshes.length; index++) {
  18193. var mesh = this.meshes[index];
  18194. mesh.computeWorldMatrix(true);
  18195. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18196. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18197. BABYLON.Tools.CheckExtends(minBox, min, max);
  18198. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18199. }
  18200. return {
  18201. min: min,
  18202. max: max
  18203. };
  18204. };
  18205. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18206. if (maxCapacity === void 0) { maxCapacity = 64; }
  18207. if (maxDepth === void 0) { maxDepth = 2; }
  18208. if (!this._selectionOctree) {
  18209. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18210. }
  18211. var worldExtends = this.getWorldExtends();
  18212. // Update octree
  18213. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18214. return this._selectionOctree;
  18215. };
  18216. // Picking
  18217. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18218. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18219. var engine = this._engine;
  18220. if (!camera) {
  18221. if (!this.activeCamera)
  18222. throw new Error("Active camera not set");
  18223. camera = this.activeCamera;
  18224. }
  18225. var cameraViewport = camera.viewport;
  18226. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18227. // Moving coordinates to local viewport world
  18228. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18229. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18230. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18231. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18232. };
  18233. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  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. var identity = BABYLON.Matrix.Identity();
  18243. // Moving coordinates to local viewport world
  18244. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18245. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18246. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18247. };
  18248. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18249. var pickingInfo = null;
  18250. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18251. var mesh = this.meshes[meshIndex];
  18252. if (predicate) {
  18253. if (!predicate(mesh)) {
  18254. continue;
  18255. }
  18256. }
  18257. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18258. continue;
  18259. }
  18260. var world = mesh.getWorldMatrix();
  18261. var ray = rayFunction(world);
  18262. var result = mesh.intersects(ray, fastCheck);
  18263. if (!result || !result.hit)
  18264. continue;
  18265. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18266. continue;
  18267. pickingInfo = result;
  18268. if (fastCheck) {
  18269. break;
  18270. }
  18271. }
  18272. return pickingInfo || new BABYLON.PickingInfo();
  18273. };
  18274. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18275. var pickingInfo = null;
  18276. camera = camera || this.activeCamera;
  18277. if (this.spriteManagers.length > 0) {
  18278. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18279. var spriteManager = this.spriteManagers[spriteIndex];
  18280. if (!spriteManager.isPickable) {
  18281. continue;
  18282. }
  18283. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18284. if (!result || !result.hit)
  18285. continue;
  18286. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18287. continue;
  18288. pickingInfo = result;
  18289. if (fastCheck) {
  18290. break;
  18291. }
  18292. }
  18293. }
  18294. return pickingInfo || new BABYLON.PickingInfo();
  18295. };
  18296. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18297. var _this = this;
  18298. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18299. /// <param name="x">X position on screen</param>
  18300. /// <param name="y">Y position on screen</param>
  18301. /// <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>
  18302. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18303. /// <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>
  18304. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18305. };
  18306. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18307. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18308. /// <param name="x">X position on screen</param>
  18309. /// <param name="y">Y position on screen</param>
  18310. /// <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>
  18311. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18312. /// <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>
  18313. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18314. };
  18315. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18316. var _this = this;
  18317. return this._internalPick(function (world) {
  18318. if (!_this._pickWithRayInverseMatrix) {
  18319. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18320. }
  18321. world.invertToRef(_this._pickWithRayInverseMatrix);
  18322. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18323. }, predicate, fastCheck);
  18324. };
  18325. Scene.prototype.setPointerOverMesh = function (mesh) {
  18326. if (this._pointerOverMesh === mesh) {
  18327. return;
  18328. }
  18329. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18330. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18331. }
  18332. this._pointerOverMesh = mesh;
  18333. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18334. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18335. }
  18336. };
  18337. Scene.prototype.getPointerOverMesh = function () {
  18338. return this._pointerOverMesh;
  18339. };
  18340. Scene.prototype.setPointerOverSprite = function (sprite) {
  18341. if (this._pointerOverSprite === sprite) {
  18342. return;
  18343. }
  18344. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18345. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18346. }
  18347. this._pointerOverSprite = sprite;
  18348. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18349. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18350. }
  18351. };
  18352. Scene.prototype.getPointerOverSprite = function () {
  18353. return this._pointerOverSprite;
  18354. };
  18355. // Physics
  18356. Scene.prototype.getPhysicsEngine = function () {
  18357. return this._physicsEngine;
  18358. };
  18359. /**
  18360. * Enables physics to the current scene
  18361. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18362. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18363. * @return {boolean} was the physics engine initialized
  18364. */
  18365. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18366. if (this._physicsEngine) {
  18367. return true;
  18368. }
  18369. try {
  18370. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18371. return true;
  18372. }
  18373. catch (e) {
  18374. BABYLON.Tools.Error(e.message);
  18375. return false;
  18376. }
  18377. };
  18378. Scene.prototype.disablePhysicsEngine = function () {
  18379. if (!this._physicsEngine) {
  18380. return;
  18381. }
  18382. this._physicsEngine.dispose();
  18383. this._physicsEngine = undefined;
  18384. };
  18385. Scene.prototype.isPhysicsEnabled = function () {
  18386. return this._physicsEngine !== undefined;
  18387. };
  18388. /**
  18389. *
  18390. * Sets the gravity of the physics engine (and NOT of the scene)
  18391. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  18392. */
  18393. Scene.prototype.setGravity = function (gravity) {
  18394. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  18395. if (!this._physicsEngine) {
  18396. return;
  18397. }
  18398. this._physicsEngine.setGravity(gravity);
  18399. };
  18400. /**
  18401. * Legacy support, using the new API
  18402. * @Deprecated
  18403. */
  18404. Scene.prototype.createCompoundImpostor = function (parts, options) {
  18405. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  18406. if (parts.parts) {
  18407. options = parts;
  18408. parts = parts.parts;
  18409. }
  18410. var mainMesh = parts[0].mesh;
  18411. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  18412. for (var index = 1; index < parts.length; index++) {
  18413. var mesh = parts[index].mesh;
  18414. if (mesh.parent !== mainMesh) {
  18415. mesh.position = mesh.position.subtract(mainMesh.position);
  18416. mesh.parent = mainMesh;
  18417. }
  18418. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  18419. }
  18420. mainMesh.physicsImpostor.forceUpdate();
  18421. };
  18422. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18423. var mesh = compound.parts[0].mesh;
  18424. mesh.physicsImpostor.dispose();
  18425. mesh.physicsImpostor = null;
  18426. };
  18427. // Misc.
  18428. Scene.prototype.createDefaultCameraOrLight = function () {
  18429. // Light
  18430. if (this.lights.length === 0) {
  18431. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18432. }
  18433. // Camera
  18434. if (!this.activeCamera) {
  18435. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  18436. // Compute position
  18437. var worldExtends = this.getWorldExtends();
  18438. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  18439. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  18440. camera.setTarget(worldCenter);
  18441. this.activeCamera = camera;
  18442. }
  18443. };
  18444. // Tags
  18445. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18446. if (tagsQuery === undefined) {
  18447. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18448. return list;
  18449. }
  18450. var listByTags = [];
  18451. forEach = forEach || (function (item) { return; });
  18452. for (var i in list) {
  18453. var item = list[i];
  18454. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18455. listByTags.push(item);
  18456. forEach(item);
  18457. }
  18458. }
  18459. return listByTags;
  18460. };
  18461. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18462. return this._getByTags(this.meshes, tagsQuery, forEach);
  18463. };
  18464. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18465. return this._getByTags(this.cameras, tagsQuery, forEach);
  18466. };
  18467. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18468. return this._getByTags(this.lights, tagsQuery, forEach);
  18469. };
  18470. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18471. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18472. };
  18473. /**
  18474. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18475. * This allowed control for front to back rendering or reversly depending of the special needs.
  18476. *
  18477. * @param renderingGroupId The rendering group id corresponding to its index
  18478. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18479. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18480. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18481. */
  18482. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18483. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18484. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18485. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18486. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18487. };
  18488. /**
  18489. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18490. *
  18491. * @param renderingGroupId The rendering group id corresponding to its index
  18492. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18493. */
  18494. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18495. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18496. };
  18497. // Statics
  18498. Scene._FOGMODE_NONE = 0;
  18499. Scene._FOGMODE_EXP = 1;
  18500. Scene._FOGMODE_EXP2 = 2;
  18501. Scene._FOGMODE_LINEAR = 3;
  18502. Scene.MinDeltaTime = 1.0;
  18503. Scene.MaxDeltaTime = 1000.0;
  18504. return Scene;
  18505. }());
  18506. BABYLON.Scene = Scene;
  18507. })(BABYLON || (BABYLON = {}));
  18508. var BABYLON;
  18509. (function (BABYLON) {
  18510. var Buffer = (function () {
  18511. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18512. if (engine instanceof BABYLON.Mesh) {
  18513. this._engine = engine.getScene().getEngine();
  18514. }
  18515. else {
  18516. this._engine = engine;
  18517. }
  18518. this._updatable = updatable;
  18519. this._data = data;
  18520. this._strideSize = stride;
  18521. if (!postponeInternalCreation) {
  18522. this.create();
  18523. }
  18524. this._instanced = instanced;
  18525. }
  18526. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18527. // a lot of these parameters are ignored as they are overriden by the buffer
  18528. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18529. };
  18530. // Properties
  18531. Buffer.prototype.isUpdatable = function () {
  18532. return this._updatable;
  18533. };
  18534. Buffer.prototype.getData = function () {
  18535. return this._data;
  18536. };
  18537. Buffer.prototype.getBuffer = function () {
  18538. return this._buffer;
  18539. };
  18540. Buffer.prototype.getStrideSize = function () {
  18541. return this._strideSize;
  18542. };
  18543. Buffer.prototype.getIsInstanced = function () {
  18544. return this._instanced;
  18545. };
  18546. // Methods
  18547. Buffer.prototype.create = function (data) {
  18548. if (!data && this._buffer) {
  18549. return; // nothing to do
  18550. }
  18551. data = data || this._data;
  18552. if (!this._buffer) {
  18553. if (this._updatable) {
  18554. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18555. this._data = data;
  18556. }
  18557. else {
  18558. this._buffer = this._engine.createVertexBuffer(data);
  18559. }
  18560. }
  18561. else if (this._updatable) {
  18562. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18563. this._data = data;
  18564. }
  18565. };
  18566. Buffer.prototype.update = function (data) {
  18567. this.create(data);
  18568. };
  18569. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18570. if (!this._buffer) {
  18571. return;
  18572. }
  18573. if (this._updatable) {
  18574. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18575. this._data = null;
  18576. }
  18577. };
  18578. Buffer.prototype.dispose = function () {
  18579. if (!this._buffer) {
  18580. return;
  18581. }
  18582. if (this._engine._releaseBuffer(this._buffer)) {
  18583. this._buffer = null;
  18584. }
  18585. };
  18586. return Buffer;
  18587. }());
  18588. BABYLON.Buffer = Buffer;
  18589. })(BABYLON || (BABYLON = {}));
  18590. var BABYLON;
  18591. (function (BABYLON) {
  18592. var VertexBuffer = (function () {
  18593. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18594. if (!stride) {
  18595. // Deduce stride from kind
  18596. switch (kind) {
  18597. case VertexBuffer.PositionKind:
  18598. stride = 3;
  18599. break;
  18600. case VertexBuffer.NormalKind:
  18601. stride = 3;
  18602. break;
  18603. case VertexBuffer.UVKind:
  18604. case VertexBuffer.UV2Kind:
  18605. case VertexBuffer.UV3Kind:
  18606. case VertexBuffer.UV4Kind:
  18607. case VertexBuffer.UV5Kind:
  18608. case VertexBuffer.UV6Kind:
  18609. stride = 2;
  18610. break;
  18611. case VertexBuffer.ColorKind:
  18612. stride = 4;
  18613. break;
  18614. case VertexBuffer.MatricesIndicesKind:
  18615. case VertexBuffer.MatricesIndicesExtraKind:
  18616. stride = 4;
  18617. break;
  18618. case VertexBuffer.MatricesWeightsKind:
  18619. case VertexBuffer.MatricesWeightsExtraKind:
  18620. stride = 4;
  18621. break;
  18622. }
  18623. }
  18624. if (data instanceof BABYLON.Buffer) {
  18625. if (!stride) {
  18626. stride = data.getStrideSize();
  18627. }
  18628. this._buffer = data;
  18629. this._ownsBuffer = false;
  18630. }
  18631. else {
  18632. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18633. this._ownsBuffer = true;
  18634. }
  18635. this._stride = stride;
  18636. this._offset = offset ? offset : 0;
  18637. this._size = size ? size : stride;
  18638. this._kind = kind;
  18639. }
  18640. VertexBuffer.prototype.getKind = function () {
  18641. return this._kind;
  18642. };
  18643. // Properties
  18644. VertexBuffer.prototype.isUpdatable = function () {
  18645. return this._buffer.isUpdatable();
  18646. };
  18647. VertexBuffer.prototype.getData = function () {
  18648. return this._buffer.getData();
  18649. };
  18650. VertexBuffer.prototype.getBuffer = function () {
  18651. return this._buffer.getBuffer();
  18652. };
  18653. VertexBuffer.prototype.getStrideSize = function () {
  18654. return this._stride;
  18655. };
  18656. VertexBuffer.prototype.getOffset = function () {
  18657. return this._offset;
  18658. };
  18659. VertexBuffer.prototype.getSize = function () {
  18660. return this._size;
  18661. };
  18662. VertexBuffer.prototype.getIsInstanced = function () {
  18663. return this._buffer.getIsInstanced();
  18664. };
  18665. // Methods
  18666. VertexBuffer.prototype.create = function (data) {
  18667. return this._buffer.create(data);
  18668. };
  18669. VertexBuffer.prototype.update = function (data) {
  18670. return this._buffer.update(data);
  18671. };
  18672. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18673. return this._buffer.updateDirectly(data, offset);
  18674. };
  18675. VertexBuffer.prototype.dispose = function () {
  18676. if (this._ownsBuffer) {
  18677. this._buffer.dispose();
  18678. }
  18679. };
  18680. Object.defineProperty(VertexBuffer, "PositionKind", {
  18681. get: function () {
  18682. return VertexBuffer._PositionKind;
  18683. },
  18684. enumerable: true,
  18685. configurable: true
  18686. });
  18687. Object.defineProperty(VertexBuffer, "NormalKind", {
  18688. get: function () {
  18689. return VertexBuffer._NormalKind;
  18690. },
  18691. enumerable: true,
  18692. configurable: true
  18693. });
  18694. Object.defineProperty(VertexBuffer, "UVKind", {
  18695. get: function () {
  18696. return VertexBuffer._UVKind;
  18697. },
  18698. enumerable: true,
  18699. configurable: true
  18700. });
  18701. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18702. get: function () {
  18703. return VertexBuffer._UV2Kind;
  18704. },
  18705. enumerable: true,
  18706. configurable: true
  18707. });
  18708. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18709. get: function () {
  18710. return VertexBuffer._UV3Kind;
  18711. },
  18712. enumerable: true,
  18713. configurable: true
  18714. });
  18715. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18716. get: function () {
  18717. return VertexBuffer._UV4Kind;
  18718. },
  18719. enumerable: true,
  18720. configurable: true
  18721. });
  18722. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18723. get: function () {
  18724. return VertexBuffer._UV5Kind;
  18725. },
  18726. enumerable: true,
  18727. configurable: true
  18728. });
  18729. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18730. get: function () {
  18731. return VertexBuffer._UV6Kind;
  18732. },
  18733. enumerable: true,
  18734. configurable: true
  18735. });
  18736. Object.defineProperty(VertexBuffer, "ColorKind", {
  18737. get: function () {
  18738. return VertexBuffer._ColorKind;
  18739. },
  18740. enumerable: true,
  18741. configurable: true
  18742. });
  18743. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18744. get: function () {
  18745. return VertexBuffer._MatricesIndicesKind;
  18746. },
  18747. enumerable: true,
  18748. configurable: true
  18749. });
  18750. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18751. get: function () {
  18752. return VertexBuffer._MatricesWeightsKind;
  18753. },
  18754. enumerable: true,
  18755. configurable: true
  18756. });
  18757. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18758. get: function () {
  18759. return VertexBuffer._MatricesIndicesExtraKind;
  18760. },
  18761. enumerable: true,
  18762. configurable: true
  18763. });
  18764. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18765. get: function () {
  18766. return VertexBuffer._MatricesWeightsExtraKind;
  18767. },
  18768. enumerable: true,
  18769. configurable: true
  18770. });
  18771. // Enums
  18772. VertexBuffer._PositionKind = "position";
  18773. VertexBuffer._NormalKind = "normal";
  18774. VertexBuffer._UVKind = "uv";
  18775. VertexBuffer._UV2Kind = "uv2";
  18776. VertexBuffer._UV3Kind = "uv3";
  18777. VertexBuffer._UV4Kind = "uv4";
  18778. VertexBuffer._UV5Kind = "uv5";
  18779. VertexBuffer._UV6Kind = "uv6";
  18780. VertexBuffer._ColorKind = "color";
  18781. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18782. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18783. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18784. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18785. return VertexBuffer;
  18786. }());
  18787. BABYLON.VertexBuffer = VertexBuffer;
  18788. })(BABYLON || (BABYLON = {}));
  18789. var BABYLON;
  18790. (function (BABYLON) {
  18791. /**
  18792. * Creates an instance based on a source mesh.
  18793. */
  18794. var InstancedMesh = (function (_super) {
  18795. __extends(InstancedMesh, _super);
  18796. function InstancedMesh(name, source) {
  18797. _super.call(this, name, source.getScene());
  18798. source.instances.push(this);
  18799. this._sourceMesh = source;
  18800. this.position.copyFrom(source.position);
  18801. this.rotation.copyFrom(source.rotation);
  18802. this.scaling.copyFrom(source.scaling);
  18803. if (source.rotationQuaternion) {
  18804. this.rotationQuaternion = source.rotationQuaternion.clone();
  18805. }
  18806. this.infiniteDistance = source.infiniteDistance;
  18807. this.setPivotMatrix(source.getPivotMatrix());
  18808. this.refreshBoundingInfo();
  18809. this._syncSubMeshes();
  18810. }
  18811. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  18812. // Methods
  18813. get: function () {
  18814. return this._sourceMesh.receiveShadows;
  18815. },
  18816. enumerable: true,
  18817. configurable: true
  18818. });
  18819. Object.defineProperty(InstancedMesh.prototype, "material", {
  18820. get: function () {
  18821. return this._sourceMesh.material;
  18822. },
  18823. enumerable: true,
  18824. configurable: true
  18825. });
  18826. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  18827. get: function () {
  18828. return this._sourceMesh.visibility;
  18829. },
  18830. enumerable: true,
  18831. configurable: true
  18832. });
  18833. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  18834. get: function () {
  18835. return this._sourceMesh.skeleton;
  18836. },
  18837. enumerable: true,
  18838. configurable: true
  18839. });
  18840. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  18841. get: function () {
  18842. return this._sourceMesh.renderingGroupId;
  18843. },
  18844. enumerable: true,
  18845. configurable: true
  18846. });
  18847. InstancedMesh.prototype.getTotalVertices = function () {
  18848. return this._sourceMesh.getTotalVertices();
  18849. };
  18850. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  18851. get: function () {
  18852. return this._sourceMesh;
  18853. },
  18854. enumerable: true,
  18855. configurable: true
  18856. });
  18857. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18858. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  18859. };
  18860. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  18861. return this._sourceMesh.isVerticesDataPresent(kind);
  18862. };
  18863. InstancedMesh.prototype.getIndices = function () {
  18864. return this._sourceMesh.getIndices();
  18865. };
  18866. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  18867. get: function () {
  18868. return this._sourceMesh._positions;
  18869. },
  18870. enumerable: true,
  18871. configurable: true
  18872. });
  18873. InstancedMesh.prototype.refreshBoundingInfo = function () {
  18874. var meshBB = this._sourceMesh.getBoundingInfo();
  18875. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  18876. this._updateBoundingInfo();
  18877. };
  18878. InstancedMesh.prototype._preActivate = function () {
  18879. if (this._currentLOD) {
  18880. this._currentLOD._preActivate();
  18881. }
  18882. };
  18883. InstancedMesh.prototype._activate = function (renderId) {
  18884. if (this._currentLOD) {
  18885. this._currentLOD._registerInstanceForRenderId(this, renderId);
  18886. }
  18887. };
  18888. InstancedMesh.prototype.getLOD = function (camera) {
  18889. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  18890. if (this._currentLOD === this.sourceMesh) {
  18891. return this;
  18892. }
  18893. return this._currentLOD;
  18894. };
  18895. InstancedMesh.prototype._syncSubMeshes = function () {
  18896. this.releaseSubMeshes();
  18897. if (this._sourceMesh.subMeshes) {
  18898. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  18899. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  18900. }
  18901. }
  18902. };
  18903. InstancedMesh.prototype._generatePointsArray = function () {
  18904. return this._sourceMesh._generatePointsArray();
  18905. };
  18906. // Clone
  18907. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18908. var result = this._sourceMesh.createInstance(name);
  18909. // Deep copy
  18910. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  18911. // Bounding info
  18912. this.refreshBoundingInfo();
  18913. // Parent
  18914. if (newParent) {
  18915. result.parent = newParent;
  18916. }
  18917. if (!doNotCloneChildren) {
  18918. // Children
  18919. for (var index = 0; index < this.getScene().meshes.length; index++) {
  18920. var mesh = this.getScene().meshes[index];
  18921. if (mesh.parent === this) {
  18922. mesh.clone(mesh.name, result);
  18923. }
  18924. }
  18925. }
  18926. result.computeWorldMatrix(true);
  18927. return result;
  18928. };
  18929. // Dispoe
  18930. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  18931. // Remove from mesh
  18932. var index = this._sourceMesh.instances.indexOf(this);
  18933. this._sourceMesh.instances.splice(index, 1);
  18934. _super.prototype.dispose.call(this, doNotRecurse);
  18935. };
  18936. return InstancedMesh;
  18937. }(BABYLON.AbstractMesh));
  18938. BABYLON.InstancedMesh = InstancedMesh;
  18939. })(BABYLON || (BABYLON = {}));
  18940. var BABYLON;
  18941. (function (BABYLON) {
  18942. var _InstancesBatch = (function () {
  18943. function _InstancesBatch() {
  18944. this.mustReturn = false;
  18945. this.visibleInstances = new Array();
  18946. this.renderSelf = new Array();
  18947. }
  18948. return _InstancesBatch;
  18949. }());
  18950. BABYLON._InstancesBatch = _InstancesBatch;
  18951. var Mesh = (function (_super) {
  18952. __extends(Mesh, _super);
  18953. /**
  18954. * @constructor
  18955. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18956. * @param {Scene} scene The scene to add this mesh to.
  18957. * @param {Node} parent The parent of this mesh, if it has one
  18958. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18959. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18960. * When false, achieved by calling a clone(), also passing False.
  18961. * This will make creation of children, recursive.
  18962. */
  18963. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18964. if (parent === void 0) { parent = null; }
  18965. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18966. _super.call(this, name, scene);
  18967. // Events
  18968. /**
  18969. * An event triggered before rendering the mesh
  18970. * @type {BABYLON.Observable}
  18971. */
  18972. this.onBeforeRenderObservable = new BABYLON.Observable();
  18973. /**
  18974. * An event triggered after rendering the mesh
  18975. * @type {BABYLON.Observable}
  18976. */
  18977. this.onAfterRenderObservable = new BABYLON.Observable();
  18978. /**
  18979. * An event triggered before drawing the mesh
  18980. * @type {BABYLON.Observable}
  18981. */
  18982. this.onBeforeDrawObservable = new BABYLON.Observable();
  18983. // Members
  18984. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18985. this.instances = new Array();
  18986. this._LODLevels = new Array();
  18987. this._visibleInstances = {};
  18988. this._renderIdForInstances = new Array();
  18989. this._batchCache = new _InstancesBatch();
  18990. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18991. this._sideOrientation = Mesh._DEFAULTSIDE;
  18992. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18993. if (source) {
  18994. // Geometry
  18995. if (source._geometry) {
  18996. source._geometry.applyToMesh(this);
  18997. }
  18998. // Deep copy
  18999. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  19000. // Pivot
  19001. this.setPivotMatrix(source.getPivotMatrix());
  19002. this.id = name + "." + source.id;
  19003. // Material
  19004. this.material = source.material;
  19005. var index;
  19006. if (!doNotCloneChildren) {
  19007. // Children
  19008. for (index = 0; index < scene.meshes.length; index++) {
  19009. var mesh = scene.meshes[index];
  19010. if (mesh.parent === source) {
  19011. // doNotCloneChildren is always going to be False
  19012. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  19013. }
  19014. }
  19015. }
  19016. // Physics clone
  19017. var physicsEngine = this.getScene().getPhysicsEngine();
  19018. if (clonePhysicsImpostor && physicsEngine) {
  19019. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19020. if (impostor) {
  19021. this.physicsImpostor = impostor.clone(this);
  19022. }
  19023. }
  19024. // Particles
  19025. for (index = 0; index < scene.particleSystems.length; index++) {
  19026. var system = scene.particleSystems[index];
  19027. if (system.emitter === source) {
  19028. system.clone(system.name, this);
  19029. }
  19030. }
  19031. this.computeWorldMatrix(true);
  19032. }
  19033. // Parent
  19034. if (parent !== null) {
  19035. this.parent = parent;
  19036. }
  19037. }
  19038. Object.defineProperty(Mesh, "FRONTSIDE", {
  19039. /**
  19040. * Mesh side orientation : usually the external or front surface
  19041. */
  19042. get: function () {
  19043. return Mesh._FRONTSIDE;
  19044. },
  19045. enumerable: true,
  19046. configurable: true
  19047. });
  19048. Object.defineProperty(Mesh, "BACKSIDE", {
  19049. /**
  19050. * Mesh side orientation : usually the internal or back surface
  19051. */
  19052. get: function () {
  19053. return Mesh._BACKSIDE;
  19054. },
  19055. enumerable: true,
  19056. configurable: true
  19057. });
  19058. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19059. /**
  19060. * Mesh side orientation : both internal and external or front and back surfaces
  19061. */
  19062. get: function () {
  19063. return Mesh._DOUBLESIDE;
  19064. },
  19065. enumerable: true,
  19066. configurable: true
  19067. });
  19068. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19069. /**
  19070. * Mesh side orientation : by default, `FRONTSIDE`
  19071. */
  19072. get: function () {
  19073. return Mesh._DEFAULTSIDE;
  19074. },
  19075. enumerable: true,
  19076. configurable: true
  19077. });
  19078. Object.defineProperty(Mesh, "NO_CAP", {
  19079. /**
  19080. * Mesh cap setting : no cap
  19081. */
  19082. get: function () {
  19083. return Mesh._NO_CAP;
  19084. },
  19085. enumerable: true,
  19086. configurable: true
  19087. });
  19088. Object.defineProperty(Mesh, "CAP_START", {
  19089. /**
  19090. * Mesh cap setting : one cap at the beginning of the mesh
  19091. */
  19092. get: function () {
  19093. return Mesh._CAP_START;
  19094. },
  19095. enumerable: true,
  19096. configurable: true
  19097. });
  19098. Object.defineProperty(Mesh, "CAP_END", {
  19099. /**
  19100. * Mesh cap setting : one cap at the end of the mesh
  19101. */
  19102. get: function () {
  19103. return Mesh._CAP_END;
  19104. },
  19105. enumerable: true,
  19106. configurable: true
  19107. });
  19108. Object.defineProperty(Mesh, "CAP_ALL", {
  19109. /**
  19110. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19111. */
  19112. get: function () {
  19113. return Mesh._CAP_ALL;
  19114. },
  19115. enumerable: true,
  19116. configurable: true
  19117. });
  19118. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19119. set: function (callback) {
  19120. if (this._onBeforeDrawObserver) {
  19121. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19122. }
  19123. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19124. },
  19125. enumerable: true,
  19126. configurable: true
  19127. });
  19128. // Methods
  19129. /**
  19130. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19131. */
  19132. Mesh.prototype.toString = function (fullDetails) {
  19133. var ret = _super.prototype.toString.call(this, fullDetails);
  19134. ret += ", n vertices: " + this.getTotalVertices();
  19135. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19136. if (this.animations) {
  19137. for (var i = 0; i < this.animations.length; i++) {
  19138. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19139. }
  19140. }
  19141. if (fullDetails) {
  19142. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19143. }
  19144. return ret;
  19145. };
  19146. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19147. get: function () {
  19148. return this._LODLevels.length > 0;
  19149. },
  19150. enumerable: true,
  19151. configurable: true
  19152. });
  19153. Mesh.prototype._sortLODLevels = function () {
  19154. this._LODLevels.sort(function (a, b) {
  19155. if (a.distance < b.distance) {
  19156. return 1;
  19157. }
  19158. if (a.distance > b.distance) {
  19159. return -1;
  19160. }
  19161. return 0;
  19162. });
  19163. };
  19164. /**
  19165. * Add a mesh as LOD level triggered at the given distance.
  19166. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19167. * @param {number} distance The distance from the center of the object to show this level
  19168. * @param {Mesh} mesh The mesh to be added as LOD level
  19169. * @return {Mesh} This mesh (for chaining)
  19170. */
  19171. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19172. if (mesh && mesh._masterMesh) {
  19173. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19174. return this;
  19175. }
  19176. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19177. this._LODLevels.push(level);
  19178. if (mesh) {
  19179. mesh._masterMesh = this;
  19180. }
  19181. this._sortLODLevels();
  19182. return this;
  19183. };
  19184. /**
  19185. * Returns the LOD level mesh at the passed distance or null if not found.
  19186. * It is related to the method `addLODLevel(distance, mesh)`.
  19187. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19188. */
  19189. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19190. for (var index = 0; index < this._LODLevels.length; index++) {
  19191. var level = this._LODLevels[index];
  19192. if (level.distance === distance) {
  19193. return level.mesh;
  19194. }
  19195. }
  19196. return null;
  19197. };
  19198. /**
  19199. * Remove a mesh from the LOD array
  19200. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19201. * @param {Mesh} mesh The mesh to be removed.
  19202. * @return {Mesh} This mesh (for chaining)
  19203. */
  19204. Mesh.prototype.removeLODLevel = function (mesh) {
  19205. for (var index = 0; index < this._LODLevels.length; index++) {
  19206. if (this._LODLevels[index].mesh === mesh) {
  19207. this._LODLevels.splice(index, 1);
  19208. if (mesh) {
  19209. mesh._masterMesh = null;
  19210. }
  19211. }
  19212. }
  19213. this._sortLODLevels();
  19214. return this;
  19215. };
  19216. /**
  19217. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19218. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19219. */
  19220. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19221. if (!this._LODLevels || this._LODLevels.length === 0) {
  19222. return this;
  19223. }
  19224. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19225. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19226. if (this.onLODLevelSelection) {
  19227. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19228. }
  19229. return this;
  19230. }
  19231. for (var index = 0; index < this._LODLevels.length; index++) {
  19232. var level = this._LODLevels[index];
  19233. if (level.distance < distanceToCamera) {
  19234. if (level.mesh) {
  19235. level.mesh._preActivate();
  19236. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19237. }
  19238. if (this.onLODLevelSelection) {
  19239. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19240. }
  19241. return level.mesh;
  19242. }
  19243. }
  19244. if (this.onLODLevelSelection) {
  19245. this.onLODLevelSelection(distanceToCamera, this, this);
  19246. }
  19247. return this;
  19248. };
  19249. Object.defineProperty(Mesh.prototype, "geometry", {
  19250. /**
  19251. * Returns the mesh internal Geometry object.
  19252. */
  19253. get: function () {
  19254. return this._geometry;
  19255. },
  19256. enumerable: true,
  19257. configurable: true
  19258. });
  19259. /**
  19260. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19261. */
  19262. Mesh.prototype.getTotalVertices = function () {
  19263. if (!this._geometry) {
  19264. return 0;
  19265. }
  19266. return this._geometry.getTotalVertices();
  19267. };
  19268. /**
  19269. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19270. * 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.
  19271. * Returns null if the mesh has no geometry or no vertex buffer.
  19272. * Possible `kind` values :
  19273. * - BABYLON.VertexBuffer.PositionKind
  19274. * - BABYLON.VertexBuffer.UVKind
  19275. * - BABYLON.VertexBuffer.UV2Kind
  19276. * - BABYLON.VertexBuffer.UV3Kind
  19277. * - BABYLON.VertexBuffer.UV4Kind
  19278. * - BABYLON.VertexBuffer.UV5Kind
  19279. * - BABYLON.VertexBuffer.UV6Kind
  19280. * - BABYLON.VertexBuffer.ColorKind
  19281. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19282. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19283. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19284. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19285. */
  19286. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19287. if (!this._geometry) {
  19288. return null;
  19289. }
  19290. return this._geometry.getVerticesData(kind, copyWhenShared);
  19291. };
  19292. /**
  19293. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19294. * Returns `undefined` if the mesh has no geometry.
  19295. * Possible `kind` values :
  19296. * - BABYLON.VertexBuffer.PositionKind
  19297. * - BABYLON.VertexBuffer.UVKind
  19298. * - BABYLON.VertexBuffer.UV2Kind
  19299. * - BABYLON.VertexBuffer.UV3Kind
  19300. * - BABYLON.VertexBuffer.UV4Kind
  19301. * - BABYLON.VertexBuffer.UV5Kind
  19302. * - BABYLON.VertexBuffer.UV6Kind
  19303. * - BABYLON.VertexBuffer.ColorKind
  19304. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19305. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19306. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19307. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19308. */
  19309. Mesh.prototype.getVertexBuffer = function (kind) {
  19310. if (!this._geometry) {
  19311. return undefined;
  19312. }
  19313. return this._geometry.getVertexBuffer(kind);
  19314. };
  19315. /**
  19316. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19317. * Possible `kind` values :
  19318. * - BABYLON.VertexBuffer.PositionKind
  19319. * - BABYLON.VertexBuffer.UVKind
  19320. * - BABYLON.VertexBuffer.UV2Kind
  19321. * - BABYLON.VertexBuffer.UV3Kind
  19322. * - BABYLON.VertexBuffer.UV4Kind
  19323. * - BABYLON.VertexBuffer.UV5Kind
  19324. * - BABYLON.VertexBuffer.UV6Kind
  19325. * - BABYLON.VertexBuffer.ColorKind
  19326. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19327. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19328. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19329. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19330. */
  19331. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19332. if (!this._geometry) {
  19333. if (this._delayInfo) {
  19334. return this._delayInfo.indexOf(kind) !== -1;
  19335. }
  19336. return false;
  19337. }
  19338. return this._geometry.isVerticesDataPresent(kind);
  19339. };
  19340. /**
  19341. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19342. * Possible `kind` values :
  19343. * - BABYLON.VertexBuffer.PositionKind
  19344. * - BABYLON.VertexBuffer.UVKind
  19345. * - BABYLON.VertexBuffer.UV2Kind
  19346. * - BABYLON.VertexBuffer.UV3Kind
  19347. * - BABYLON.VertexBuffer.UV4Kind
  19348. * - BABYLON.VertexBuffer.UV5Kind
  19349. * - BABYLON.VertexBuffer.UV6Kind
  19350. * - BABYLON.VertexBuffer.ColorKind
  19351. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19352. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19353. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19354. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19355. */
  19356. Mesh.prototype.getVerticesDataKinds = function () {
  19357. if (!this._geometry) {
  19358. var result = [];
  19359. if (this._delayInfo) {
  19360. this._delayInfo.forEach(function (kind, index, array) {
  19361. result.push(kind);
  19362. });
  19363. }
  19364. return result;
  19365. }
  19366. return this._geometry.getVerticesDataKinds();
  19367. };
  19368. /**
  19369. * Returns a positive integer : the total number of indices in this mesh geometry.
  19370. * Returns zero if the mesh has no geometry.
  19371. */
  19372. Mesh.prototype.getTotalIndices = function () {
  19373. if (!this._geometry) {
  19374. return 0;
  19375. }
  19376. return this._geometry.getTotalIndices();
  19377. };
  19378. /**
  19379. * Returns an array of integers or a Int32Array populated with the mesh indices.
  19380. * 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.
  19381. * Returns an empty array if the mesh has no geometry.
  19382. */
  19383. Mesh.prototype.getIndices = function (copyWhenShared) {
  19384. if (!this._geometry) {
  19385. return [];
  19386. }
  19387. return this._geometry.getIndices(copyWhenShared);
  19388. };
  19389. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19390. get: function () {
  19391. return this._masterMesh !== null && this._masterMesh !== undefined;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. /**
  19397. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19398. */
  19399. Mesh.prototype.isReady = function () {
  19400. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19401. return false;
  19402. }
  19403. return _super.prototype.isReady.call(this);
  19404. };
  19405. /**
  19406. * Boolean : true if the mesh has been disposed.
  19407. */
  19408. Mesh.prototype.isDisposed = function () {
  19409. return this._isDisposed;
  19410. };
  19411. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19412. get: function () {
  19413. return this._sideOrientation;
  19414. },
  19415. /**
  19416. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19417. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19418. */
  19419. set: function (sideO) {
  19420. this._sideOrientation = sideO;
  19421. },
  19422. enumerable: true,
  19423. configurable: true
  19424. });
  19425. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19426. /**
  19427. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19428. * This property is pertinent only for updatable parametric shapes.
  19429. */
  19430. get: function () {
  19431. return this._areNormalsFrozen;
  19432. },
  19433. enumerable: true,
  19434. configurable: true
  19435. });
  19436. /**
  19437. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19438. * It has no effect at all on other shapes.
  19439. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19440. */
  19441. Mesh.prototype.freezeNormals = function () {
  19442. this._areNormalsFrozen = true;
  19443. };
  19444. /**
  19445. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19446. * It has no effect at all on other shapes.
  19447. * It reactivates the mesh normals computation if it was previously frozen.
  19448. */
  19449. Mesh.prototype.unfreezeNormals = function () {
  19450. this._areNormalsFrozen = false;
  19451. };
  19452. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19453. /**
  19454. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19455. */
  19456. set: function (count) {
  19457. this._overridenInstanceCount = count;
  19458. },
  19459. enumerable: true,
  19460. configurable: true
  19461. });
  19462. // Methods
  19463. Mesh.prototype._preActivate = function () {
  19464. var sceneRenderId = this.getScene().getRenderId();
  19465. if (this._preActivateId === sceneRenderId) {
  19466. return;
  19467. }
  19468. this._preActivateId = sceneRenderId;
  19469. this._visibleInstances = null;
  19470. };
  19471. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19472. if (this._visibleInstances) {
  19473. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19474. }
  19475. };
  19476. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19477. if (!this._visibleInstances) {
  19478. this._visibleInstances = {};
  19479. this._visibleInstances.defaultRenderId = renderId;
  19480. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19481. }
  19482. if (!this._visibleInstances[renderId]) {
  19483. this._visibleInstances[renderId] = new Array();
  19484. }
  19485. this._visibleInstances[renderId].push(instance);
  19486. };
  19487. /**
  19488. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19489. * This means the mesh underlying bounding box and sphere are recomputed.
  19490. */
  19491. Mesh.prototype.refreshBoundingInfo = function () {
  19492. if (this._boundingInfo.isLocked) {
  19493. return;
  19494. }
  19495. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19496. if (data) {
  19497. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19498. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19499. }
  19500. if (this.subMeshes) {
  19501. for (var index = 0; index < this.subMeshes.length; index++) {
  19502. this.subMeshes[index].refreshBoundingInfo();
  19503. }
  19504. }
  19505. this._updateBoundingInfo();
  19506. };
  19507. Mesh.prototype._createGlobalSubMesh = function () {
  19508. var totalVertices = this.getTotalVertices();
  19509. if (!totalVertices || !this.getIndices()) {
  19510. return null;
  19511. }
  19512. this.releaseSubMeshes();
  19513. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19514. };
  19515. Mesh.prototype.subdivide = function (count) {
  19516. if (count < 1) {
  19517. return;
  19518. }
  19519. var totalIndices = this.getTotalIndices();
  19520. var subdivisionSize = (totalIndices / count) | 0;
  19521. var offset = 0;
  19522. // Ensure that subdivisionSize is a multiple of 3
  19523. while (subdivisionSize % 3 !== 0) {
  19524. subdivisionSize++;
  19525. }
  19526. this.releaseSubMeshes();
  19527. for (var index = 0; index < count; index++) {
  19528. if (offset >= totalIndices) {
  19529. break;
  19530. }
  19531. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19532. offset += subdivisionSize;
  19533. }
  19534. this.synchronizeInstances();
  19535. };
  19536. /**
  19537. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19538. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19539. * The `data` are either a numeric array either a Float32Array.
  19540. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19541. * 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).
  19542. * Note that a new underlying VertexBuffer object is created each call.
  19543. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19544. *
  19545. * Possible `kind` values :
  19546. * - BABYLON.VertexBuffer.PositionKind
  19547. * - BABYLON.VertexBuffer.UVKind
  19548. * - BABYLON.VertexBuffer.UV2Kind
  19549. * - BABYLON.VertexBuffer.UV3Kind
  19550. * - BABYLON.VertexBuffer.UV4Kind
  19551. * - BABYLON.VertexBuffer.UV5Kind
  19552. * - BABYLON.VertexBuffer.UV6Kind
  19553. * - BABYLON.VertexBuffer.ColorKind
  19554. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19555. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19556. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19557. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19558. */
  19559. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19560. if (!this._geometry) {
  19561. var vertexData = new BABYLON.VertexData();
  19562. vertexData.set(data, kind);
  19563. var scene = this.getScene();
  19564. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19565. }
  19566. else {
  19567. this._geometry.setVerticesData(kind, data, updatable, stride);
  19568. }
  19569. };
  19570. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19571. if (!this._geometry) {
  19572. var scene = this.getScene();
  19573. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19574. }
  19575. this._geometry.setVerticesBuffer(buffer);
  19576. };
  19577. /**
  19578. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19579. * If the mesh has no geometry, it is simply returned as it is.
  19580. * The `data` are either a numeric array either a Float32Array.
  19581. * No new underlying VertexBuffer object is created.
  19582. * 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.
  19583. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19584. *
  19585. * Possible `kind` values :
  19586. * - BABYLON.VertexBuffer.PositionKind
  19587. * - BABYLON.VertexBuffer.UVKind
  19588. * - BABYLON.VertexBuffer.UV2Kind
  19589. * - BABYLON.VertexBuffer.UV3Kind
  19590. * - BABYLON.VertexBuffer.UV4Kind
  19591. * - BABYLON.VertexBuffer.UV5Kind
  19592. * - BABYLON.VertexBuffer.UV6Kind
  19593. * - BABYLON.VertexBuffer.ColorKind
  19594. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19595. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19596. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19597. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19598. */
  19599. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19600. if (!this._geometry) {
  19601. return;
  19602. }
  19603. if (!makeItUnique) {
  19604. this._geometry.updateVerticesData(kind, data, updateExtends);
  19605. }
  19606. else {
  19607. this.makeGeometryUnique();
  19608. this.updateVerticesData(kind, data, updateExtends, false);
  19609. }
  19610. };
  19611. /**
  19612. * Deprecated since BabylonJS v2.3
  19613. */
  19614. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19615. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19616. if (!this._geometry) {
  19617. return;
  19618. }
  19619. if (!makeItUnique) {
  19620. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19621. }
  19622. else {
  19623. this.makeGeometryUnique();
  19624. this.updateVerticesDataDirectly(kind, data, offset, false);
  19625. }
  19626. };
  19627. /**
  19628. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19629. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19630. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19631. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19632. */
  19633. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19634. if (computeNormals === void 0) { computeNormals = true; }
  19635. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19636. positionFunction(positions);
  19637. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19638. if (computeNormals) {
  19639. var indices = this.getIndices();
  19640. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19641. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19642. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19643. }
  19644. };
  19645. Mesh.prototype.makeGeometryUnique = function () {
  19646. if (!this._geometry) {
  19647. return;
  19648. }
  19649. var oldGeometry = this._geometry;
  19650. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19651. oldGeometry.releaseForMesh(this, true);
  19652. geometry.applyToMesh(this);
  19653. };
  19654. /**
  19655. * Sets the mesh indices.
  19656. * Expects an array populated with integers or a Int32Array.
  19657. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19658. * This method creates a new index buffer each call.
  19659. */
  19660. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19661. if (!this._geometry) {
  19662. var vertexData = new BABYLON.VertexData();
  19663. vertexData.indices = indices;
  19664. var scene = this.getScene();
  19665. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19666. }
  19667. else {
  19668. this._geometry.setIndices(indices, totalVertices);
  19669. }
  19670. };
  19671. /**
  19672. * Invert the geometry to move from a right handed system to a left handed one.
  19673. */
  19674. Mesh.prototype.toLeftHanded = function () {
  19675. if (!this._geometry) {
  19676. return;
  19677. }
  19678. this._geometry.toLeftHanded();
  19679. };
  19680. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19681. var engine = this.getScene().getEngine();
  19682. // Wireframe
  19683. var indexToBind;
  19684. if (this._unIndexed) {
  19685. indexToBind = null;
  19686. }
  19687. else {
  19688. switch (fillMode) {
  19689. case BABYLON.Material.PointFillMode:
  19690. indexToBind = null;
  19691. break;
  19692. case BABYLON.Material.WireFrameFillMode:
  19693. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19694. break;
  19695. default:
  19696. case BABYLON.Material.TriangleFillMode:
  19697. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19698. break;
  19699. }
  19700. }
  19701. // VBOs
  19702. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19703. };
  19704. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19705. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19706. return;
  19707. }
  19708. this.onBeforeDrawObservable.notifyObservers(this);
  19709. var engine = this.getScene().getEngine();
  19710. // Draw order
  19711. switch (fillMode) {
  19712. case BABYLON.Material.PointFillMode:
  19713. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19714. break;
  19715. case BABYLON.Material.WireFrameFillMode:
  19716. if (this._unIndexed) {
  19717. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19718. }
  19719. else {
  19720. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19721. }
  19722. break;
  19723. default:
  19724. if (this._unIndexed) {
  19725. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19726. }
  19727. else {
  19728. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19729. }
  19730. }
  19731. };
  19732. /**
  19733. * Registers for this mesh a javascript function called just before the rendering process.
  19734. * This function is passed the current mesh and doesn't return anything.
  19735. */
  19736. Mesh.prototype.registerBeforeRender = function (func) {
  19737. this.onBeforeRenderObservable.add(func);
  19738. };
  19739. /**
  19740. * Disposes a previously registered javascript function called before the rendering.
  19741. * This function is passed the current mesh and doesn't return anything.
  19742. */
  19743. Mesh.prototype.unregisterBeforeRender = function (func) {
  19744. this.onBeforeRenderObservable.removeCallback(func);
  19745. };
  19746. /**
  19747. * Registers for this mesh a javascript function called just after the rendering is complete.
  19748. * This function is passed the current mesh and doesn't return anything.
  19749. */
  19750. Mesh.prototype.registerAfterRender = function (func) {
  19751. this.onAfterRenderObservable.add(func);
  19752. };
  19753. /**
  19754. * Disposes a previously registered javascript function called after the rendering.
  19755. * This function is passed the current mesh and doesn't return anything.
  19756. */
  19757. Mesh.prototype.unregisterAfterRender = function (func) {
  19758. this.onAfterRenderObservable.removeCallback(func);
  19759. };
  19760. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19761. var scene = this.getScene();
  19762. this._batchCache.mustReturn = false;
  19763. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19764. this._batchCache.visibleInstances[subMeshId] = null;
  19765. if (this._visibleInstances) {
  19766. var currentRenderId = scene.getRenderId();
  19767. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19768. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19769. var selfRenderId = this._renderId;
  19770. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19771. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19772. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19773. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19774. }
  19775. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19776. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19777. this._batchCache.mustReturn = true;
  19778. return this._batchCache;
  19779. }
  19780. if (currentRenderId !== selfRenderId) {
  19781. this._batchCache.renderSelf[subMeshId] = false;
  19782. }
  19783. }
  19784. this._renderIdForInstances[subMeshId] = currentRenderId;
  19785. }
  19786. return this._batchCache;
  19787. };
  19788. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19789. var visibleInstances = batch.visibleInstances[subMesh._id];
  19790. var matricesCount = visibleInstances.length + 1;
  19791. var bufferSize = matricesCount * 16 * 4;
  19792. var currentInstancesBufferSize = this._instancesBufferSize;
  19793. var instancesBuffer = this._instancesBuffer;
  19794. while (this._instancesBufferSize < bufferSize) {
  19795. this._instancesBufferSize *= 2;
  19796. }
  19797. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19798. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19799. }
  19800. var offset = 0;
  19801. var instancesCount = 0;
  19802. var world = this.getWorldMatrix();
  19803. if (batch.renderSelf[subMesh._id]) {
  19804. world.copyToArray(this._instancesData, offset);
  19805. offset += 16;
  19806. instancesCount++;
  19807. }
  19808. if (visibleInstances) {
  19809. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19810. var instance = visibleInstances[instanceIndex];
  19811. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19812. offset += 16;
  19813. instancesCount++;
  19814. }
  19815. }
  19816. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19817. if (instancesBuffer) {
  19818. instancesBuffer.dispose();
  19819. }
  19820. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19821. this._instancesBuffer = instancesBuffer;
  19822. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19823. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19824. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19825. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19826. }
  19827. else {
  19828. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19829. }
  19830. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  19831. this._draw(subMesh, fillMode, instancesCount);
  19832. engine.unbindInstanceAttributes();
  19833. };
  19834. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19835. var scene = this.getScene();
  19836. var engine = scene.getEngine();
  19837. if (hardwareInstancedRendering) {
  19838. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19839. }
  19840. else {
  19841. if (batch.renderSelf[subMesh._id]) {
  19842. // Draw
  19843. if (onBeforeDraw) {
  19844. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19845. }
  19846. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19847. }
  19848. if (batch.visibleInstances[subMesh._id]) {
  19849. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19850. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19851. // World
  19852. var world = instance.getWorldMatrix();
  19853. if (onBeforeDraw) {
  19854. onBeforeDraw(true, world, effectiveMaterial);
  19855. }
  19856. // Draw
  19857. this._draw(subMesh, fillMode);
  19858. }
  19859. }
  19860. }
  19861. };
  19862. /**
  19863. * Triggers the draw call for the mesh.
  19864. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19865. */
  19866. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19867. var scene = this.getScene();
  19868. // Managing instances
  19869. var batch = this._getInstancesRenderList(subMesh._id);
  19870. if (batch.mustReturn) {
  19871. return;
  19872. }
  19873. // Checking geometry state
  19874. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19875. return;
  19876. }
  19877. var callbackIndex;
  19878. this.onBeforeRenderObservable.notifyObservers(this);
  19879. var engine = scene.getEngine();
  19880. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19881. // Material
  19882. var effectiveMaterial = subMesh.getMaterial();
  19883. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19884. return;
  19885. }
  19886. // Outline - step 1
  19887. var savedDepthWrite = engine.getDepthWrite();
  19888. if (this.renderOutline) {
  19889. engine.setDepthWrite(false);
  19890. scene.getOutlineRenderer().render(subMesh, batch);
  19891. engine.setDepthWrite(savedDepthWrite);
  19892. }
  19893. effectiveMaterial._preBind();
  19894. var effect = effectiveMaterial.getEffect();
  19895. // Bind
  19896. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19897. this._bind(subMesh, effect, fillMode);
  19898. var world = this.getWorldMatrix();
  19899. effectiveMaterial.bind(world, this);
  19900. // Alpha mode
  19901. if (enableAlphaMode) {
  19902. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19903. }
  19904. // Draw
  19905. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  19906. // Unbind
  19907. effectiveMaterial.unbind();
  19908. // Outline - step 2
  19909. if (this.renderOutline && savedDepthWrite) {
  19910. engine.setDepthWrite(true);
  19911. engine.setColorWrite(false);
  19912. scene.getOutlineRenderer().render(subMesh, batch);
  19913. engine.setColorWrite(true);
  19914. }
  19915. // Overlay
  19916. if (this.renderOverlay) {
  19917. var currentMode = engine.getAlphaMode();
  19918. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19919. scene.getOutlineRenderer().render(subMesh, batch, true);
  19920. engine.setAlphaMode(currentMode);
  19921. }
  19922. this.onAfterRenderObservable.notifyObservers(this);
  19923. };
  19924. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19925. if (isInstance) {
  19926. effectiveMaterial.bindOnlyWorldMatrix(world);
  19927. }
  19928. };
  19929. /**
  19930. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19931. */
  19932. Mesh.prototype.getEmittedParticleSystems = function () {
  19933. var results = new Array();
  19934. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19935. var particleSystem = this.getScene().particleSystems[index];
  19936. if (particleSystem.emitter === this) {
  19937. results.push(particleSystem);
  19938. }
  19939. }
  19940. return results;
  19941. };
  19942. /**
  19943. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19944. */
  19945. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19946. var results = new Array();
  19947. var descendants = this.getDescendants();
  19948. descendants.push(this);
  19949. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19950. var particleSystem = this.getScene().particleSystems[index];
  19951. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19952. results.push(particleSystem);
  19953. }
  19954. }
  19955. return results;
  19956. };
  19957. Mesh.prototype._checkDelayState = function () {
  19958. var scene = this.getScene();
  19959. if (this._geometry) {
  19960. this._geometry.load(scene);
  19961. }
  19962. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19963. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19964. this._queueLoad(this, scene);
  19965. }
  19966. };
  19967. Mesh.prototype._queueLoad = function (mesh, scene) {
  19968. var _this = this;
  19969. scene._addPendingData(mesh);
  19970. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19971. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19972. if (data instanceof ArrayBuffer) {
  19973. _this._delayLoadingFunction(data, _this);
  19974. }
  19975. else {
  19976. _this._delayLoadingFunction(JSON.parse(data), _this);
  19977. }
  19978. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19979. scene._removePendingData(_this);
  19980. }, function () { }, scene.database, getBinaryData);
  19981. };
  19982. /**
  19983. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19984. */
  19985. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19986. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19987. return false;
  19988. }
  19989. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19990. return false;
  19991. }
  19992. this._checkDelayState();
  19993. return true;
  19994. };
  19995. /**
  19996. * Sets the mesh material by the material or multiMaterial `id` property.
  19997. * The material `id` is a string identifying the material or the multiMaterial.
  19998. * This method returns nothing.
  19999. */
  20000. Mesh.prototype.setMaterialByID = function (id) {
  20001. var materials = this.getScene().materials;
  20002. var index;
  20003. for (index = 0; index < materials.length; index++) {
  20004. if (materials[index].id === id) {
  20005. this.material = materials[index];
  20006. return;
  20007. }
  20008. }
  20009. // Multi
  20010. var multiMaterials = this.getScene().multiMaterials;
  20011. for (index = 0; index < multiMaterials.length; index++) {
  20012. if (multiMaterials[index].id === id) {
  20013. this.material = multiMaterials[index];
  20014. return;
  20015. }
  20016. }
  20017. };
  20018. /**
  20019. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20020. */
  20021. Mesh.prototype.getAnimatables = function () {
  20022. var results = [];
  20023. if (this.material) {
  20024. results.push(this.material);
  20025. }
  20026. if (this.skeleton) {
  20027. results.push(this.skeleton);
  20028. }
  20029. return results;
  20030. };
  20031. /**
  20032. * Modifies the mesh geometry according to the passed transformation matrix.
  20033. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20034. * The mesh normals are modified accordingly the same transformation.
  20035. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20036. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20037. */
  20038. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20039. // Position
  20040. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20041. return;
  20042. }
  20043. var submeshes = this.subMeshes.splice(0);
  20044. this._resetPointsArrayCache();
  20045. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20046. var temp = [];
  20047. var index;
  20048. for (index = 0; index < data.length; index += 3) {
  20049. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20050. }
  20051. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20052. // Normals
  20053. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20054. return;
  20055. }
  20056. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20057. temp = [];
  20058. for (index = 0; index < data.length; index += 3) {
  20059. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20060. }
  20061. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20062. // flip faces?
  20063. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20064. this.flipFaces();
  20065. }
  20066. // Restore submeshes
  20067. this.releaseSubMeshes();
  20068. this.subMeshes = submeshes;
  20069. };
  20070. /**
  20071. * Modifies the mesh geometry according to its own current World Matrix.
  20072. * The mesh World Matrix is then reset.
  20073. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20074. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20075. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20076. */
  20077. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20078. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20079. this.scaling.copyFromFloats(1, 1, 1);
  20080. this.position.copyFromFloats(0, 0, 0);
  20081. this.rotation.copyFromFloats(0, 0, 0);
  20082. //only if quaternion is already set
  20083. if (this.rotationQuaternion) {
  20084. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20085. }
  20086. this._worldMatrix = BABYLON.Matrix.Identity();
  20087. };
  20088. // Cache
  20089. Mesh.prototype._resetPointsArrayCache = function () {
  20090. this._positions = null;
  20091. };
  20092. Mesh.prototype._generatePointsArray = function () {
  20093. if (this._positions)
  20094. return true;
  20095. this._positions = [];
  20096. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20097. if (!data) {
  20098. return false;
  20099. }
  20100. for (var index = 0; index < data.length; index += 3) {
  20101. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20102. }
  20103. return true;
  20104. };
  20105. /**
  20106. * Returns a new Mesh object generated from the current mesh properties.
  20107. * This method must not get confused with createInstance().
  20108. * The parameter `name` is a string, the name given to the new mesh.
  20109. * The optional parameter `newParent` can be any Node object (default `null`).
  20110. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20111. * 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.
  20112. */
  20113. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20114. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20115. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20116. };
  20117. /**
  20118. * Disposes the mesh.
  20119. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20120. */
  20121. Mesh.prototype.dispose = function (doNotRecurse) {
  20122. if (this._geometry) {
  20123. this._geometry.releaseForMesh(this, true);
  20124. }
  20125. // Instances
  20126. if (this._instancesBuffer) {
  20127. this._instancesBuffer.dispose();
  20128. this._instancesBuffer = null;
  20129. }
  20130. while (this.instances.length) {
  20131. this.instances[0].dispose();
  20132. }
  20133. // Highlight layers.
  20134. var highlightLayers = this.getScene().highlightLayers;
  20135. for (var i = 0; i < highlightLayers.length; i++) {
  20136. var highlightLayer = highlightLayers[i];
  20137. if (highlightLayer) {
  20138. highlightLayer.removeMesh(this);
  20139. highlightLayer.removeExcludedMesh(this);
  20140. }
  20141. }
  20142. _super.prototype.dispose.call(this, doNotRecurse);
  20143. };
  20144. /**
  20145. * Modifies the mesh geometry according to a displacement map.
  20146. * 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.
  20147. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20148. * This method returns nothing.
  20149. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20150. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20151. * 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.
  20152. */
  20153. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20154. var _this = this;
  20155. var scene = this.getScene();
  20156. var onload = function (img) {
  20157. // Getting height map data
  20158. var canvas = document.createElement("canvas");
  20159. var context = canvas.getContext("2d");
  20160. var heightMapWidth = img.width;
  20161. var heightMapHeight = img.height;
  20162. canvas.width = heightMapWidth;
  20163. canvas.height = heightMapHeight;
  20164. context.drawImage(img, 0, 0);
  20165. // Create VertexData from map data
  20166. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20167. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20168. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20169. //execute success callback, if set
  20170. if (onSuccess) {
  20171. onSuccess(_this);
  20172. }
  20173. };
  20174. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20175. };
  20176. /**
  20177. * Modifies the mesh geometry according to a displacementMap buffer.
  20178. * 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.
  20179. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20180. * This method returns nothing.
  20181. * 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.
  20182. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20183. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20184. */
  20185. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20186. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20187. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20188. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20189. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20190. return;
  20191. }
  20192. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20193. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20194. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20195. var position = BABYLON.Vector3.Zero();
  20196. var normal = BABYLON.Vector3.Zero();
  20197. var uv = BABYLON.Vector2.Zero();
  20198. for (var index = 0; index < positions.length; index += 3) {
  20199. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20200. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20201. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20202. // Compute height
  20203. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20204. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20205. var pos = (u + v * heightMapWidth) * 4;
  20206. var r = buffer[pos] / 255.0;
  20207. var g = buffer[pos + 1] / 255.0;
  20208. var b = buffer[pos + 2] / 255.0;
  20209. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20210. normal.normalize();
  20211. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20212. position = position.add(normal);
  20213. position.toArray(positions, index);
  20214. }
  20215. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20216. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20217. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20218. };
  20219. /**
  20220. * Modify the mesh to get a flat shading rendering.
  20221. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20222. * This method returns nothing.
  20223. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20224. */
  20225. Mesh.prototype.convertToFlatShadedMesh = function () {
  20226. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20227. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20228. var kinds = this.getVerticesDataKinds();
  20229. var vbs = [];
  20230. var data = [];
  20231. var newdata = [];
  20232. var updatableNormals = false;
  20233. var kindIndex;
  20234. var kind;
  20235. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20236. kind = kinds[kindIndex];
  20237. var vertexBuffer = this.getVertexBuffer(kind);
  20238. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20239. updatableNormals = vertexBuffer.isUpdatable();
  20240. kinds.splice(kindIndex, 1);
  20241. kindIndex--;
  20242. continue;
  20243. }
  20244. vbs[kind] = vertexBuffer;
  20245. data[kind] = vbs[kind].getData();
  20246. newdata[kind] = [];
  20247. }
  20248. // Save previous submeshes
  20249. var previousSubmeshes = this.subMeshes.slice(0);
  20250. var indices = this.getIndices();
  20251. var totalIndices = this.getTotalIndices();
  20252. // Generating unique vertices per face
  20253. var index;
  20254. for (index = 0; index < totalIndices; index++) {
  20255. var vertexIndex = indices[index];
  20256. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20257. kind = kinds[kindIndex];
  20258. var stride = vbs[kind].getStrideSize();
  20259. for (var offset = 0; offset < stride; offset++) {
  20260. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20261. }
  20262. }
  20263. }
  20264. // Updating faces & normal
  20265. var normals = [];
  20266. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20267. for (index = 0; index < totalIndices; index += 3) {
  20268. indices[index] = index;
  20269. indices[index + 1] = index + 1;
  20270. indices[index + 2] = index + 2;
  20271. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20272. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20273. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20274. var p1p2 = p1.subtract(p2);
  20275. var p3p2 = p3.subtract(p2);
  20276. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20277. // Store same normals for every vertex
  20278. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20279. normals.push(normal.x);
  20280. normals.push(normal.y);
  20281. normals.push(normal.z);
  20282. }
  20283. }
  20284. this.setIndices(indices);
  20285. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20286. // Updating vertex buffers
  20287. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20288. kind = kinds[kindIndex];
  20289. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20290. }
  20291. // Updating submeshes
  20292. this.releaseSubMeshes();
  20293. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20294. var previousOne = previousSubmeshes[submeshIndex];
  20295. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20296. }
  20297. this.synchronizeInstances();
  20298. };
  20299. /**
  20300. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20301. * In other words, more vertices, no more indices and a single bigger VBO.
  20302. * This method returns nothing.
  20303. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20304. *
  20305. */
  20306. Mesh.prototype.convertToUnIndexedMesh = function () {
  20307. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20308. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20309. var kinds = this.getVerticesDataKinds();
  20310. var vbs = [];
  20311. var data = [];
  20312. var newdata = [];
  20313. var updatableNormals = false;
  20314. var kindIndex;
  20315. var kind;
  20316. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20317. kind = kinds[kindIndex];
  20318. var vertexBuffer = this.getVertexBuffer(kind);
  20319. vbs[kind] = vertexBuffer;
  20320. data[kind] = vbs[kind].getData();
  20321. newdata[kind] = [];
  20322. }
  20323. // Save previous submeshes
  20324. var previousSubmeshes = this.subMeshes.slice(0);
  20325. var indices = this.getIndices();
  20326. var totalIndices = this.getTotalIndices();
  20327. // Generating unique vertices per face
  20328. var index;
  20329. for (index = 0; index < totalIndices; index++) {
  20330. var vertexIndex = indices[index];
  20331. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20332. kind = kinds[kindIndex];
  20333. var stride = vbs[kind].getStrideSize();
  20334. for (var offset = 0; offset < stride; offset++) {
  20335. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20336. }
  20337. }
  20338. }
  20339. // Updating indices
  20340. for (index = 0; index < totalIndices; index += 3) {
  20341. indices[index] = index;
  20342. indices[index + 1] = index + 1;
  20343. indices[index + 2] = index + 2;
  20344. }
  20345. this.setIndices(indices);
  20346. // Updating vertex buffers
  20347. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20348. kind = kinds[kindIndex];
  20349. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20350. }
  20351. // Updating submeshes
  20352. this.releaseSubMeshes();
  20353. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20354. var previousOne = previousSubmeshes[submeshIndex];
  20355. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20356. }
  20357. this._unIndexed = true;
  20358. this.synchronizeInstances();
  20359. };
  20360. /**
  20361. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20362. * This method returns nothing.
  20363. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20364. */
  20365. Mesh.prototype.flipFaces = function (flipNormals) {
  20366. if (flipNormals === void 0) { flipNormals = false; }
  20367. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20368. var i;
  20369. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20370. for (i = 0; i < vertex_data.normals.length; i++) {
  20371. vertex_data.normals[i] *= -1;
  20372. }
  20373. }
  20374. var temp;
  20375. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20376. // reassign indices
  20377. temp = vertex_data.indices[i + 1];
  20378. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20379. vertex_data.indices[i + 2] = temp;
  20380. }
  20381. vertex_data.applyToMesh(this);
  20382. };
  20383. // Instances
  20384. /**
  20385. * Creates a new InstancedMesh object from the mesh model.
  20386. * An instance shares the same properties and the same material than its model.
  20387. * Only these properties of each instance can then be set individually :
  20388. * - position
  20389. * - rotation
  20390. * - rotationQuaternion
  20391. * - setPivotMatrix
  20392. * - scaling
  20393. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20394. * Warning : this method is not supported for Line mesh and LineSystem
  20395. */
  20396. Mesh.prototype.createInstance = function (name) {
  20397. return new BABYLON.InstancedMesh(name, this);
  20398. };
  20399. /**
  20400. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20401. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20402. * This method returns nothing.
  20403. */
  20404. Mesh.prototype.synchronizeInstances = function () {
  20405. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20406. var instance = this.instances[instanceIndex];
  20407. instance._syncSubMeshes();
  20408. }
  20409. };
  20410. /**
  20411. * Simplify the mesh according to the given array of settings.
  20412. * Function will return immediately and will simplify async. It returns nothing.
  20413. * @param settings a collection of simplification settings.
  20414. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20415. * @param type the type of simplification to run.
  20416. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20417. */
  20418. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20419. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20420. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20421. this.getScene().simplificationQueue.addTask({
  20422. settings: settings,
  20423. parallelProcessing: parallelProcessing,
  20424. mesh: this,
  20425. simplificationType: simplificationType,
  20426. successCallback: successCallback
  20427. });
  20428. };
  20429. /**
  20430. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20431. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20432. * This should be used together with the simplification to avoid disappearing triangles.
  20433. * @param successCallback an optional success callback to be called after the optimization finished.
  20434. */
  20435. Mesh.prototype.optimizeIndices = function (successCallback) {
  20436. var _this = this;
  20437. var indices = this.getIndices();
  20438. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20439. var vectorPositions = [];
  20440. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20441. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20442. }
  20443. var dupes = [];
  20444. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20445. var realPos = vectorPositions.length - 1 - iteration;
  20446. var testedPosition = vectorPositions[realPos];
  20447. for (var j = 0; j < realPos; ++j) {
  20448. var againstPosition = vectorPositions[j];
  20449. if (testedPosition.equals(againstPosition)) {
  20450. dupes[realPos] = j;
  20451. break;
  20452. }
  20453. }
  20454. }, function () {
  20455. for (var i = 0; i < indices.length; ++i) {
  20456. indices[i] = dupes[indices[i]] || indices[i];
  20457. }
  20458. //indices are now reordered
  20459. var originalSubMeshes = _this.subMeshes.slice(0);
  20460. _this.setIndices(indices);
  20461. _this.subMeshes = originalSubMeshes;
  20462. if (successCallback) {
  20463. successCallback(_this);
  20464. }
  20465. });
  20466. };
  20467. // Statics
  20468. /**
  20469. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20470. * The parameter `parsedMesh` is the mesh to be copied.
  20471. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20472. */
  20473. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20474. var mesh = new Mesh(parsedMesh.name, scene);
  20475. mesh.id = parsedMesh.id;
  20476. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20477. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20478. if (parsedMesh.rotationQuaternion) {
  20479. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20480. }
  20481. else if (parsedMesh.rotation) {
  20482. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20483. }
  20484. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20485. if (parsedMesh.localMatrix) {
  20486. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20487. }
  20488. else if (parsedMesh.pivotMatrix) {
  20489. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20490. }
  20491. mesh.setEnabled(parsedMesh.isEnabled);
  20492. mesh.isVisible = parsedMesh.isVisible;
  20493. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20494. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20495. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20496. if (parsedMesh.applyFog !== undefined) {
  20497. mesh.applyFog = parsedMesh.applyFog;
  20498. }
  20499. if (parsedMesh.pickable !== undefined) {
  20500. mesh.isPickable = parsedMesh.pickable;
  20501. }
  20502. if (parsedMesh.alphaIndex !== undefined) {
  20503. mesh.alphaIndex = parsedMesh.alphaIndex;
  20504. }
  20505. mesh.receiveShadows = parsedMesh.receiveShadows;
  20506. mesh.billboardMode = parsedMesh.billboardMode;
  20507. if (parsedMesh.visibility !== undefined) {
  20508. mesh.visibility = parsedMesh.visibility;
  20509. }
  20510. mesh.checkCollisions = parsedMesh.checkCollisions;
  20511. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20512. // freezeWorldMatrix
  20513. if (parsedMesh.freezeWorldMatrix) {
  20514. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20515. }
  20516. // Parent
  20517. if (parsedMesh.parentId) {
  20518. mesh._waitingParentId = parsedMesh.parentId;
  20519. }
  20520. // Actions
  20521. if (parsedMesh.actions !== undefined) {
  20522. mesh._waitingActions = parsedMesh.actions;
  20523. }
  20524. // Geometry
  20525. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20526. if (parsedMesh.delayLoadingFile) {
  20527. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20528. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20529. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20530. if (parsedMesh._binaryInfo) {
  20531. mesh._binaryInfo = parsedMesh._binaryInfo;
  20532. }
  20533. mesh._delayInfo = [];
  20534. if (parsedMesh.hasUVs) {
  20535. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20536. }
  20537. if (parsedMesh.hasUVs2) {
  20538. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20539. }
  20540. if (parsedMesh.hasUVs3) {
  20541. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20542. }
  20543. if (parsedMesh.hasUVs4) {
  20544. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20545. }
  20546. if (parsedMesh.hasUVs5) {
  20547. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20548. }
  20549. if (parsedMesh.hasUVs6) {
  20550. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20551. }
  20552. if (parsedMesh.hasColors) {
  20553. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20554. }
  20555. if (parsedMesh.hasMatricesIndices) {
  20556. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20557. }
  20558. if (parsedMesh.hasMatricesWeights) {
  20559. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20560. }
  20561. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20562. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20563. mesh._checkDelayState();
  20564. }
  20565. }
  20566. else {
  20567. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20568. }
  20569. // Material
  20570. if (parsedMesh.materialId) {
  20571. mesh.setMaterialByID(parsedMesh.materialId);
  20572. }
  20573. else {
  20574. mesh.material = null;
  20575. }
  20576. // Skeleton
  20577. if (parsedMesh.skeletonId > -1) {
  20578. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20579. if (parsedMesh.numBoneInfluencers) {
  20580. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20581. }
  20582. }
  20583. // Animations
  20584. if (parsedMesh.animations) {
  20585. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20586. var parsedAnimation = parsedMesh.animations[animationIndex];
  20587. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20588. }
  20589. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20590. }
  20591. if (parsedMesh.autoAnimate) {
  20592. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20593. }
  20594. // Layer Mask
  20595. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20596. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20597. }
  20598. else {
  20599. mesh.layerMask = 0x0FFFFFFF;
  20600. }
  20601. //(Deprecated) physics
  20602. if (parsedMesh.physicsImpostor) {
  20603. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20604. mass: parsedMesh.physicsMass,
  20605. friction: parsedMesh.physicsFriction,
  20606. restitution: parsedMesh.physicsRestitution
  20607. }, scene);
  20608. }
  20609. // Instances
  20610. if (parsedMesh.instances) {
  20611. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20612. var parsedInstance = parsedMesh.instances[index];
  20613. var instance = mesh.createInstance(parsedInstance.name);
  20614. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20615. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20616. if (parsedInstance.parentId) {
  20617. instance._waitingParentId = parsedInstance.parentId;
  20618. }
  20619. if (parsedInstance.rotationQuaternion) {
  20620. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20621. }
  20622. else if (parsedInstance.rotation) {
  20623. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20624. }
  20625. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20626. instance.checkCollisions = mesh.checkCollisions;
  20627. if (parsedMesh.animations) {
  20628. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20629. parsedAnimation = parsedMesh.animations[animationIndex];
  20630. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20631. }
  20632. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20633. }
  20634. }
  20635. }
  20636. return mesh;
  20637. };
  20638. /**
  20639. * Creates a ribbon mesh.
  20640. * Please consider using the same method from the MeshBuilder class instead.
  20641. * 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.
  20642. *
  20643. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20644. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20645. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20646. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20647. * 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.
  20648. * 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.
  20649. * 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
  20650. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20651. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20652. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20653. */
  20654. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20655. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20656. pathArray: pathArray,
  20657. closeArray: closeArray,
  20658. closePath: closePath,
  20659. offset: offset,
  20660. updatable: updatable,
  20661. sideOrientation: sideOrientation,
  20662. instance: instance
  20663. }, scene);
  20664. };
  20665. /**
  20666. * Creates a plane polygonal mesh. By default, this is a disc.
  20667. * Please consider using the same method from the MeshBuilder class instead.
  20668. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20669. * 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.
  20670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20671. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20672. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20673. */
  20674. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20675. var options = {
  20676. radius: radius,
  20677. tessellation: tessellation,
  20678. sideOrientation: sideOrientation,
  20679. updatable: updatable
  20680. };
  20681. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20682. };
  20683. /**
  20684. * Creates a box mesh.
  20685. * Please consider using the same method from the MeshBuilder class instead.
  20686. * The parameter `size` sets the size (float) of each box side (default 1).
  20687. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20688. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20690. */
  20691. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20692. var options = {
  20693. size: size,
  20694. sideOrientation: sideOrientation,
  20695. updatable: updatable
  20696. };
  20697. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20698. };
  20699. /**
  20700. * Creates a sphere mesh.
  20701. * Please consider using the same method from the MeshBuilder class instead.
  20702. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20703. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20704. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20705. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20706. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20707. */
  20708. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20709. var options = {
  20710. segments: segments,
  20711. diameterX: diameter,
  20712. diameterY: diameter,
  20713. diameterZ: diameter,
  20714. sideOrientation: sideOrientation,
  20715. updatable: updatable
  20716. };
  20717. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20718. };
  20719. /**
  20720. * Creates a cylinder or a cone mesh.
  20721. * Please consider using the same method from the MeshBuilder class instead.
  20722. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20723. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20724. * 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.
  20725. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20726. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20727. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20728. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20730. */
  20731. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20732. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20733. if (scene !== undefined) {
  20734. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20735. updatable = scene;
  20736. }
  20737. scene = subdivisions;
  20738. subdivisions = 1;
  20739. }
  20740. var options = {
  20741. height: height,
  20742. diameterTop: diameterTop,
  20743. diameterBottom: diameterBottom,
  20744. tessellation: tessellation,
  20745. subdivisions: subdivisions,
  20746. sideOrientation: sideOrientation,
  20747. updatable: updatable
  20748. };
  20749. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20750. };
  20751. // Torus (Code from SharpDX.org)
  20752. /**
  20753. * Creates a torus mesh.
  20754. * Please consider using the same method from the MeshBuilder class instead.
  20755. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20756. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20757. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20758. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20759. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20761. */
  20762. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20763. var options = {
  20764. diameter: diameter,
  20765. thickness: thickness,
  20766. tessellation: tessellation,
  20767. sideOrientation: sideOrientation,
  20768. updatable: updatable
  20769. };
  20770. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20771. };
  20772. /**
  20773. * Creates a torus knot mesh.
  20774. * Please consider using the same method from the MeshBuilder class instead.
  20775. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20776. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20777. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20778. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20779. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20780. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20781. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20782. */
  20783. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20784. var options = {
  20785. radius: radius,
  20786. tube: tube,
  20787. radialSegments: radialSegments,
  20788. tubularSegments: tubularSegments,
  20789. p: p,
  20790. q: q,
  20791. sideOrientation: sideOrientation,
  20792. updatable: updatable
  20793. };
  20794. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20795. };
  20796. /**
  20797. * Creates a line mesh.
  20798. * Please consider using the same method from the MeshBuilder class instead.
  20799. * 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.
  20800. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20801. * The parameter `points` is an array successive Vector3.
  20802. * 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
  20803. * When updating an instance, remember that only point positions can change, not the number of points.
  20804. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20805. */
  20806. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20807. var options = {
  20808. points: points,
  20809. updatable: updatable,
  20810. instance: instance
  20811. };
  20812. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20813. };
  20814. /**
  20815. * Creates a dashed line mesh.
  20816. * Please consider using the same method from the MeshBuilder class instead.
  20817. * 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.
  20818. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20819. * The parameter `points` is an array successive Vector3.
  20820. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20821. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20822. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20823. * 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
  20824. * When updating an instance, remember that only point positions can change, not the number of points.
  20825. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20826. */
  20827. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20828. var options = {
  20829. points: points,
  20830. dashSize: dashSize,
  20831. gapSize: gapSize,
  20832. dashNb: dashNb,
  20833. updatable: updatable,
  20834. instance: instance
  20835. };
  20836. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20837. };
  20838. /**
  20839. * Creates an extruded shape mesh.
  20840. * 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.
  20841. * Please consider using the same method from the MeshBuilder class instead.
  20842. *
  20843. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20844. * 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
  20845. * extruded along the Z axis.
  20846. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20847. * 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.
  20848. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20849. * 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
  20850. * 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
  20851. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20852. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20853. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20854. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20855. */
  20856. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20857. var options = {
  20858. shape: shape,
  20859. path: path,
  20860. scale: scale,
  20861. rotation: rotation,
  20862. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20863. sideOrientation: sideOrientation,
  20864. instance: instance,
  20865. updatable: updatable
  20866. };
  20867. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20868. };
  20869. /**
  20870. * Creates an custom extruded shape mesh.
  20871. * 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.
  20872. * Please consider using the same method from the MeshBuilder class instead.
  20873. *
  20874. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20875. * 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
  20876. * extruded along the Z axis.
  20877. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20878. * 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
  20879. * and the distance of this point from the begining of the path :
  20880. * ```javascript
  20881. * var rotationFunction = function(i, distance) {
  20882. * // do things
  20883. * return rotationValue; }
  20884. * ```
  20885. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20886. * 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
  20887. * and the distance of this point from the begining of the path :
  20888. * ```javascript
  20889. * var scaleFunction = function(i, distance) {
  20890. * // do things
  20891. * return scaleValue;}
  20892. * ```
  20893. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20894. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20895. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20896. * 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
  20897. * 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
  20898. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20902. */
  20903. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20904. var options = {
  20905. shape: shape,
  20906. path: path,
  20907. scaleFunction: scaleFunction,
  20908. rotationFunction: rotationFunction,
  20909. ribbonCloseArray: ribbonCloseArray,
  20910. ribbonClosePath: ribbonClosePath,
  20911. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20912. sideOrientation: sideOrientation,
  20913. instance: instance,
  20914. updatable: updatable
  20915. };
  20916. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20917. };
  20918. /**
  20919. * Creates lathe mesh.
  20920. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20921. * Please consider using the same method from the MeshBuilder class instead.
  20922. * 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
  20923. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20924. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20925. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20926. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20927. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20928. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20929. */
  20930. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20931. var options = {
  20932. shape: shape,
  20933. radius: radius,
  20934. tessellation: tessellation,
  20935. sideOrientation: sideOrientation,
  20936. updatable: updatable
  20937. };
  20938. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20939. };
  20940. /**
  20941. * Creates a plane mesh.
  20942. * Please consider using the same method from the MeshBuilder class instead.
  20943. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20944. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20945. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20947. */
  20948. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20949. var options = {
  20950. size: size,
  20951. width: size,
  20952. height: size,
  20953. sideOrientation: sideOrientation,
  20954. updatable: updatable
  20955. };
  20956. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20957. };
  20958. /**
  20959. * Creates a ground mesh.
  20960. * Please consider using the same method from the MeshBuilder class instead.
  20961. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20962. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20963. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20964. */
  20965. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20966. var options = {
  20967. width: width,
  20968. height: height,
  20969. subdivisions: subdivisions,
  20970. updatable: updatable
  20971. };
  20972. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20973. };
  20974. /**
  20975. * Creates a tiled ground mesh.
  20976. * Please consider using the same method from the MeshBuilder class instead.
  20977. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20978. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20979. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20980. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20981. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20982. * numbers of subdivisions on the ground width and height of each tile.
  20983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20984. */
  20985. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20986. var options = {
  20987. xmin: xmin,
  20988. zmin: zmin,
  20989. xmax: xmax,
  20990. zmax: zmax,
  20991. subdivisions: subdivisions,
  20992. precision: precision,
  20993. updatable: updatable
  20994. };
  20995. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20996. };
  20997. /**
  20998. * Creates a ground mesh from a height map.
  20999. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21000. * Please consider using the same method from the MeshBuilder class instead.
  21001. * The parameter `url` sets the URL of the height map image resource.
  21002. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21003. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21004. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21005. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21006. * 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).
  21007. * This function is passed the newly built mesh :
  21008. * ```javascript
  21009. * function(mesh) { // do things
  21010. * return; }
  21011. * ```
  21012. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21013. */
  21014. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21015. var options = {
  21016. width: width,
  21017. height: height,
  21018. subdivisions: subdivisions,
  21019. minHeight: minHeight,
  21020. maxHeight: maxHeight,
  21021. updatable: updatable,
  21022. onReady: onReady
  21023. };
  21024. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21025. };
  21026. /**
  21027. * Creates a tube mesh.
  21028. * 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.
  21029. * Please consider using the same method from the MeshBuilder class instead.
  21030. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21031. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21032. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21033. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21034. * 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.
  21035. * It must return a radius value (positive float) :
  21036. * ```javascript
  21037. * var radiusFunction = function(i, distance) {
  21038. * // do things
  21039. * return radius; }
  21040. * ```
  21041. * 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
  21042. * 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
  21043. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21044. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21046. */
  21047. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21048. var options = {
  21049. path: path,
  21050. radius: radius,
  21051. tessellation: tessellation,
  21052. radiusFunction: radiusFunction,
  21053. arc: 1,
  21054. cap: cap,
  21055. updatable: updatable,
  21056. sideOrientation: sideOrientation,
  21057. instance: instance
  21058. };
  21059. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21060. };
  21061. /**
  21062. * Creates a polyhedron mesh.
  21063. * Please consider using the same method from the MeshBuilder class instead.
  21064. * 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
  21065. * to choose the wanted type.
  21066. * The parameter `size` (positive float, default 1) sets the polygon size.
  21067. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21068. * 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`.
  21069. * 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
  21070. * 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)`).
  21071. * 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
  21072. * 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.
  21073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21074. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21076. */
  21077. Mesh.CreatePolyhedron = function (name, options, scene) {
  21078. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21079. };
  21080. /**
  21081. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21082. * Please consider using the same method from the MeshBuilder class instead.
  21083. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21084. * 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`).
  21085. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21086. * 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.
  21087. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21088. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21090. */
  21091. Mesh.CreateIcoSphere = function (name, options, scene) {
  21092. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21093. };
  21094. /**
  21095. * Creates a decal mesh.
  21096. * Please consider using the same method from the MeshBuilder class instead.
  21097. * 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.
  21098. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21099. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21100. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21101. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21102. */
  21103. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21104. var options = {
  21105. position: position,
  21106. normal: normal,
  21107. size: size,
  21108. angle: angle
  21109. };
  21110. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21111. };
  21112. // Skeletons
  21113. /**
  21114. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21115. */
  21116. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21117. var source;
  21118. if (!this._sourcePositions) {
  21119. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21120. this._sourcePositions = new Float32Array(source);
  21121. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21122. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21123. }
  21124. }
  21125. return this._sourcePositions;
  21126. };
  21127. /**
  21128. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21129. */
  21130. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21131. var source;
  21132. if (!this._sourceNormals) {
  21133. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21134. this._sourceNormals = new Float32Array(source);
  21135. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21136. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21137. }
  21138. }
  21139. return this._sourceNormals;
  21140. };
  21141. /**
  21142. * Update the vertex buffers by applying transformation from the bones
  21143. * @param {skeleton} skeleton to apply
  21144. */
  21145. Mesh.prototype.applySkeleton = function (skeleton) {
  21146. if (!this.geometry) {
  21147. return;
  21148. }
  21149. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21150. return;
  21151. }
  21152. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21153. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21154. return this;
  21155. }
  21156. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21157. return this;
  21158. }
  21159. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21160. return this;
  21161. }
  21162. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21163. return this;
  21164. }
  21165. if (!this._sourcePositions) {
  21166. this.setPositionsForCPUSkinning();
  21167. }
  21168. if (!this._sourceNormals) {
  21169. this.setNormalsForCPUSkinning();
  21170. }
  21171. // positionsData checks for not being Float32Array will only pass at most once
  21172. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21173. if (!(positionsData instanceof Float32Array)) {
  21174. positionsData = new Float32Array(positionsData);
  21175. }
  21176. // normalsData checks for not being Float32Array will only pass at most once
  21177. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21178. if (!(normalsData instanceof Float32Array)) {
  21179. normalsData = new Float32Array(normalsData);
  21180. }
  21181. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21182. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21183. var needExtras = this.numBoneInfluencers > 4;
  21184. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21185. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21186. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21187. var tempVector3 = BABYLON.Vector3.Zero();
  21188. var finalMatrix = new BABYLON.Matrix();
  21189. var tempMatrix = new BABYLON.Matrix();
  21190. var matWeightIdx = 0;
  21191. var inf;
  21192. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21193. var weight;
  21194. for (inf = 0; inf < 4; inf++) {
  21195. weight = matricesWeightsData[matWeightIdx + inf];
  21196. if (weight > 0) {
  21197. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21198. finalMatrix.addToSelf(tempMatrix);
  21199. }
  21200. else
  21201. break;
  21202. }
  21203. if (needExtras) {
  21204. for (inf = 0; inf < 4; inf++) {
  21205. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21206. if (weight > 0) {
  21207. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21208. finalMatrix.addToSelf(tempMatrix);
  21209. }
  21210. else
  21211. break;
  21212. }
  21213. }
  21214. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21215. tempVector3.toArray(positionsData, index);
  21216. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21217. tempVector3.toArray(normalsData, index);
  21218. finalMatrix.reset();
  21219. }
  21220. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21221. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21222. return this;
  21223. };
  21224. // Tools
  21225. /**
  21226. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21227. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21228. */
  21229. Mesh.MinMax = function (meshes) {
  21230. var minVector = null;
  21231. var maxVector = null;
  21232. meshes.forEach(function (mesh, index, array) {
  21233. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21234. if (!minVector) {
  21235. minVector = boundingBox.minimumWorld;
  21236. maxVector = boundingBox.maximumWorld;
  21237. }
  21238. else {
  21239. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21240. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21241. }
  21242. });
  21243. return {
  21244. min: minVector,
  21245. max: maxVector
  21246. };
  21247. };
  21248. /**
  21249. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21250. */
  21251. Mesh.Center = function (meshesOrMinMaxVector) {
  21252. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21253. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21254. };
  21255. /**
  21256. * Merge the array of meshes into a single mesh for performance reasons.
  21257. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21258. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21259. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21260. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21261. */
  21262. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21263. if (disposeSource === void 0) { disposeSource = true; }
  21264. var index;
  21265. if (!allow32BitsIndices) {
  21266. var totalVertices = 0;
  21267. // Counting vertices
  21268. for (index = 0; index < meshes.length; index++) {
  21269. if (meshes[index]) {
  21270. totalVertices += meshes[index].getTotalVertices();
  21271. if (totalVertices > 65536) {
  21272. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21273. return null;
  21274. }
  21275. }
  21276. }
  21277. }
  21278. // Merge
  21279. var vertexData;
  21280. var otherVertexData;
  21281. var source;
  21282. for (index = 0; index < meshes.length; index++) {
  21283. if (meshes[index]) {
  21284. meshes[index].computeWorldMatrix(true);
  21285. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21286. otherVertexData.transform(meshes[index].getWorldMatrix());
  21287. if (vertexData) {
  21288. vertexData.merge(otherVertexData);
  21289. }
  21290. else {
  21291. vertexData = otherVertexData;
  21292. source = meshes[index];
  21293. }
  21294. }
  21295. }
  21296. if (!meshSubclass) {
  21297. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21298. }
  21299. vertexData.applyToMesh(meshSubclass);
  21300. // Setting properties
  21301. meshSubclass.material = source.material;
  21302. meshSubclass.checkCollisions = source.checkCollisions;
  21303. // Cleaning
  21304. if (disposeSource) {
  21305. for (index = 0; index < meshes.length; index++) {
  21306. if (meshes[index]) {
  21307. meshes[index].dispose();
  21308. }
  21309. }
  21310. }
  21311. return meshSubclass;
  21312. };
  21313. // Consts
  21314. Mesh._FRONTSIDE = 0;
  21315. Mesh._BACKSIDE = 1;
  21316. Mesh._DOUBLESIDE = 2;
  21317. Mesh._DEFAULTSIDE = 0;
  21318. Mesh._NO_CAP = 0;
  21319. Mesh._CAP_START = 1;
  21320. Mesh._CAP_END = 2;
  21321. Mesh._CAP_ALL = 3;
  21322. return Mesh;
  21323. }(BABYLON.AbstractMesh));
  21324. BABYLON.Mesh = Mesh;
  21325. })(BABYLON || (BABYLON = {}));
  21326. var BABYLON;
  21327. (function (BABYLON) {
  21328. var SubMesh = (function () {
  21329. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21330. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21331. this.materialIndex = materialIndex;
  21332. this.verticesStart = verticesStart;
  21333. this.verticesCount = verticesCount;
  21334. this.indexStart = indexStart;
  21335. this.indexCount = indexCount;
  21336. this._renderId = 0;
  21337. this._mesh = mesh;
  21338. this._renderingMesh = renderingMesh || mesh;
  21339. mesh.subMeshes.push(this);
  21340. this._trianglePlanes = [];
  21341. this._id = mesh.subMeshes.length - 1;
  21342. if (createBoundingBox) {
  21343. this.refreshBoundingInfo();
  21344. mesh.computeWorldMatrix(true);
  21345. }
  21346. }
  21347. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21348. get: function () {
  21349. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21350. },
  21351. enumerable: true,
  21352. configurable: true
  21353. });
  21354. SubMesh.prototype.getBoundingInfo = function () {
  21355. if (this.IsGlobal) {
  21356. return this._mesh.getBoundingInfo();
  21357. }
  21358. return this._boundingInfo;
  21359. };
  21360. SubMesh.prototype.getMesh = function () {
  21361. return this._mesh;
  21362. };
  21363. SubMesh.prototype.getRenderingMesh = function () {
  21364. return this._renderingMesh;
  21365. };
  21366. SubMesh.prototype.getMaterial = function () {
  21367. var rootMaterial = this._renderingMesh.material;
  21368. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  21369. var multiMaterial = rootMaterial;
  21370. return multiMaterial.getSubMaterial(this.materialIndex);
  21371. }
  21372. if (!rootMaterial) {
  21373. return this._mesh.getScene().defaultMaterial;
  21374. }
  21375. return rootMaterial;
  21376. };
  21377. // Methods
  21378. SubMesh.prototype.refreshBoundingInfo = function () {
  21379. this._lastColliderWorldVertices = null;
  21380. if (this.IsGlobal) {
  21381. return;
  21382. }
  21383. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21384. if (!data) {
  21385. this._boundingInfo = this._mesh._boundingInfo;
  21386. return;
  21387. }
  21388. var indices = this._renderingMesh.getIndices();
  21389. var extend;
  21390. //is this the only submesh?
  21391. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21392. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21393. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21394. }
  21395. else {
  21396. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21397. }
  21398. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21399. };
  21400. SubMesh.prototype._checkCollision = function (collider) {
  21401. return this.getBoundingInfo()._checkCollision(collider);
  21402. };
  21403. SubMesh.prototype.updateBoundingInfo = function (world) {
  21404. if (!this.getBoundingInfo()) {
  21405. this.refreshBoundingInfo();
  21406. }
  21407. this.getBoundingInfo().update(world);
  21408. };
  21409. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21410. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21411. };
  21412. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21413. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21414. };
  21415. SubMesh.prototype.render = function (enableAlphaMode) {
  21416. this._renderingMesh.render(this, enableAlphaMode);
  21417. };
  21418. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21419. if (!this._linesIndexBuffer) {
  21420. var linesIndices = [];
  21421. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21422. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21423. }
  21424. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21425. this.linesIndexCount = linesIndices.length;
  21426. }
  21427. return this._linesIndexBuffer;
  21428. };
  21429. SubMesh.prototype.canIntersects = function (ray) {
  21430. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21431. };
  21432. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21433. var intersectInfo = null;
  21434. // LineMesh first as it's also a Mesh...
  21435. if (this._mesh instanceof BABYLON.LinesMesh) {
  21436. var lineMesh = this._mesh;
  21437. // Line test
  21438. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21439. var p0 = positions[indices[index]];
  21440. var p1 = positions[indices[index + 1]];
  21441. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21442. if (length < 0) {
  21443. continue;
  21444. }
  21445. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21446. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21447. if (fastCheck) {
  21448. break;
  21449. }
  21450. }
  21451. }
  21452. }
  21453. else {
  21454. // Triangles test
  21455. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21456. var p0 = positions[indices[index]];
  21457. var p1 = positions[indices[index + 1]];
  21458. var p2 = positions[indices[index + 2]];
  21459. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21460. if (currentIntersectInfo) {
  21461. if (currentIntersectInfo.distance < 0) {
  21462. continue;
  21463. }
  21464. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21465. intersectInfo = currentIntersectInfo;
  21466. intersectInfo.faceId = index / 3;
  21467. if (fastCheck) {
  21468. break;
  21469. }
  21470. }
  21471. }
  21472. }
  21473. }
  21474. return intersectInfo;
  21475. };
  21476. // Clone
  21477. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21478. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21479. if (!this.IsGlobal) {
  21480. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21481. }
  21482. return result;
  21483. };
  21484. // Dispose
  21485. SubMesh.prototype.dispose = function () {
  21486. if (this._linesIndexBuffer) {
  21487. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21488. this._linesIndexBuffer = null;
  21489. }
  21490. // Remove from mesh
  21491. var index = this._mesh.subMeshes.indexOf(this);
  21492. this._mesh.subMeshes.splice(index, 1);
  21493. };
  21494. // Statics
  21495. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21496. var minVertexIndex = Number.MAX_VALUE;
  21497. var maxVertexIndex = -Number.MAX_VALUE;
  21498. renderingMesh = renderingMesh || mesh;
  21499. var indices = renderingMesh.getIndices();
  21500. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21501. var vertexIndex = indices[index];
  21502. if (vertexIndex < minVertexIndex)
  21503. minVertexIndex = vertexIndex;
  21504. if (vertexIndex > maxVertexIndex)
  21505. maxVertexIndex = vertexIndex;
  21506. }
  21507. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21508. };
  21509. return SubMesh;
  21510. }());
  21511. BABYLON.SubMesh = SubMesh;
  21512. })(BABYLON || (BABYLON = {}));
  21513. var BABYLON;
  21514. (function (BABYLON) {
  21515. var MeshBuilder = (function () {
  21516. function MeshBuilder() {
  21517. }
  21518. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  21519. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  21520. return BABYLON.Mesh.DOUBLESIDE;
  21521. }
  21522. if (orientation === undefined || orientation === null) {
  21523. return BABYLON.Mesh.FRONTSIDE;
  21524. }
  21525. return orientation;
  21526. };
  21527. /**
  21528. * Creates a box mesh.
  21529. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21530. * The parameter `size` sets the size (float) of each box side (default 1).
  21531. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21532. * 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).
  21533. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21534. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21535. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21537. */
  21538. MeshBuilder.CreateBox = function (name, options, scene) {
  21539. var box = new BABYLON.Mesh(name, scene);
  21540. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21541. var vertexData = BABYLON.VertexData.CreateBox(options);
  21542. vertexData.applyToMesh(box, options.updatable);
  21543. return box;
  21544. };
  21545. /**
  21546. * Creates a sphere mesh.
  21547. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21548. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21549. * 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`).
  21550. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21551. * 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
  21552. * 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).
  21553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21554. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21556. */
  21557. MeshBuilder.CreateSphere = function (name, options, scene) {
  21558. var sphere = new BABYLON.Mesh(name, scene);
  21559. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21560. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21561. vertexData.applyToMesh(sphere, options.updatable);
  21562. return sphere;
  21563. };
  21564. /**
  21565. * Creates a plane polygonal mesh. By default, this is a disc.
  21566. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21567. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21568. * 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.
  21569. * 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
  21570. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21571. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21572. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21573. */
  21574. MeshBuilder.CreateDisc = function (name, options, scene) {
  21575. var disc = new BABYLON.Mesh(name, scene);
  21576. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21577. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21578. vertexData.applyToMesh(disc, options.updatable);
  21579. return disc;
  21580. };
  21581. /**
  21582. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21583. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21584. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21585. * 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`).
  21586. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21587. * 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.
  21588. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21589. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21590. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21591. */
  21592. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21593. var sphere = new BABYLON.Mesh(name, scene);
  21594. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21595. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21596. vertexData.applyToMesh(sphere, options.updatable);
  21597. return sphere;
  21598. };
  21599. ;
  21600. /**
  21601. * Creates a ribbon mesh.
  21602. * 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.
  21603. *
  21604. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21605. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21606. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21607. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21608. * 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.
  21609. * 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.
  21610. * 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
  21611. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21613. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21615. */
  21616. MeshBuilder.CreateRibbon = function (name, options, scene) {
  21617. var pathArray = options.pathArray;
  21618. var closeArray = options.closeArray;
  21619. var closePath = options.closePath;
  21620. var offset = options.offset;
  21621. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21622. var instance = options.instance;
  21623. var updatable = options.updatable;
  21624. if (instance) {
  21625. // positionFunction : ribbon case
  21626. // only pathArray and sideOrientation parameters are taken into account for positions update
  21627. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21628. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21629. var positionFunction = function (positions) {
  21630. var minlg = pathArray[0].length;
  21631. var i = 0;
  21632. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21633. for (var si = 1; si <= ns; si++) {
  21634. for (var p = 0; p < pathArray.length; p++) {
  21635. var path = pathArray[p];
  21636. var l = path.length;
  21637. minlg = (minlg < l) ? minlg : l;
  21638. var j = 0;
  21639. while (j < minlg) {
  21640. positions[i] = path[j].x;
  21641. positions[i + 1] = path[j].y;
  21642. positions[i + 2] = path[j].z;
  21643. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21644. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21645. }
  21646. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21647. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21648. }
  21649. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21650. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21651. }
  21652. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21653. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21654. }
  21655. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21656. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21657. }
  21658. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21659. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21660. }
  21661. j++;
  21662. i += 3;
  21663. }
  21664. if (instance._closePath) {
  21665. positions[i] = path[0].x;
  21666. positions[i + 1] = path[0].y;
  21667. positions[i + 2] = path[0].z;
  21668. i += 3;
  21669. }
  21670. }
  21671. }
  21672. };
  21673. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21674. positionFunction(positions);
  21675. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21676. instance._boundingInfo.update(instance._worldMatrix);
  21677. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21678. if (!(instance.areNormalsFrozen)) {
  21679. var indices = instance.getIndices();
  21680. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21681. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21682. if (instance._closePath) {
  21683. var indexFirst = 0;
  21684. var indexLast = 0;
  21685. for (var p = 0; p < pathArray.length; p++) {
  21686. indexFirst = instance._idx[p] * 3;
  21687. if (p + 1 < pathArray.length) {
  21688. indexLast = (instance._idx[p + 1] - 1) * 3;
  21689. }
  21690. else {
  21691. indexLast = normals.length - 3;
  21692. }
  21693. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21694. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21695. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21696. normals[indexLast] = normals[indexFirst];
  21697. normals[indexLast + 1] = normals[indexFirst + 1];
  21698. normals[indexLast + 2] = normals[indexFirst + 2];
  21699. }
  21700. }
  21701. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21702. }
  21703. return instance;
  21704. }
  21705. else {
  21706. var ribbon = new BABYLON.Mesh(name, scene);
  21707. ribbon.sideOrientation = sideOrientation;
  21708. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21709. if (closePath) {
  21710. ribbon._idx = vertexData._idx;
  21711. }
  21712. ribbon._closePath = closePath;
  21713. ribbon._closeArray = closeArray;
  21714. vertexData.applyToMesh(ribbon, updatable);
  21715. return ribbon;
  21716. }
  21717. };
  21718. /**
  21719. * Creates a cylinder or a cone mesh.
  21720. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21721. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21722. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21723. * 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.
  21724. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21725. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21726. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21727. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21728. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21729. * 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).
  21730. * 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
  21731. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21732. * 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
  21733. * 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.
  21734. * If `enclose` is false, a ring surface is one element.
  21735. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21736. * 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
  21737. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21738. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21739. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21740. */
  21741. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21742. var cylinder = new BABYLON.Mesh(name, scene);
  21743. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21744. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21745. vertexData.applyToMesh(cylinder, options.updatable);
  21746. return cylinder;
  21747. };
  21748. /**
  21749. * Creates a torus mesh.
  21750. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21751. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21752. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21753. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21755. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21757. */
  21758. MeshBuilder.CreateTorus = function (name, options, scene) {
  21759. var torus = new BABYLON.Mesh(name, scene);
  21760. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21761. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21762. vertexData.applyToMesh(torus, options.updatable);
  21763. return torus;
  21764. };
  21765. /**
  21766. * Creates a torus knot mesh.
  21767. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21768. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21769. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21770. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21771. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21772. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21773. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21775. */
  21776. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21777. var torusKnot = new BABYLON.Mesh(name, scene);
  21778. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21779. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21780. vertexData.applyToMesh(torusKnot, options.updatable);
  21781. return torusKnot;
  21782. };
  21783. /**
  21784. * Creates a line system mesh.
  21785. * A line system is a pool of many lines gathered in a single mesh.
  21786. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21787. * 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.
  21788. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21789. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21790. * 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
  21791. * 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
  21792. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21794. */
  21795. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  21796. var instance = options.instance;
  21797. var lines = options.lines;
  21798. if (instance) {
  21799. var positionFunction = function (positions) {
  21800. var i = 0;
  21801. for (var l = 0; l < lines.length; l++) {
  21802. var points = lines[l];
  21803. for (var p = 0; p < points.length; p++) {
  21804. positions[i] = points[p].x;
  21805. positions[i + 1] = points[p].y;
  21806. positions[i + 2] = points[p].z;
  21807. i += 3;
  21808. }
  21809. }
  21810. };
  21811. instance.updateMeshPositions(positionFunction, false);
  21812. return instance;
  21813. }
  21814. // line system creation
  21815. var lineSystem = new BABYLON.LinesMesh(name, scene);
  21816. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  21817. vertexData.applyToMesh(lineSystem, options.updatable);
  21818. return lineSystem;
  21819. };
  21820. /**
  21821. * Creates a line mesh.
  21822. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  21823. * 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.
  21824. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21825. * The parameter `points` is an array successive Vector3.
  21826. * 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
  21827. * When updating an instance, remember that only point positions can change, not the number of points.
  21828. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21829. */
  21830. MeshBuilder.CreateLines = function (name, options, scene) {
  21831. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  21832. return lines;
  21833. };
  21834. /**
  21835. * Creates a dashed line mesh.
  21836. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  21837. * 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.
  21838. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21839. * The parameter `points` is an array successive Vector3.
  21840. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21841. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21842. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21843. * 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
  21844. * When updating an instance, remember that only point positions can change, not the number of points.
  21845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21846. */
  21847. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  21848. var points = options.points;
  21849. var instance = options.instance;
  21850. var gapSize = options.gapSize;
  21851. var dashNb = options.dashNb;
  21852. var dashSize = options.dashSize;
  21853. if (instance) {
  21854. var positionFunction = function (positions) {
  21855. var curvect = BABYLON.Vector3.Zero();
  21856. var nbSeg = positions.length / 6;
  21857. var lg = 0;
  21858. var nb = 0;
  21859. var shft = 0;
  21860. var dashshft = 0;
  21861. var curshft = 0;
  21862. var p = 0;
  21863. var i = 0;
  21864. var j = 0;
  21865. for (i = 0; i < points.length - 1; i++) {
  21866. points[i + 1].subtractToRef(points[i], curvect);
  21867. lg += curvect.length();
  21868. }
  21869. shft = lg / nbSeg;
  21870. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  21871. for (i = 0; i < points.length - 1; i++) {
  21872. points[i + 1].subtractToRef(points[i], curvect);
  21873. nb = Math.floor(curvect.length() / shft);
  21874. curvect.normalize();
  21875. j = 0;
  21876. while (j < nb && p < positions.length) {
  21877. curshft = shft * j;
  21878. positions[p] = points[i].x + curshft * curvect.x;
  21879. positions[p + 1] = points[i].y + curshft * curvect.y;
  21880. positions[p + 2] = points[i].z + curshft * curvect.z;
  21881. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  21882. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  21883. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  21884. p += 6;
  21885. j++;
  21886. }
  21887. }
  21888. while (p < positions.length) {
  21889. positions[p] = points[i].x;
  21890. positions[p + 1] = points[i].y;
  21891. positions[p + 2] = points[i].z;
  21892. p += 3;
  21893. }
  21894. };
  21895. instance.updateMeshPositions(positionFunction, false);
  21896. return instance;
  21897. }
  21898. // dashed lines creation
  21899. var dashedLines = new BABYLON.LinesMesh(name, scene);
  21900. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  21901. vertexData.applyToMesh(dashedLines, options.updatable);
  21902. dashedLines.dashSize = dashSize;
  21903. dashedLines.gapSize = gapSize;
  21904. return dashedLines;
  21905. };
  21906. /**
  21907. * Creates an extruded shape mesh.
  21908. * 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.
  21909. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  21910. *
  21911. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21912. * 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
  21913. * extruded along the Z axis.
  21914. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21915. * 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.
  21916. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21917. * 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
  21918. * 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
  21919. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21920. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21921. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21922. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21923. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21924. */
  21925. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  21926. var path = options.path;
  21927. var shape = options.shape;
  21928. var scale = options.scale || 1;
  21929. var rotation = options.rotation || 0;
  21930. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21931. var updatable = options.updatable;
  21932. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21933. var instance = options.instance;
  21934. var invertUV = options.invertUV || false;
  21935. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  21936. };
  21937. /**
  21938. * Creates an custom extruded shape mesh.
  21939. * 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.
  21940. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  21941. *
  21942. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21943. * 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
  21944. * extruded along the Z axis.
  21945. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21946. * 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
  21947. * and the distance of this point from the begining of the path :
  21948. * ```javascript
  21949. * var rotationFunction = function(i, distance) {
  21950. * // do things
  21951. * return rotationValue; }
  21952. * ```
  21953. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21954. * 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
  21955. * and the distance of this point from the begining of the path :
  21956. * ```javascript
  21957. * var scaleFunction = function(i, distance) {
  21958. * // do things
  21959. * return scaleValue;}
  21960. * ```
  21961. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21962. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21963. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21964. * 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
  21965. * 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
  21966. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21967. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21968. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21969. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21970. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21971. */
  21972. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  21973. var path = options.path;
  21974. var shape = options.shape;
  21975. var scaleFunction = options.scaleFunction || (function () { return 1; });
  21976. var rotationFunction = options.rotationFunction || (function () { return 0; });
  21977. var ribbonCloseArray = options.ribbonCloseArray || false;
  21978. var ribbonClosePath = options.ribbonClosePath || false;
  21979. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21980. var updatable = options.updatable;
  21981. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21982. var instance = options.instance;
  21983. var invertUV = options.invertUV || false;
  21984. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  21985. };
  21986. /**
  21987. * Creates lathe mesh.
  21988. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21989. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  21990. *
  21991. * 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
  21992. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21993. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21994. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21995. * 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.
  21996. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  21997. * 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
  21998. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21999. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22000. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22002. */
  22003. MeshBuilder.CreateLathe = function (name, options, scene) {
  22004. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22005. var closed = (options.closed === undefined) ? true : options.closed;
  22006. var shape = options.shape;
  22007. var radius = options.radius || 1;
  22008. var tessellation = options.tessellation || 64;
  22009. var updatable = options.updatable;
  22010. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22011. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22012. var pi2 = Math.PI * 2;
  22013. var paths = new Array();
  22014. var invertUV = options.invertUV || false;
  22015. var i = 0;
  22016. var p = 0;
  22017. var step = pi2 / tessellation * arc;
  22018. var rotated;
  22019. var path = new Array();
  22020. ;
  22021. for (i = 0; i <= tessellation; i++) {
  22022. var path = [];
  22023. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22024. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22025. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22026. }
  22027. for (p = 0; p < shape.length; p++) {
  22028. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22029. path.push(rotated);
  22030. }
  22031. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22032. 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));
  22033. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22034. }
  22035. paths.push(path);
  22036. }
  22037. // lathe ribbon
  22038. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22039. return lathe;
  22040. };
  22041. /**
  22042. * Creates a plane mesh.
  22043. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22044. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22045. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22046. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22048. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22050. */
  22051. MeshBuilder.CreatePlane = function (name, options, scene) {
  22052. var plane = new BABYLON.Mesh(name, scene);
  22053. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22054. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22055. vertexData.applyToMesh(plane, options.updatable);
  22056. if (options.sourcePlane) {
  22057. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22058. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22059. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22060. plane.rotate(vectorProduct, product);
  22061. }
  22062. return plane;
  22063. };
  22064. /**
  22065. * Creates a ground mesh.
  22066. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22067. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22068. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22070. */
  22071. MeshBuilder.CreateGround = function (name, options, scene) {
  22072. var ground = new BABYLON.GroundMesh(name, scene);
  22073. ground._setReady(false);
  22074. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22075. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22076. ground._width = options.width || 1;
  22077. ground._height = options.height || 1;
  22078. ground._maxX = ground._width / 2;
  22079. ground._maxZ = ground._height / 2;
  22080. ground._minX = -ground._maxX;
  22081. ground._minZ = -ground._maxZ;
  22082. var vertexData = BABYLON.VertexData.CreateGround(options);
  22083. vertexData.applyToMesh(ground, options.updatable);
  22084. ground._setReady(true);
  22085. return ground;
  22086. };
  22087. /**
  22088. * Creates a tiled ground mesh.
  22089. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22090. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22091. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22092. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22093. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22094. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22095. * numbers of subdivisions on the ground width and height of each tile.
  22096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22097. */
  22098. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22099. var tiledGround = new BABYLON.Mesh(name, scene);
  22100. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22101. vertexData.applyToMesh(tiledGround, options.updatable);
  22102. return tiledGround;
  22103. };
  22104. /**
  22105. * Creates a ground mesh from a height map.
  22106. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22107. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22108. * The parameter `url` sets the URL of the height map image resource.
  22109. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22110. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22111. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22112. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22113. * 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).
  22114. * This function is passed the newly built mesh :
  22115. * ```javascript
  22116. * function(mesh) { // do things
  22117. * return; }
  22118. * ```
  22119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22120. */
  22121. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22122. var width = options.width || 10.0;
  22123. var height = options.height || 10.0;
  22124. var subdivisions = options.subdivisions || 1 | 0;
  22125. var minHeight = options.minHeight || 0.0;
  22126. var maxHeight = options.maxHeight || 10.0;
  22127. var updatable = options.updatable;
  22128. var onReady = options.onReady;
  22129. var ground = new BABYLON.GroundMesh(name, scene);
  22130. ground._subdivisionsX = subdivisions;
  22131. ground._subdivisionsY = subdivisions;
  22132. ground._width = width;
  22133. ground._height = height;
  22134. ground._maxX = ground._width / 2.0;
  22135. ground._maxZ = ground._height / 2.0;
  22136. ground._minX = -ground._maxX;
  22137. ground._minZ = -ground._maxZ;
  22138. ground._setReady(false);
  22139. var onload = function (img) {
  22140. // Getting height map data
  22141. var canvas = document.createElement("canvas");
  22142. var context = canvas.getContext("2d");
  22143. var bufferWidth = img.width;
  22144. var bufferHeight = img.height;
  22145. canvas.width = bufferWidth;
  22146. canvas.height = bufferHeight;
  22147. context.drawImage(img, 0, 0);
  22148. // Create VertexData from map data
  22149. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22150. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22151. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22152. width: width, height: height,
  22153. subdivisions: subdivisions,
  22154. minHeight: minHeight, maxHeight: maxHeight,
  22155. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22156. });
  22157. vertexData.applyToMesh(ground, updatable);
  22158. ground._setReady(true);
  22159. //execute ready callback, if set
  22160. if (onReady) {
  22161. onReady(ground);
  22162. }
  22163. };
  22164. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22165. return ground;
  22166. };
  22167. /**
  22168. * Creates a tube mesh.
  22169. * 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.
  22170. *
  22171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22172. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22173. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22174. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22175. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22176. * 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.
  22177. * It must return a radius value (positive float) :
  22178. * ```javascript
  22179. * var radiusFunction = function(i, distance) {
  22180. * // do things
  22181. * return radius; }
  22182. * ```
  22183. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22184. * 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
  22185. * 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
  22186. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22187. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22188. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22189. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22190. */
  22191. MeshBuilder.CreateTube = function (name, options, scene) {
  22192. var path = options.path;
  22193. var radius = options.radius || 1.0;
  22194. var tessellation = options.tessellation || 64 | 0;
  22195. var radiusFunction = options.radiusFunction;
  22196. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22197. var invertUV = options.invertUV || false;
  22198. var updatable = options.updatable;
  22199. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22200. var instance = options.instance;
  22201. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22202. // tube geometry
  22203. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22204. var tangents = path3D.getTangents();
  22205. var normals = path3D.getNormals();
  22206. var distances = path3D.getDistances();
  22207. var pi2 = Math.PI * 2;
  22208. var step = pi2 / tessellation * arc;
  22209. var returnRadius = function () { return radius; };
  22210. var radiusFunctionFinal = radiusFunction || returnRadius;
  22211. var circlePath;
  22212. var rad;
  22213. var normal;
  22214. var rotated;
  22215. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22216. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22217. for (var i = 0; i < path.length; i++) {
  22218. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22219. circlePath = Array(); // current circle array
  22220. normal = normals[i]; // current normal
  22221. for (var t = 0; t < tessellation; t++) {
  22222. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22223. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22224. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22225. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22226. circlePath[t] = rotated;
  22227. }
  22228. circlePaths[index] = circlePath;
  22229. index++;
  22230. }
  22231. // cap
  22232. var capPath = function (nbPoints, pathIndex) {
  22233. var pointCap = Array();
  22234. for (var i = 0; i < nbPoints; i++) {
  22235. pointCap.push(path[pathIndex]);
  22236. }
  22237. return pointCap;
  22238. };
  22239. switch (cap) {
  22240. case BABYLON.Mesh.NO_CAP:
  22241. break;
  22242. case BABYLON.Mesh.CAP_START:
  22243. circlePaths[0] = capPath(tessellation, 0);
  22244. circlePaths[1] = circlePaths[2].slice(0);
  22245. break;
  22246. case BABYLON.Mesh.CAP_END:
  22247. circlePaths[index] = circlePaths[index - 1].slice(0);
  22248. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22249. break;
  22250. case BABYLON.Mesh.CAP_ALL:
  22251. circlePaths[0] = capPath(tessellation, 0);
  22252. circlePaths[1] = circlePaths[2].slice(0);
  22253. circlePaths[index] = circlePaths[index - 1].slice(0);
  22254. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22255. break;
  22256. default:
  22257. break;
  22258. }
  22259. return circlePaths;
  22260. };
  22261. var path3D;
  22262. var pathArray;
  22263. if (instance) {
  22264. var arc = options.arc || instance.arc;
  22265. path3D = (instance.path3D).update(path);
  22266. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22267. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22268. instance.path3D = path3D;
  22269. instance.pathArray = pathArray;
  22270. instance.arc = arc;
  22271. return instance;
  22272. }
  22273. // tube creation
  22274. path3D = new BABYLON.Path3D(path);
  22275. var newPathArray = new Array();
  22276. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22277. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22278. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22279. tube.pathArray = pathArray;
  22280. tube.path3D = path3D;
  22281. tube.tessellation = tessellation;
  22282. tube.cap = cap;
  22283. tube.arc = options.arc;
  22284. return tube;
  22285. };
  22286. /**
  22287. * Creates a polyhedron mesh.
  22288. *
  22289. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22290. * 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
  22291. * to choose the wanted type.
  22292. * The parameter `size` (positive float, default 1) sets the polygon size.
  22293. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22294. * 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`.
  22295. * 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
  22296. * 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)`).
  22297. * 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
  22298. * 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.
  22299. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22300. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22301. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22302. */
  22303. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22304. var polyhedron = new BABYLON.Mesh(name, scene);
  22305. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22306. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22307. vertexData.applyToMesh(polyhedron, options.updatable);
  22308. return polyhedron;
  22309. };
  22310. /**
  22311. * Creates a decal mesh.
  22312. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22313. * 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.
  22314. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22315. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22316. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22317. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22318. */
  22319. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22320. var indices = sourceMesh.getIndices();
  22321. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22322. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22323. var position = options.position || BABYLON.Vector3.Zero();
  22324. var normal = options.normal || BABYLON.Vector3.Up();
  22325. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22326. var angle = options.angle || 0;
  22327. // Getting correct rotation
  22328. if (!normal) {
  22329. var target = new BABYLON.Vector3(0, 0, 1);
  22330. var camera = sourceMesh.getScene().activeCamera;
  22331. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22332. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22333. }
  22334. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22335. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22336. var pitch = Math.atan2(normal.y, len);
  22337. // Matrix
  22338. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22339. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22340. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22341. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22342. var vertexData = new BABYLON.VertexData();
  22343. vertexData.indices = [];
  22344. vertexData.positions = [];
  22345. vertexData.normals = [];
  22346. vertexData.uvs = [];
  22347. var currentVertexDataIndex = 0;
  22348. var extractDecalVector3 = function (indexId) {
  22349. var vertexId = indices[indexId];
  22350. var result = new BABYLON.PositionNormalVertex();
  22351. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  22352. // Send vector to decal local world
  22353. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  22354. // Get normal
  22355. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  22356. return result;
  22357. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  22358. var clip = function (vertices, axis) {
  22359. if (vertices.length === 0) {
  22360. return vertices;
  22361. }
  22362. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  22363. var clipVertices = function (v0, v1) {
  22364. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  22365. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  22366. };
  22367. var result = new Array();
  22368. for (var index = 0; index < vertices.length; index += 3) {
  22369. var v1Out;
  22370. var v2Out;
  22371. var v3Out;
  22372. var total = 0;
  22373. var nV1, nV2, nV3, nV4;
  22374. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  22375. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  22376. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  22377. v1Out = d1 > 0;
  22378. v2Out = d2 > 0;
  22379. v3Out = d3 > 0;
  22380. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  22381. switch (total) {
  22382. case 0:
  22383. result.push(vertices[index]);
  22384. result.push(vertices[index + 1]);
  22385. result.push(vertices[index + 2]);
  22386. break;
  22387. case 1:
  22388. if (v1Out) {
  22389. nV1 = vertices[index + 1];
  22390. nV2 = vertices[index + 2];
  22391. nV3 = clipVertices(vertices[index], nV1);
  22392. nV4 = clipVertices(vertices[index], nV2);
  22393. }
  22394. if (v2Out) {
  22395. nV1 = vertices[index];
  22396. nV2 = vertices[index + 2];
  22397. nV3 = clipVertices(vertices[index + 1], nV1);
  22398. nV4 = clipVertices(vertices[index + 1], nV2);
  22399. result.push(nV3);
  22400. result.push(nV2.clone());
  22401. result.push(nV1.clone());
  22402. result.push(nV2.clone());
  22403. result.push(nV3.clone());
  22404. result.push(nV4);
  22405. break;
  22406. }
  22407. if (v3Out) {
  22408. nV1 = vertices[index];
  22409. nV2 = vertices[index + 1];
  22410. nV3 = clipVertices(vertices[index + 2], nV1);
  22411. nV4 = clipVertices(vertices[index + 2], nV2);
  22412. }
  22413. result.push(nV1.clone());
  22414. result.push(nV2.clone());
  22415. result.push(nV3);
  22416. result.push(nV4);
  22417. result.push(nV3.clone());
  22418. result.push(nV2.clone());
  22419. break;
  22420. case 2:
  22421. if (!v1Out) {
  22422. nV1 = vertices[index].clone();
  22423. nV2 = clipVertices(nV1, vertices[index + 1]);
  22424. nV3 = clipVertices(nV1, vertices[index + 2]);
  22425. result.push(nV1);
  22426. result.push(nV2);
  22427. result.push(nV3);
  22428. }
  22429. if (!v2Out) {
  22430. nV1 = vertices[index + 1].clone();
  22431. nV2 = clipVertices(nV1, vertices[index + 2]);
  22432. nV3 = clipVertices(nV1, vertices[index]);
  22433. result.push(nV1);
  22434. result.push(nV2);
  22435. result.push(nV3);
  22436. }
  22437. if (!v3Out) {
  22438. nV1 = vertices[index + 2].clone();
  22439. nV2 = clipVertices(nV1, vertices[index]);
  22440. nV3 = clipVertices(nV1, vertices[index + 1]);
  22441. result.push(nV1);
  22442. result.push(nV2);
  22443. result.push(nV3);
  22444. }
  22445. break;
  22446. case 3:
  22447. break;
  22448. }
  22449. }
  22450. return result;
  22451. };
  22452. for (var index = 0; index < indices.length; index += 3) {
  22453. var faceVertices = new Array();
  22454. faceVertices.push(extractDecalVector3(index));
  22455. faceVertices.push(extractDecalVector3(index + 1));
  22456. faceVertices.push(extractDecalVector3(index + 2));
  22457. // Clip
  22458. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  22459. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  22460. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  22461. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  22462. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  22463. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  22464. if (faceVertices.length === 0) {
  22465. continue;
  22466. }
  22467. // Add UVs and get back to world
  22468. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  22469. var vertex = faceVertices[vIndex];
  22470. //TODO check for Int32Array
  22471. vertexData.indices.push(currentVertexDataIndex);
  22472. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  22473. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  22474. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  22475. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  22476. currentVertexDataIndex++;
  22477. }
  22478. }
  22479. // Return mesh
  22480. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  22481. vertexData.applyToMesh(decal);
  22482. decal.position = position.clone();
  22483. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  22484. return decal;
  22485. };
  22486. // Privates
  22487. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  22488. // extrusion geometry
  22489. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  22490. var tangents = path3D.getTangents();
  22491. var normals = path3D.getNormals();
  22492. var binormals = path3D.getBinormals();
  22493. var distances = path3D.getDistances();
  22494. var angle = 0;
  22495. var returnScale = function () { return scale; };
  22496. var returnRotation = function () { return rotation; };
  22497. var rotate = custom ? rotateFunction : returnRotation;
  22498. var scl = custom ? scaleFunction : returnScale;
  22499. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22500. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22501. for (var i = 0; i < curve.length; i++) {
  22502. var shapePath = new Array();
  22503. var angleStep = rotate(i, distances[i]);
  22504. var scaleRatio = scl(i, distances[i]);
  22505. for (var p = 0; p < shape.length; p++) {
  22506. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  22507. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  22508. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  22509. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  22510. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  22511. shapePath[p] = rotated;
  22512. }
  22513. shapePaths[index] = shapePath;
  22514. angle += angleStep;
  22515. index++;
  22516. }
  22517. // cap
  22518. var capPath = function (shapePath) {
  22519. var pointCap = Array();
  22520. var barycenter = BABYLON.Vector3.Zero();
  22521. var i;
  22522. for (i = 0; i < shapePath.length; i++) {
  22523. barycenter.addInPlace(shapePath[i]);
  22524. }
  22525. barycenter.scaleInPlace(1 / shapePath.length);
  22526. for (i = 0; i < shapePath.length; i++) {
  22527. pointCap.push(barycenter);
  22528. }
  22529. return pointCap;
  22530. };
  22531. switch (cap) {
  22532. case BABYLON.Mesh.NO_CAP:
  22533. break;
  22534. case BABYLON.Mesh.CAP_START:
  22535. shapePaths[0] = capPath(shapePaths[2]);
  22536. shapePaths[1] = shapePaths[2].slice(0);
  22537. break;
  22538. case BABYLON.Mesh.CAP_END:
  22539. shapePaths[index] = shapePaths[index - 1];
  22540. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22541. break;
  22542. case BABYLON.Mesh.CAP_ALL:
  22543. shapePaths[0] = capPath(shapePaths[2]);
  22544. shapePaths[1] = shapePaths[2].slice(0);
  22545. shapePaths[index] = shapePaths[index - 1];
  22546. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22547. break;
  22548. default:
  22549. break;
  22550. }
  22551. return shapePaths;
  22552. };
  22553. var path3D;
  22554. var pathArray;
  22555. if (instance) {
  22556. path3D = (instance.path3D).update(curve);
  22557. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22558. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  22559. return instance;
  22560. }
  22561. // extruded shape creation
  22562. path3D = new BABYLON.Path3D(curve);
  22563. var newShapePaths = new Array();
  22564. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22565. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22566. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22567. extrudedGeneric.pathArray = pathArray;
  22568. extrudedGeneric.path3D = path3D;
  22569. extrudedGeneric.cap = cap;
  22570. return extrudedGeneric;
  22571. };
  22572. return MeshBuilder;
  22573. }());
  22574. BABYLON.MeshBuilder = MeshBuilder;
  22575. })(BABYLON || (BABYLON = {}));
  22576. var BABYLON;
  22577. (function (BABYLON) {
  22578. var BaseTexture = (function () {
  22579. function BaseTexture(scene) {
  22580. this.hasAlpha = false;
  22581. this.getAlphaFromRGB = false;
  22582. this.level = 1;
  22583. this.coordinatesIndex = 0;
  22584. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22585. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22586. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22587. this.anisotropicFilteringLevel = 4;
  22588. this.isCube = false;
  22589. this.isRenderTarget = false;
  22590. this.animations = new Array();
  22591. /**
  22592. * An event triggered when the texture is disposed.
  22593. * @type {BABYLON.Observable}
  22594. */
  22595. this.onDisposeObservable = new BABYLON.Observable();
  22596. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22597. this._scene = scene;
  22598. this._scene.textures.push(this);
  22599. }
  22600. BaseTexture.prototype.toString = function () {
  22601. return this.name;
  22602. };
  22603. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22604. set: function (callback) {
  22605. if (this._onDisposeObserver) {
  22606. this.onDisposeObservable.remove(this._onDisposeObserver);
  22607. }
  22608. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22609. },
  22610. enumerable: true,
  22611. configurable: true
  22612. });
  22613. BaseTexture.prototype.getScene = function () {
  22614. return this._scene;
  22615. };
  22616. BaseTexture.prototype.getTextureMatrix = function () {
  22617. return null;
  22618. };
  22619. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22620. return null;
  22621. };
  22622. BaseTexture.prototype.getInternalTexture = function () {
  22623. return this._texture;
  22624. };
  22625. BaseTexture.prototype.isReady = function () {
  22626. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22627. return true;
  22628. }
  22629. if (this._texture) {
  22630. return this._texture.isReady;
  22631. }
  22632. return false;
  22633. };
  22634. BaseTexture.prototype.getSize = function () {
  22635. if (this._texture._width) {
  22636. return new BABYLON.Size(this._texture._width, this._texture._height);
  22637. }
  22638. if (this._texture._size) {
  22639. return new BABYLON.Size(this._texture._size, this._texture._size);
  22640. }
  22641. return BABYLON.Size.Zero();
  22642. };
  22643. BaseTexture.prototype.getBaseSize = function () {
  22644. if (!this.isReady() || !this._texture)
  22645. return BABYLON.Size.Zero();
  22646. if (this._texture._size) {
  22647. return new BABYLON.Size(this._texture._size, this._texture._size);
  22648. }
  22649. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22650. };
  22651. BaseTexture.prototype.scale = function (ratio) {
  22652. };
  22653. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22654. get: function () {
  22655. return false;
  22656. },
  22657. enumerable: true,
  22658. configurable: true
  22659. });
  22660. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22661. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22662. for (var index = 0; index < texturesCache.length; index++) {
  22663. var texturesCacheEntry = texturesCache[index];
  22664. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22665. texturesCache.splice(index, 1);
  22666. return;
  22667. }
  22668. }
  22669. };
  22670. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22671. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22672. for (var index = 0; index < texturesCache.length; index++) {
  22673. var texturesCacheEntry = texturesCache[index];
  22674. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22675. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22676. texturesCacheEntry.references++;
  22677. return texturesCacheEntry;
  22678. }
  22679. }
  22680. }
  22681. return null;
  22682. };
  22683. BaseTexture.prototype.delayLoad = function () {
  22684. };
  22685. BaseTexture.prototype.clone = function () {
  22686. return null;
  22687. };
  22688. BaseTexture.prototype.releaseInternalTexture = function () {
  22689. if (this._texture) {
  22690. this._scene.getEngine().releaseInternalTexture(this._texture);
  22691. delete this._texture;
  22692. }
  22693. };
  22694. BaseTexture.prototype.dispose = function () {
  22695. // Animations
  22696. this.getScene().stopAnimation(this);
  22697. // Remove from scene
  22698. var index = this._scene.textures.indexOf(this);
  22699. if (index >= 0) {
  22700. this._scene.textures.splice(index, 1);
  22701. }
  22702. if (this._texture === undefined) {
  22703. return;
  22704. }
  22705. // Release
  22706. this.releaseInternalTexture();
  22707. // Callback
  22708. this.onDisposeObservable.notifyObservers(this);
  22709. this.onDisposeObservable.clear();
  22710. };
  22711. BaseTexture.prototype.serialize = function () {
  22712. if (!this.name) {
  22713. return null;
  22714. }
  22715. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22716. // Animations
  22717. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22718. return serializationObject;
  22719. };
  22720. __decorate([
  22721. BABYLON.serialize()
  22722. ], BaseTexture.prototype, "name", void 0);
  22723. __decorate([
  22724. BABYLON.serialize()
  22725. ], BaseTexture.prototype, "hasAlpha", void 0);
  22726. __decorate([
  22727. BABYLON.serialize()
  22728. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22729. __decorate([
  22730. BABYLON.serialize()
  22731. ], BaseTexture.prototype, "level", void 0);
  22732. __decorate([
  22733. BABYLON.serialize()
  22734. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22735. __decorate([
  22736. BABYLON.serialize()
  22737. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22738. __decorate([
  22739. BABYLON.serialize()
  22740. ], BaseTexture.prototype, "wrapU", void 0);
  22741. __decorate([
  22742. BABYLON.serialize()
  22743. ], BaseTexture.prototype, "wrapV", void 0);
  22744. __decorate([
  22745. BABYLON.serialize()
  22746. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22747. __decorate([
  22748. BABYLON.serialize()
  22749. ], BaseTexture.prototype, "isCube", void 0);
  22750. __decorate([
  22751. BABYLON.serialize()
  22752. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22753. return BaseTexture;
  22754. }());
  22755. BABYLON.BaseTexture = BaseTexture;
  22756. })(BABYLON || (BABYLON = {}));
  22757. var BABYLON;
  22758. (function (BABYLON) {
  22759. var Texture = (function (_super) {
  22760. __extends(Texture, _super);
  22761. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22762. var _this = this;
  22763. if (noMipmap === void 0) { noMipmap = false; }
  22764. if (invertY === void 0) { invertY = true; }
  22765. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22766. if (onLoad === void 0) { onLoad = null; }
  22767. if (onError === void 0) { onError = null; }
  22768. if (buffer === void 0) { buffer = null; }
  22769. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22770. _super.call(this, scene);
  22771. this.uOffset = 0;
  22772. this.vOffset = 0;
  22773. this.uScale = 1.0;
  22774. this.vScale = 1.0;
  22775. this.uAng = 0;
  22776. this.vAng = 0;
  22777. this.wAng = 0;
  22778. this.name = url;
  22779. this.url = url;
  22780. this._noMipmap = noMipmap;
  22781. this._invertY = invertY;
  22782. this._samplingMode = samplingMode;
  22783. this._buffer = buffer;
  22784. this._deleteBuffer = deleteBuffer;
  22785. if (!url) {
  22786. return;
  22787. }
  22788. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  22789. var load = function () {
  22790. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  22791. _this.onLoadObservable.notifyObservers(true);
  22792. }
  22793. if (onLoad) {
  22794. onLoad();
  22795. }
  22796. };
  22797. if (!this._texture) {
  22798. if (!scene.useDelayedTextureLoading) {
  22799. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  22800. if (deleteBuffer) {
  22801. delete this._buffer;
  22802. }
  22803. }
  22804. else {
  22805. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22806. this._delayedOnLoad = load;
  22807. this._delayedOnError = onError;
  22808. }
  22809. }
  22810. else {
  22811. if (this._texture.isReady) {
  22812. BABYLON.Tools.SetImmediate(function () { return load(); });
  22813. }
  22814. else {
  22815. this._texture.onLoadedCallbacks.push(load);
  22816. }
  22817. }
  22818. }
  22819. Object.defineProperty(Texture.prototype, "noMipmap", {
  22820. get: function () {
  22821. return this._noMipmap;
  22822. },
  22823. enumerable: true,
  22824. configurable: true
  22825. });
  22826. Texture.prototype.delayLoad = function () {
  22827. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22828. return;
  22829. }
  22830. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22831. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22832. if (!this._texture) {
  22833. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  22834. if (this._deleteBuffer) {
  22835. delete this._buffer;
  22836. }
  22837. }
  22838. };
  22839. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22840. if (!this._texture) {
  22841. return;
  22842. }
  22843. this._samplingMode = samplingMode;
  22844. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22845. };
  22846. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22847. x *= this.uScale;
  22848. y *= this.vScale;
  22849. x -= 0.5 * this.uScale;
  22850. y -= 0.5 * this.vScale;
  22851. z -= 0.5;
  22852. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22853. t.x += 0.5 * this.uScale + this.uOffset;
  22854. t.y += 0.5 * this.vScale + this.vOffset;
  22855. t.z += 0.5;
  22856. };
  22857. Texture.prototype.getTextureMatrix = function () {
  22858. if (this.uOffset === this._cachedUOffset &&
  22859. this.vOffset === this._cachedVOffset &&
  22860. this.uScale === this._cachedUScale &&
  22861. this.vScale === this._cachedVScale &&
  22862. this.uAng === this._cachedUAng &&
  22863. this.vAng === this._cachedVAng &&
  22864. this.wAng === this._cachedWAng) {
  22865. return this._cachedTextureMatrix;
  22866. }
  22867. this._cachedUOffset = this.uOffset;
  22868. this._cachedVOffset = this.vOffset;
  22869. this._cachedUScale = this.uScale;
  22870. this._cachedVScale = this.vScale;
  22871. this._cachedUAng = this.uAng;
  22872. this._cachedVAng = this.vAng;
  22873. this._cachedWAng = this.wAng;
  22874. if (!this._cachedTextureMatrix) {
  22875. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22876. this._rowGenerationMatrix = new BABYLON.Matrix();
  22877. this._t0 = BABYLON.Vector3.Zero();
  22878. this._t1 = BABYLON.Vector3.Zero();
  22879. this._t2 = BABYLON.Vector3.Zero();
  22880. }
  22881. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22882. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22883. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22884. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22885. this._t1.subtractInPlace(this._t0);
  22886. this._t2.subtractInPlace(this._t0);
  22887. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22888. this._cachedTextureMatrix.m[0] = this._t1.x;
  22889. this._cachedTextureMatrix.m[1] = this._t1.y;
  22890. this._cachedTextureMatrix.m[2] = this._t1.z;
  22891. this._cachedTextureMatrix.m[4] = this._t2.x;
  22892. this._cachedTextureMatrix.m[5] = this._t2.y;
  22893. this._cachedTextureMatrix.m[6] = this._t2.z;
  22894. this._cachedTextureMatrix.m[8] = this._t0.x;
  22895. this._cachedTextureMatrix.m[9] = this._t0.y;
  22896. this._cachedTextureMatrix.m[10] = this._t0.z;
  22897. return this._cachedTextureMatrix;
  22898. };
  22899. Texture.prototype.getReflectionTextureMatrix = function () {
  22900. if (this.uOffset === this._cachedUOffset &&
  22901. this.vOffset === this._cachedVOffset &&
  22902. this.uScale === this._cachedUScale &&
  22903. this.vScale === this._cachedVScale &&
  22904. this.coordinatesMode === this._cachedCoordinatesMode) {
  22905. return this._cachedTextureMatrix;
  22906. }
  22907. if (!this._cachedTextureMatrix) {
  22908. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22909. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22910. }
  22911. this._cachedCoordinatesMode = this.coordinatesMode;
  22912. switch (this.coordinatesMode) {
  22913. case Texture.PLANAR_MODE:
  22914. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22915. this._cachedTextureMatrix[0] = this.uScale;
  22916. this._cachedTextureMatrix[5] = this.vScale;
  22917. this._cachedTextureMatrix[12] = this.uOffset;
  22918. this._cachedTextureMatrix[13] = this.vOffset;
  22919. break;
  22920. case Texture.PROJECTION_MODE:
  22921. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22922. this._projectionModeMatrix.m[0] = 0.5;
  22923. this._projectionModeMatrix.m[5] = -0.5;
  22924. this._projectionModeMatrix.m[10] = 0.0;
  22925. this._projectionModeMatrix.m[12] = 0.5;
  22926. this._projectionModeMatrix.m[13] = 0.5;
  22927. this._projectionModeMatrix.m[14] = 1.0;
  22928. this._projectionModeMatrix.m[15] = 1.0;
  22929. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22930. break;
  22931. default:
  22932. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22933. break;
  22934. }
  22935. return this._cachedTextureMatrix;
  22936. };
  22937. Texture.prototype.clone = function () {
  22938. var _this = this;
  22939. return BABYLON.SerializationHelper.Clone(function () {
  22940. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22941. }, this);
  22942. };
  22943. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22944. get: function () {
  22945. if (!this._onLoadObservarble) {
  22946. this._onLoadObservarble = new BABYLON.Observable();
  22947. }
  22948. return this._onLoadObservarble;
  22949. },
  22950. enumerable: true,
  22951. configurable: true
  22952. });
  22953. // Statics
  22954. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  22955. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22956. if (onLoad === void 0) { onLoad = null; }
  22957. if (onError === void 0) { onError = null; }
  22958. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  22959. };
  22960. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22961. if (parsedTexture.isCube) {
  22962. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22963. }
  22964. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22965. return null;
  22966. }
  22967. var texture = BABYLON.SerializationHelper.Parse(function () {
  22968. if (parsedTexture.customType) {
  22969. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22970. return customTexture.Parse(parsedTexture, scene, rootUrl);
  22971. }
  22972. else if (parsedTexture.mirrorPlane) {
  22973. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22974. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22975. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22976. return mirrorTexture;
  22977. }
  22978. else if (parsedTexture.isRenderTarget) {
  22979. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22980. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22981. return renderTargetTexture;
  22982. }
  22983. else {
  22984. var texture;
  22985. if (parsedTexture.base64String) {
  22986. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22987. }
  22988. else {
  22989. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22990. }
  22991. return texture;
  22992. }
  22993. }, parsedTexture, scene);
  22994. // Animations
  22995. if (parsedTexture.animations) {
  22996. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22997. var parsedAnimation = parsedTexture.animations[animationIndex];
  22998. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22999. }
  23000. }
  23001. return texture;
  23002. };
  23003. // Constants
  23004. Texture.NEAREST_SAMPLINGMODE = 1;
  23005. Texture.BILINEAR_SAMPLINGMODE = 2;
  23006. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23007. Texture.EXPLICIT_MODE = 0;
  23008. Texture.SPHERICAL_MODE = 1;
  23009. Texture.PLANAR_MODE = 2;
  23010. Texture.CUBIC_MODE = 3;
  23011. Texture.PROJECTION_MODE = 4;
  23012. Texture.SKYBOX_MODE = 5;
  23013. Texture.INVCUBIC_MODE = 6;
  23014. Texture.EQUIRECTANGULAR_MODE = 7;
  23015. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23016. Texture.CLAMP_ADDRESSMODE = 0;
  23017. Texture.WRAP_ADDRESSMODE = 1;
  23018. Texture.MIRROR_ADDRESSMODE = 2;
  23019. __decorate([
  23020. BABYLON.serialize()
  23021. ], Texture.prototype, "url", void 0);
  23022. __decorate([
  23023. BABYLON.serialize()
  23024. ], Texture.prototype, "uOffset", void 0);
  23025. __decorate([
  23026. BABYLON.serialize()
  23027. ], Texture.prototype, "vOffset", void 0);
  23028. __decorate([
  23029. BABYLON.serialize()
  23030. ], Texture.prototype, "uScale", void 0);
  23031. __decorate([
  23032. BABYLON.serialize()
  23033. ], Texture.prototype, "vScale", void 0);
  23034. __decorate([
  23035. BABYLON.serialize()
  23036. ], Texture.prototype, "uAng", void 0);
  23037. __decorate([
  23038. BABYLON.serialize()
  23039. ], Texture.prototype, "vAng", void 0);
  23040. __decorate([
  23041. BABYLON.serialize()
  23042. ], Texture.prototype, "wAng", void 0);
  23043. return Texture;
  23044. }(BABYLON.BaseTexture));
  23045. BABYLON.Texture = Texture;
  23046. })(BABYLON || (BABYLON = {}));
  23047. var BABYLON;
  23048. (function (BABYLON) {
  23049. var CubeTexture = (function (_super) {
  23050. __extends(CubeTexture, _super);
  23051. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23052. if (onLoad === void 0) { onLoad = null; }
  23053. if (onError === void 0) { onError = null; }
  23054. _super.call(this, scene);
  23055. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23056. this.name = rootUrl;
  23057. this.url = rootUrl;
  23058. this._noMipmap = noMipmap;
  23059. this.hasAlpha = false;
  23060. if (!rootUrl && !files) {
  23061. return;
  23062. }
  23063. this._texture = this._getFromCache(rootUrl, noMipmap);
  23064. if (!files) {
  23065. if (!extensions) {
  23066. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23067. }
  23068. files = [];
  23069. for (var index = 0; index < extensions.length; index++) {
  23070. files.push(rootUrl + extensions[index]);
  23071. }
  23072. this._extensions = extensions;
  23073. }
  23074. this._files = files;
  23075. if (!this._texture) {
  23076. if (!scene.useDelayedTextureLoading) {
  23077. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23078. }
  23079. else {
  23080. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23081. }
  23082. }
  23083. else {
  23084. if (this._texture.isReady) {
  23085. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23086. }
  23087. else {
  23088. this._texture.onLoadedCallbacks.push(onLoad);
  23089. }
  23090. }
  23091. this.isCube = true;
  23092. this._textureMatrix = BABYLON.Matrix.Identity();
  23093. }
  23094. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23095. return new CubeTexture("", scene, null, noMipmap, files);
  23096. };
  23097. // Methods
  23098. CubeTexture.prototype.delayLoad = function () {
  23099. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23100. return;
  23101. }
  23102. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23103. this._texture = this._getFromCache(this.url, this._noMipmap);
  23104. if (!this._texture) {
  23105. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23106. }
  23107. };
  23108. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23109. return this._textureMatrix;
  23110. };
  23111. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23112. var texture = BABYLON.SerializationHelper.Parse(function () {
  23113. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23114. }, parsedTexture, scene);
  23115. // Animations
  23116. if (parsedTexture.animations) {
  23117. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23118. var parsedAnimation = parsedTexture.animations[animationIndex];
  23119. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23120. }
  23121. }
  23122. return texture;
  23123. };
  23124. CubeTexture.prototype.clone = function () {
  23125. var _this = this;
  23126. return BABYLON.SerializationHelper.Clone(function () {
  23127. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23128. }, this);
  23129. };
  23130. return CubeTexture;
  23131. }(BABYLON.BaseTexture));
  23132. BABYLON.CubeTexture = CubeTexture;
  23133. })(BABYLON || (BABYLON = {}));
  23134. var BABYLON;
  23135. (function (BABYLON) {
  23136. var RenderTargetTexture = (function (_super) {
  23137. __extends(RenderTargetTexture, _super);
  23138. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23139. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23140. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23141. if (isCube === void 0) { isCube = false; }
  23142. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23143. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23144. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23145. _super.call(this, null, scene, !generateMipMaps);
  23146. this.isCube = isCube;
  23147. /**
  23148. * Use this list to define the list of mesh you want to render.
  23149. */
  23150. this.renderList = new Array();
  23151. this.renderParticles = true;
  23152. this.renderSprites = false;
  23153. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23154. // Events
  23155. /**
  23156. * An event triggered when the texture is unbind.
  23157. * @type {BABYLON.Observable}
  23158. */
  23159. this.onAfterUnbindObservable = new BABYLON.Observable();
  23160. /**
  23161. * An event triggered before rendering the texture
  23162. * @type {BABYLON.Observable}
  23163. */
  23164. this.onBeforeRenderObservable = new BABYLON.Observable();
  23165. /**
  23166. * An event triggered after rendering the texture
  23167. * @type {BABYLON.Observable}
  23168. */
  23169. this.onAfterRenderObservable = new BABYLON.Observable();
  23170. /**
  23171. * An event triggered after the texture clear
  23172. * @type {BABYLON.Observable}
  23173. */
  23174. this.onClearObservable = new BABYLON.Observable();
  23175. this._currentRefreshId = -1;
  23176. this._refreshRate = 1;
  23177. this.name = name;
  23178. this.isRenderTarget = true;
  23179. this._size = size;
  23180. this._generateMipMaps = generateMipMaps;
  23181. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23182. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23183. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23184. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23185. }
  23186. if (isCube) {
  23187. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23188. generateMipMaps: generateMipMaps,
  23189. samplingMode: samplingMode,
  23190. generateDepthBuffer: generateDepthBuffer,
  23191. generateStencilBuffer: generateStencilBuffer
  23192. });
  23193. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23194. this._textureMatrix = BABYLON.Matrix.Identity();
  23195. }
  23196. else {
  23197. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23198. generateMipMaps: generateMipMaps,
  23199. type: type,
  23200. samplingMode: samplingMode,
  23201. generateDepthBuffer: generateDepthBuffer,
  23202. generateStencilBuffer: generateStencilBuffer
  23203. });
  23204. }
  23205. // Rendering groups
  23206. this._renderingManager = new BABYLON.RenderingManager(scene);
  23207. }
  23208. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23209. get: function () {
  23210. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23211. },
  23212. enumerable: true,
  23213. configurable: true
  23214. });
  23215. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23216. get: function () {
  23217. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23218. },
  23219. enumerable: true,
  23220. configurable: true
  23221. });
  23222. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23223. get: function () {
  23224. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23225. },
  23226. enumerable: true,
  23227. configurable: true
  23228. });
  23229. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23230. set: function (callback) {
  23231. if (this._onAfterUnbindObserver) {
  23232. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23233. }
  23234. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23235. },
  23236. enumerable: true,
  23237. configurable: true
  23238. });
  23239. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23240. set: function (callback) {
  23241. if (this._onBeforeRenderObserver) {
  23242. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23243. }
  23244. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23245. },
  23246. enumerable: true,
  23247. configurable: true
  23248. });
  23249. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23250. set: function (callback) {
  23251. if (this._onAfterRenderObserver) {
  23252. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23253. }
  23254. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23255. },
  23256. enumerable: true,
  23257. configurable: true
  23258. });
  23259. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23260. set: function (callback) {
  23261. if (this._onClearObserver) {
  23262. this.onClearObservable.remove(this._onClearObserver);
  23263. }
  23264. this._onClearObserver = this.onClearObservable.add(callback);
  23265. },
  23266. enumerable: true,
  23267. configurable: true
  23268. });
  23269. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23270. this._currentRefreshId = -1;
  23271. };
  23272. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23273. get: function () {
  23274. return this._refreshRate;
  23275. },
  23276. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23277. set: function (value) {
  23278. this._refreshRate = value;
  23279. this.resetRefreshCounter();
  23280. },
  23281. enumerable: true,
  23282. configurable: true
  23283. });
  23284. RenderTargetTexture.prototype._shouldRender = function () {
  23285. if (this._currentRefreshId === -1) {
  23286. this._currentRefreshId = 1;
  23287. return true;
  23288. }
  23289. if (this.refreshRate === this._currentRefreshId) {
  23290. this._currentRefreshId = 1;
  23291. return true;
  23292. }
  23293. this._currentRefreshId++;
  23294. return false;
  23295. };
  23296. RenderTargetTexture.prototype.isReady = function () {
  23297. if (!this.getScene().renderTargetsEnabled) {
  23298. return false;
  23299. }
  23300. return _super.prototype.isReady.call(this);
  23301. };
  23302. RenderTargetTexture.prototype.getRenderSize = function () {
  23303. return this._size;
  23304. };
  23305. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23306. get: function () {
  23307. return true;
  23308. },
  23309. enumerable: true,
  23310. configurable: true
  23311. });
  23312. RenderTargetTexture.prototype.scale = function (ratio) {
  23313. var newSize = this._size * ratio;
  23314. this.resize(newSize, this._generateMipMaps);
  23315. };
  23316. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23317. if (this.isCube) {
  23318. return this._textureMatrix;
  23319. }
  23320. return _super.prototype.getReflectionTextureMatrix.call(this);
  23321. };
  23322. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  23323. this.releaseInternalTexture();
  23324. if (this.isCube) {
  23325. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  23326. }
  23327. else {
  23328. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23329. }
  23330. };
  23331. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  23332. var scene = this.getScene();
  23333. if (this.useCameraPostProcesses !== undefined) {
  23334. useCameraPostProcess = this.useCameraPostProcesses;
  23335. }
  23336. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23337. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  23338. }
  23339. if (this._waitingRenderList) {
  23340. this.renderList = [];
  23341. for (var index = 0; index < this._waitingRenderList.length; index++) {
  23342. var id = this._waitingRenderList[index];
  23343. this.renderList.push(scene.getMeshByID(id));
  23344. }
  23345. delete this._waitingRenderList;
  23346. }
  23347. // Is predicate defined?
  23348. if (this.renderListPredicate) {
  23349. this.renderList.splice(0); // Clear previous renderList
  23350. var sceneMeshes = this.getScene().meshes;
  23351. for (var index = 0; index < sceneMeshes.length; index++) {
  23352. var mesh = sceneMeshes[index];
  23353. if (this.renderListPredicate(mesh)) {
  23354. this.renderList.push(mesh);
  23355. }
  23356. }
  23357. }
  23358. if (this.renderList && this.renderList.length === 0) {
  23359. return;
  23360. }
  23361. // Prepare renderingManager
  23362. this._renderingManager.reset();
  23363. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  23364. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  23365. var sceneRenderId = scene.getRenderId();
  23366. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  23367. var mesh = currentRenderList[meshIndex];
  23368. if (mesh) {
  23369. if (!mesh.isReady()) {
  23370. // Reset _currentRefreshId
  23371. this.resetRefreshCounter();
  23372. continue;
  23373. }
  23374. mesh._preActivateForIntermediateRendering(sceneRenderId);
  23375. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  23376. mesh._activate(sceneRenderId);
  23377. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23378. var subMesh = mesh.subMeshes[subIndex];
  23379. scene._activeIndices.addCount(subMesh.indexCount, false);
  23380. this._renderingManager.dispatch(subMesh);
  23381. }
  23382. }
  23383. }
  23384. }
  23385. if (this.isCube) {
  23386. for (var face = 0; face < 6; face++) {
  23387. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23388. scene.incrementRenderId();
  23389. scene.resetCachedMaterial();
  23390. }
  23391. }
  23392. else {
  23393. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23394. }
  23395. this.onAfterUnbindObservable.notifyObservers(this);
  23396. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23397. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  23398. }
  23399. scene.resetCachedMaterial();
  23400. };
  23401. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  23402. var scene = this.getScene();
  23403. var engine = scene.getEngine();
  23404. // Bind
  23405. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  23406. if (this.isCube) {
  23407. engine.bindFramebuffer(this._texture, faceIndex);
  23408. }
  23409. else {
  23410. engine.bindFramebuffer(this._texture);
  23411. }
  23412. }
  23413. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  23414. // Clear
  23415. if (this.onClearObservable.hasObservers()) {
  23416. this.onClearObservable.notifyObservers(engine);
  23417. }
  23418. else {
  23419. engine.clear(scene.clearColor, true, true, true);
  23420. }
  23421. if (!this._doNotChangeAspectRatio) {
  23422. scene.updateTransformMatrix(true);
  23423. }
  23424. // Render
  23425. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  23426. if (useCameraPostProcess) {
  23427. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  23428. }
  23429. if (!this._doNotChangeAspectRatio) {
  23430. scene.updateTransformMatrix(true);
  23431. }
  23432. this.onAfterRenderObservable.notifyObservers(faceIndex);
  23433. // Dump ?
  23434. if (dumpForDebug) {
  23435. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  23436. }
  23437. // Unbind
  23438. if (!this.isCube || faceIndex === 5) {
  23439. if (this.isCube) {
  23440. if (faceIndex === 5) {
  23441. engine.generateMipMapsForCubemap(this._texture);
  23442. }
  23443. }
  23444. engine.unBindFramebuffer(this._texture, this.isCube);
  23445. }
  23446. };
  23447. /**
  23448. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23449. * This allowed control for front to back rendering or reversly depending of the special needs.
  23450. *
  23451. * @param renderingGroupId The rendering group id corresponding to its index
  23452. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23453. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23454. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23455. */
  23456. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23457. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23458. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23459. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23460. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23461. };
  23462. /**
  23463. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23464. *
  23465. * @param renderingGroupId The rendering group id corresponding to its index
  23466. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23467. */
  23468. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  23469. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  23470. };
  23471. RenderTargetTexture.prototype.clone = function () {
  23472. var textureSize = this.getSize();
  23473. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23474. // Base texture
  23475. newTexture.hasAlpha = this.hasAlpha;
  23476. newTexture.level = this.level;
  23477. // RenderTarget Texture
  23478. newTexture.coordinatesMode = this.coordinatesMode;
  23479. newTexture.renderList = this.renderList.slice(0);
  23480. return newTexture;
  23481. };
  23482. RenderTargetTexture.prototype.serialize = function () {
  23483. if (!this.name) {
  23484. return null;
  23485. }
  23486. var serializationObject = _super.prototype.serialize.call(this);
  23487. serializationObject.renderTargetSize = this.getRenderSize();
  23488. serializationObject.renderList = [];
  23489. for (var index = 0; index < this.renderList.length; index++) {
  23490. serializationObject.renderList.push(this.renderList[index].id);
  23491. }
  23492. return serializationObject;
  23493. };
  23494. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  23495. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  23496. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  23497. return RenderTargetTexture;
  23498. }(BABYLON.Texture));
  23499. BABYLON.RenderTargetTexture = RenderTargetTexture;
  23500. })(BABYLON || (BABYLON = {}));
  23501. var BABYLON;
  23502. (function (BABYLON) {
  23503. var ProceduralTexture = (function (_super) {
  23504. __extends(ProceduralTexture, _super);
  23505. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  23506. if (generateMipMaps === void 0) { generateMipMaps = true; }
  23507. if (isCube === void 0) { isCube = false; }
  23508. _super.call(this, null, scene, !generateMipMaps);
  23509. this.isCube = isCube;
  23510. this.isEnabled = true;
  23511. this._currentRefreshId = -1;
  23512. this._refreshRate = 1;
  23513. this._vertexBuffers = {};
  23514. this._uniforms = new Array();
  23515. this._samplers = new Array();
  23516. this._textures = new Array();
  23517. this._floats = new Array();
  23518. this._floatsArrays = {};
  23519. this._colors3 = new Array();
  23520. this._colors4 = new Array();
  23521. this._vectors2 = new Array();
  23522. this._vectors3 = new Array();
  23523. this._matrices = new Array();
  23524. this._fallbackTextureUsed = false;
  23525. scene._proceduralTextures.push(this);
  23526. this.name = name;
  23527. this.isRenderTarget = true;
  23528. this._size = size;
  23529. this._generateMipMaps = generateMipMaps;
  23530. this.setFragment(fragment);
  23531. this._fallbackTexture = fallbackTexture;
  23532. var engine = scene.getEngine();
  23533. if (isCube) {
  23534. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23535. this.setFloat("face", 0);
  23536. }
  23537. else {
  23538. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23539. }
  23540. // VBO
  23541. var vertices = [];
  23542. vertices.push(1, 1);
  23543. vertices.push(-1, 1);
  23544. vertices.push(-1, -1);
  23545. vertices.push(1, -1);
  23546. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23547. // Indices
  23548. var indices = [];
  23549. indices.push(0);
  23550. indices.push(1);
  23551. indices.push(2);
  23552. indices.push(0);
  23553. indices.push(2);
  23554. indices.push(3);
  23555. this._indexBuffer = engine.createIndexBuffer(indices);
  23556. }
  23557. ProceduralTexture.prototype.reset = function () {
  23558. if (this._effect === undefined) {
  23559. return;
  23560. }
  23561. var engine = this.getScene().getEngine();
  23562. engine._releaseEffect(this._effect);
  23563. };
  23564. ProceduralTexture.prototype.isReady = function () {
  23565. var _this = this;
  23566. var engine = this.getScene().getEngine();
  23567. var shaders;
  23568. if (!this._fragment) {
  23569. return false;
  23570. }
  23571. if (this._fallbackTextureUsed) {
  23572. return true;
  23573. }
  23574. if (this._fragment.fragmentElement !== undefined) {
  23575. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23576. }
  23577. else {
  23578. shaders = { vertex: "procedural", fragment: this._fragment };
  23579. }
  23580. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23581. _this.releaseInternalTexture();
  23582. if (_this._fallbackTexture) {
  23583. _this._texture = _this._fallbackTexture._texture;
  23584. _this._texture.references++;
  23585. }
  23586. _this._fallbackTextureUsed = true;
  23587. });
  23588. return this._effect.isReady();
  23589. };
  23590. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23591. this._currentRefreshId = -1;
  23592. };
  23593. ProceduralTexture.prototype.setFragment = function (fragment) {
  23594. this._fragment = fragment;
  23595. };
  23596. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23597. get: function () {
  23598. return this._refreshRate;
  23599. },
  23600. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23601. set: function (value) {
  23602. this._refreshRate = value;
  23603. this.resetRefreshCounter();
  23604. },
  23605. enumerable: true,
  23606. configurable: true
  23607. });
  23608. ProceduralTexture.prototype._shouldRender = function () {
  23609. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23610. return false;
  23611. }
  23612. if (this._fallbackTextureUsed) {
  23613. return false;
  23614. }
  23615. if (this._currentRefreshId === -1) {
  23616. this._currentRefreshId = 1;
  23617. return true;
  23618. }
  23619. if (this.refreshRate === this._currentRefreshId) {
  23620. this._currentRefreshId = 1;
  23621. return true;
  23622. }
  23623. this._currentRefreshId++;
  23624. return false;
  23625. };
  23626. ProceduralTexture.prototype.getRenderSize = function () {
  23627. return this._size;
  23628. };
  23629. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23630. if (this._fallbackTextureUsed) {
  23631. return;
  23632. }
  23633. this.releaseInternalTexture();
  23634. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23635. };
  23636. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23637. if (this._uniforms.indexOf(uniformName) === -1) {
  23638. this._uniforms.push(uniformName);
  23639. }
  23640. };
  23641. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23642. if (this._samplers.indexOf(name) === -1) {
  23643. this._samplers.push(name);
  23644. }
  23645. this._textures[name] = texture;
  23646. return this;
  23647. };
  23648. ProceduralTexture.prototype.setFloat = function (name, value) {
  23649. this._checkUniform(name);
  23650. this._floats[name] = value;
  23651. return this;
  23652. };
  23653. ProceduralTexture.prototype.setFloats = function (name, value) {
  23654. this._checkUniform(name);
  23655. this._floatsArrays[name] = value;
  23656. return this;
  23657. };
  23658. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23659. this._checkUniform(name);
  23660. this._colors3[name] = value;
  23661. return this;
  23662. };
  23663. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23664. this._checkUniform(name);
  23665. this._colors4[name] = value;
  23666. return this;
  23667. };
  23668. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23669. this._checkUniform(name);
  23670. this._vectors2[name] = value;
  23671. return this;
  23672. };
  23673. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23674. this._checkUniform(name);
  23675. this._vectors3[name] = value;
  23676. return this;
  23677. };
  23678. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23679. this._checkUniform(name);
  23680. this._matrices[name] = value;
  23681. return this;
  23682. };
  23683. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23684. var scene = this.getScene();
  23685. var engine = scene.getEngine();
  23686. // Render
  23687. engine.enableEffect(this._effect);
  23688. engine.setState(false);
  23689. // Texture
  23690. for (var name in this._textures) {
  23691. this._effect.setTexture(name, this._textures[name]);
  23692. }
  23693. // Float
  23694. for (name in this._floats) {
  23695. this._effect.setFloat(name, this._floats[name]);
  23696. }
  23697. // Floats
  23698. for (name in this._floatsArrays) {
  23699. this._effect.setArray(name, this._floatsArrays[name]);
  23700. }
  23701. // Color3
  23702. for (name in this._colors3) {
  23703. this._effect.setColor3(name, this._colors3[name]);
  23704. }
  23705. // Color4
  23706. for (name in this._colors4) {
  23707. var color = this._colors4[name];
  23708. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23709. }
  23710. // Vector2
  23711. for (name in this._vectors2) {
  23712. this._effect.setVector2(name, this._vectors2[name]);
  23713. }
  23714. // Vector3
  23715. for (name in this._vectors3) {
  23716. this._effect.setVector3(name, this._vectors3[name]);
  23717. }
  23718. // Matrix
  23719. for (name in this._matrices) {
  23720. this._effect.setMatrix(name, this._matrices[name]);
  23721. }
  23722. // VBOs
  23723. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23724. if (this.isCube) {
  23725. for (var face = 0; face < 6; face++) {
  23726. engine.bindFramebuffer(this._texture, face);
  23727. this._effect.setFloat("face", face);
  23728. // Clear
  23729. engine.clear(scene.clearColor, true, true, true);
  23730. // Draw order
  23731. engine.draw(true, 0, 6);
  23732. // Mipmaps
  23733. if (face === 5) {
  23734. engine.generateMipMapsForCubemap(this._texture);
  23735. }
  23736. }
  23737. }
  23738. else {
  23739. engine.bindFramebuffer(this._texture);
  23740. // Clear
  23741. engine.clear(scene.clearColor, true, true, true);
  23742. // Draw order
  23743. engine.draw(true, 0, 6);
  23744. }
  23745. // Unbind
  23746. engine.unBindFramebuffer(this._texture, this.isCube);
  23747. if (this.onGenerated) {
  23748. this.onGenerated();
  23749. }
  23750. };
  23751. ProceduralTexture.prototype.clone = function () {
  23752. var textureSize = this.getSize();
  23753. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23754. // Base texture
  23755. newTexture.hasAlpha = this.hasAlpha;
  23756. newTexture.level = this.level;
  23757. // RenderTarget Texture
  23758. newTexture.coordinatesMode = this.coordinatesMode;
  23759. return newTexture;
  23760. };
  23761. ProceduralTexture.prototype.dispose = function () {
  23762. var index = this.getScene()._proceduralTextures.indexOf(this);
  23763. if (index >= 0) {
  23764. this.getScene()._proceduralTextures.splice(index, 1);
  23765. }
  23766. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23767. if (vertexBuffer) {
  23768. vertexBuffer.dispose();
  23769. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23770. }
  23771. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23772. this._indexBuffer = null;
  23773. }
  23774. _super.prototype.dispose.call(this);
  23775. };
  23776. return ProceduralTexture;
  23777. }(BABYLON.Texture));
  23778. BABYLON.ProceduralTexture = ProceduralTexture;
  23779. })(BABYLON || (BABYLON = {}));
  23780. var BABYLON;
  23781. (function (BABYLON) {
  23782. var MirrorTexture = (function (_super) {
  23783. __extends(MirrorTexture, _super);
  23784. function MirrorTexture(name, size, scene, generateMipMaps) {
  23785. var _this = this;
  23786. _super.call(this, name, size, scene, generateMipMaps, true);
  23787. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  23788. this._transformMatrix = BABYLON.Matrix.Zero();
  23789. this._mirrorMatrix = BABYLON.Matrix.Zero();
  23790. this.onBeforeRenderObservable.add(function () {
  23791. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  23792. _this._savedViewMatrix = scene.getViewMatrix();
  23793. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  23794. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  23795. scene.clipPlane = _this.mirrorPlane;
  23796. scene.getEngine().cullBackFaces = false;
  23797. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  23798. });
  23799. this.onAfterRenderObservable.add(function () {
  23800. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  23801. scene.getEngine().cullBackFaces = true;
  23802. scene._mirroredCameraPosition = null;
  23803. delete scene.clipPlane;
  23804. });
  23805. }
  23806. MirrorTexture.prototype.clone = function () {
  23807. var textureSize = this.getSize();
  23808. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23809. // Base texture
  23810. newTexture.hasAlpha = this.hasAlpha;
  23811. newTexture.level = this.level;
  23812. // Mirror Texture
  23813. newTexture.mirrorPlane = this.mirrorPlane.clone();
  23814. newTexture.renderList = this.renderList.slice(0);
  23815. return newTexture;
  23816. };
  23817. MirrorTexture.prototype.serialize = function () {
  23818. if (!this.name) {
  23819. return null;
  23820. }
  23821. var serializationObject = _super.prototype.serialize.call(this);
  23822. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  23823. return serializationObject;
  23824. };
  23825. return MirrorTexture;
  23826. }(BABYLON.RenderTargetTexture));
  23827. BABYLON.MirrorTexture = MirrorTexture;
  23828. })(BABYLON || (BABYLON = {}));
  23829. var BABYLON;
  23830. (function (BABYLON) {
  23831. /**
  23832. * Creates a refraction texture used by refraction channel of the standard material.
  23833. * @param name the texture name
  23834. * @param size size of the underlying texture
  23835. * @param scene root scene
  23836. */
  23837. var RefractionTexture = (function (_super) {
  23838. __extends(RefractionTexture, _super);
  23839. function RefractionTexture(name, size, scene, generateMipMaps) {
  23840. var _this = this;
  23841. _super.call(this, name, size, scene, generateMipMaps, true);
  23842. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  23843. this.depth = 2.0;
  23844. this.onBeforeRenderObservable.add(function () {
  23845. scene.clipPlane = _this.refractionPlane;
  23846. });
  23847. this.onAfterRenderObservable.add(function () {
  23848. delete scene.clipPlane;
  23849. });
  23850. }
  23851. RefractionTexture.prototype.clone = function () {
  23852. var textureSize = this.getSize();
  23853. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23854. // Base texture
  23855. newTexture.hasAlpha = this.hasAlpha;
  23856. newTexture.level = this.level;
  23857. // Refraction Texture
  23858. newTexture.refractionPlane = this.refractionPlane.clone();
  23859. newTexture.renderList = this.renderList.slice(0);
  23860. newTexture.depth = this.depth;
  23861. return newTexture;
  23862. };
  23863. RefractionTexture.prototype.serialize = function () {
  23864. if (!this.name) {
  23865. return null;
  23866. }
  23867. var serializationObject = _super.prototype.serialize.call(this);
  23868. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  23869. serializationObject.depth = this.depth;
  23870. return serializationObject;
  23871. };
  23872. return RefractionTexture;
  23873. }(BABYLON.RenderTargetTexture));
  23874. BABYLON.RefractionTexture = RefractionTexture;
  23875. })(BABYLON || (BABYLON = {}));
  23876. var BABYLON;
  23877. (function (BABYLON) {
  23878. var DynamicTexture = (function (_super) {
  23879. __extends(DynamicTexture, _super);
  23880. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  23881. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23882. _super.call(this, null, scene, !generateMipMaps);
  23883. this.name = name;
  23884. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23885. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23886. this._generateMipMaps = generateMipMaps;
  23887. if (options.getContext) {
  23888. this._canvas = options;
  23889. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23890. }
  23891. else {
  23892. this._canvas = document.createElement("canvas");
  23893. if (options.width) {
  23894. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23895. }
  23896. else {
  23897. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  23898. }
  23899. }
  23900. var textureSize = this.getSize();
  23901. this._canvas.width = textureSize.width;
  23902. this._canvas.height = textureSize.height;
  23903. this._context = this._canvas.getContext("2d");
  23904. }
  23905. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  23906. get: function () {
  23907. return true;
  23908. },
  23909. enumerable: true,
  23910. configurable: true
  23911. });
  23912. DynamicTexture.prototype.scale = function (ratio) {
  23913. var textureSize = this.getSize();
  23914. textureSize.width *= ratio;
  23915. textureSize.height *= ratio;
  23916. this._canvas.width = textureSize.width;
  23917. this._canvas.height = textureSize.height;
  23918. this.releaseInternalTexture();
  23919. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  23920. };
  23921. DynamicTexture.prototype.getContext = function () {
  23922. return this._context;
  23923. };
  23924. DynamicTexture.prototype.clear = function () {
  23925. var size = this.getSize();
  23926. this._context.fillRect(0, 0, size.width, size.height);
  23927. };
  23928. DynamicTexture.prototype.update = function (invertY) {
  23929. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  23930. };
  23931. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  23932. if (update === void 0) { update = true; }
  23933. var size = this.getSize();
  23934. if (clearColor) {
  23935. this._context.fillStyle = clearColor;
  23936. this._context.fillRect(0, 0, size.width, size.height);
  23937. }
  23938. this._context.font = font;
  23939. if (x === null) {
  23940. var textSize = this._context.measureText(text);
  23941. x = (size.width - textSize.width) / 2;
  23942. }
  23943. this._context.fillStyle = color;
  23944. this._context.fillText(text, x, y);
  23945. if (update) {
  23946. this.update(invertY);
  23947. }
  23948. };
  23949. DynamicTexture.prototype.clone = function () {
  23950. var textureSize = this.getSize();
  23951. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  23952. // Base texture
  23953. newTexture.hasAlpha = this.hasAlpha;
  23954. newTexture.level = this.level;
  23955. // Dynamic Texture
  23956. newTexture.wrapU = this.wrapU;
  23957. newTexture.wrapV = this.wrapV;
  23958. return newTexture;
  23959. };
  23960. return DynamicTexture;
  23961. }(BABYLON.Texture));
  23962. BABYLON.DynamicTexture = DynamicTexture;
  23963. })(BABYLON || (BABYLON = {}));
  23964. var BABYLON;
  23965. (function (BABYLON) {
  23966. var VideoTexture = (function (_super) {
  23967. __extends(VideoTexture, _super);
  23968. /**
  23969. * Creates a video texture.
  23970. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  23971. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  23972. * @param {BABYLON.Scene} scene is obviously the current scene.
  23973. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  23974. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  23975. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  23976. */
  23977. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  23978. var _this = this;
  23979. if (generateMipMaps === void 0) { generateMipMaps = false; }
  23980. if (invertY === void 0) { invertY = false; }
  23981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23982. _super.call(this, null, scene, !generateMipMaps, invertY);
  23983. this._autoLaunch = true;
  23984. var urls;
  23985. this.name = name;
  23986. if (urlsOrVideo instanceof HTMLVideoElement) {
  23987. this.video = urlsOrVideo;
  23988. }
  23989. else {
  23990. urls = urlsOrVideo;
  23991. this.video = document.createElement("video");
  23992. this.video.autoplay = false;
  23993. this.video.loop = true;
  23994. }
  23995. this._generateMipMaps = generateMipMaps;
  23996. this._samplingMode = samplingMode;
  23997. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  23998. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23999. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24000. }
  24001. else {
  24002. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24003. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24004. this._generateMipMaps = false;
  24005. }
  24006. if (urls) {
  24007. this.video.addEventListener("canplaythrough", function () {
  24008. _this._createTexture();
  24009. });
  24010. urls.forEach(function (url) {
  24011. var source = document.createElement("source");
  24012. source.src = url;
  24013. _this.video.appendChild(source);
  24014. });
  24015. }
  24016. else {
  24017. this._createTexture();
  24018. }
  24019. this._lastUpdate = BABYLON.Tools.Now;
  24020. }
  24021. VideoTexture.prototype._createTexture = function () {
  24022. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24023. this._texture.isReady = true;
  24024. };
  24025. VideoTexture.prototype.update = function () {
  24026. if (this._autoLaunch) {
  24027. this._autoLaunch = false;
  24028. this.video.play();
  24029. }
  24030. var now = BABYLON.Tools.Now;
  24031. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24032. return false;
  24033. }
  24034. this._lastUpdate = now;
  24035. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24036. return true;
  24037. };
  24038. return VideoTexture;
  24039. }(BABYLON.Texture));
  24040. BABYLON.VideoTexture = VideoTexture;
  24041. })(BABYLON || (BABYLON = {}));
  24042. var BABYLON;
  24043. (function (BABYLON) {
  24044. var CustomProceduralTexture = (function (_super) {
  24045. __extends(CustomProceduralTexture, _super);
  24046. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24047. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  24048. this._animate = true;
  24049. this._time = 0;
  24050. this._texturePath = texturePath;
  24051. //Try to load json
  24052. this.loadJson(texturePath);
  24053. this.refreshRate = 1;
  24054. }
  24055. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24056. var _this = this;
  24057. var that = this;
  24058. function noConfigFile() {
  24059. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24060. try {
  24061. that.setFragment(that._texturePath);
  24062. }
  24063. catch (ex) {
  24064. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24065. }
  24066. }
  24067. var configFileUrl = jsonUrl + "/config.json";
  24068. var xhr = new XMLHttpRequest();
  24069. xhr.open("GET", configFileUrl, true);
  24070. xhr.addEventListener("load", function () {
  24071. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24072. try {
  24073. _this._config = JSON.parse(xhr.response);
  24074. _this.updateShaderUniforms();
  24075. _this.updateTextures();
  24076. _this.setFragment(_this._texturePath + "/custom");
  24077. _this._animate = _this._config.animate;
  24078. _this.refreshRate = _this._config.refreshrate;
  24079. }
  24080. catch (ex) {
  24081. noConfigFile();
  24082. }
  24083. }
  24084. else {
  24085. noConfigFile();
  24086. }
  24087. }, false);
  24088. xhr.addEventListener("error", function () {
  24089. noConfigFile();
  24090. }, false);
  24091. try {
  24092. xhr.send();
  24093. }
  24094. catch (ex) {
  24095. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24096. }
  24097. };
  24098. CustomProceduralTexture.prototype.isReady = function () {
  24099. if (!_super.prototype.isReady.call(this)) {
  24100. return false;
  24101. }
  24102. for (var name in this._textures) {
  24103. var texture = this._textures[name];
  24104. if (!texture.isReady()) {
  24105. return false;
  24106. }
  24107. }
  24108. return true;
  24109. };
  24110. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24111. if (this._animate) {
  24112. this._time += this.getScene().getAnimationRatio() * 0.03;
  24113. this.updateShaderUniforms();
  24114. }
  24115. _super.prototype.render.call(this, useCameraPostProcess);
  24116. };
  24117. CustomProceduralTexture.prototype.updateTextures = function () {
  24118. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24119. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24120. }
  24121. };
  24122. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24123. if (this._config) {
  24124. for (var j = 0; j < this._config.uniforms.length; j++) {
  24125. var uniform = this._config.uniforms[j];
  24126. switch (uniform.type) {
  24127. case "float":
  24128. this.setFloat(uniform.name, uniform.value);
  24129. break;
  24130. case "color3":
  24131. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24132. break;
  24133. case "color4":
  24134. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24135. break;
  24136. case "vector2":
  24137. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24138. break;
  24139. case "vector3":
  24140. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24141. break;
  24142. }
  24143. }
  24144. }
  24145. this.setFloat("time", this._time);
  24146. };
  24147. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24148. get: function () {
  24149. return this._animate;
  24150. },
  24151. set: function (value) {
  24152. this._animate = value;
  24153. },
  24154. enumerable: true,
  24155. configurable: true
  24156. });
  24157. return CustomProceduralTexture;
  24158. }(BABYLON.ProceduralTexture));
  24159. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24160. })(BABYLON || (BABYLON = {}));
  24161. var BABYLON;
  24162. (function (BABYLON) {
  24163. var EffectFallbacks = (function () {
  24164. function EffectFallbacks() {
  24165. this._defines = {};
  24166. this._currentRank = 32;
  24167. this._maxRank = -1;
  24168. }
  24169. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24170. if (!this._defines[rank]) {
  24171. if (rank < this._currentRank) {
  24172. this._currentRank = rank;
  24173. }
  24174. if (rank > this._maxRank) {
  24175. this._maxRank = rank;
  24176. }
  24177. this._defines[rank] = new Array();
  24178. }
  24179. this._defines[rank].push(define);
  24180. };
  24181. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24182. this._meshRank = rank;
  24183. this._mesh = mesh;
  24184. if (rank > this._maxRank) {
  24185. this._maxRank = rank;
  24186. }
  24187. };
  24188. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24189. get: function () {
  24190. return this._currentRank <= this._maxRank;
  24191. },
  24192. enumerable: true,
  24193. configurable: true
  24194. });
  24195. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24196. var currentFallbacks = this._defines[this._currentRank];
  24197. for (var index = 0; index < currentFallbacks.length; index++) {
  24198. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24199. }
  24200. if (this._mesh && this._currentRank === this._meshRank) {
  24201. this._mesh.computeBonesUsingShaders = false;
  24202. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24203. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24204. }
  24205. this._currentRank++;
  24206. return currentDefines;
  24207. };
  24208. return EffectFallbacks;
  24209. }());
  24210. BABYLON.EffectFallbacks = EffectFallbacks;
  24211. var Effect = (function () {
  24212. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24213. var _this = this;
  24214. this._isReady = false;
  24215. this._compilationError = "";
  24216. this._valueCache = {};
  24217. this._engine = engine;
  24218. this.name = baseName;
  24219. this.defines = defines;
  24220. this._uniformsNames = uniformsNames.concat(samplers);
  24221. this._samplers = samplers;
  24222. this._attributesNames = attributesNames;
  24223. this.onError = onError;
  24224. this.onCompiled = onCompiled;
  24225. this._indexParameters = indexParameters;
  24226. var vertexSource;
  24227. var fragmentSource;
  24228. if (baseName.vertexElement) {
  24229. vertexSource = document.getElementById(baseName.vertexElement);
  24230. if (!vertexSource) {
  24231. vertexSource = baseName.vertexElement;
  24232. }
  24233. }
  24234. else {
  24235. vertexSource = baseName.vertex || baseName;
  24236. }
  24237. if (baseName.fragmentElement) {
  24238. fragmentSource = document.getElementById(baseName.fragmentElement);
  24239. if (!fragmentSource) {
  24240. fragmentSource = baseName.fragmentElement;
  24241. }
  24242. }
  24243. else {
  24244. fragmentSource = baseName.fragment || baseName;
  24245. }
  24246. this._loadVertexShader(vertexSource, function (vertexCode) {
  24247. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24250. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24251. });
  24252. });
  24253. });
  24254. });
  24255. }
  24256. // Properties
  24257. Effect.prototype.isReady = function () {
  24258. return this._isReady;
  24259. };
  24260. Effect.prototype.getProgram = function () {
  24261. return this._program;
  24262. };
  24263. Effect.prototype.getAttributesNames = function () {
  24264. return this._attributesNames;
  24265. };
  24266. Effect.prototype.getAttributeLocation = function (index) {
  24267. return this._attributes[index];
  24268. };
  24269. Effect.prototype.getAttributeLocationByName = function (name) {
  24270. var index = this._attributesNames.indexOf(name);
  24271. return this._attributes[index];
  24272. };
  24273. Effect.prototype.getAttributesCount = function () {
  24274. return this._attributes.length;
  24275. };
  24276. Effect.prototype.getUniformIndex = function (uniformName) {
  24277. return this._uniformsNames.indexOf(uniformName);
  24278. };
  24279. Effect.prototype.getUniform = function (uniformName) {
  24280. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24281. };
  24282. Effect.prototype.getSamplers = function () {
  24283. return this._samplers;
  24284. };
  24285. Effect.prototype.getCompilationError = function () {
  24286. return this._compilationError;
  24287. };
  24288. // Methods
  24289. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24290. // DOM element ?
  24291. if (vertex instanceof HTMLElement) {
  24292. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24293. callback(vertexCode);
  24294. return;
  24295. }
  24296. // Is in local store ?
  24297. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24298. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24299. return;
  24300. }
  24301. var vertexShaderUrl;
  24302. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24303. vertexShaderUrl = vertex;
  24304. }
  24305. else {
  24306. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24307. }
  24308. // Vertex shader
  24309. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24310. };
  24311. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24312. // DOM element ?
  24313. if (fragment instanceof HTMLElement) {
  24314. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24315. callback(fragmentCode);
  24316. return;
  24317. }
  24318. // Is in local store ?
  24319. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24320. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24321. return;
  24322. }
  24323. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24324. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24325. return;
  24326. }
  24327. var fragmentShaderUrl;
  24328. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24329. fragmentShaderUrl = fragment;
  24330. }
  24331. else {
  24332. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24333. }
  24334. // Fragment shader
  24335. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24336. };
  24337. Effect.prototype._dumpShadersName = function () {
  24338. if (this.name.vertexElement) {
  24339. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  24340. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  24341. }
  24342. else if (this.name.vertex) {
  24343. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  24344. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  24345. }
  24346. else {
  24347. BABYLON.Tools.Error("Vertex shader:" + this.name);
  24348. BABYLON.Tools.Error("Fragment shader:" + this.name);
  24349. }
  24350. };
  24351. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24352. var _this = this;
  24353. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24354. var match = regex.exec(sourceCode);
  24355. var returnValue = new String(sourceCode);
  24356. while (match != null) {
  24357. var includeFile = match[1];
  24358. if (Effect.IncludesShadersStore[includeFile]) {
  24359. // Substitution
  24360. var includeContent = Effect.IncludesShadersStore[includeFile];
  24361. if (match[2]) {
  24362. var splits = match[3].split(",");
  24363. for (var index = 0; index < splits.length; index += 2) {
  24364. var source = new RegExp(splits[index], "g");
  24365. var dest = splits[index + 1];
  24366. includeContent = includeContent.replace(source, dest);
  24367. }
  24368. }
  24369. if (match[4]) {
  24370. var indexString = match[5];
  24371. if (indexString.indexOf("..") !== -1) {
  24372. var indexSplits = indexString.split("..");
  24373. var minIndex = parseInt(indexSplits[0]);
  24374. var maxIndex = parseInt(indexSplits[1]);
  24375. var sourceIncludeContent = includeContent.slice(0);
  24376. includeContent = "";
  24377. if (isNaN(maxIndex)) {
  24378. maxIndex = this._indexParameters[indexSplits[1]];
  24379. }
  24380. for (var i = minIndex; i <= maxIndex; i++) {
  24381. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24382. }
  24383. }
  24384. else {
  24385. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24386. }
  24387. }
  24388. // Replace
  24389. returnValue = returnValue.replace(match[0], includeContent);
  24390. }
  24391. else {
  24392. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24393. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24394. Effect.IncludesShadersStore[includeFile] = fileContent;
  24395. _this._processIncludes(returnValue, callback);
  24396. });
  24397. return;
  24398. }
  24399. match = regex.exec(sourceCode);
  24400. }
  24401. callback(returnValue);
  24402. };
  24403. Effect.prototype._processPrecision = function (source) {
  24404. if (source.indexOf("precision highp float") === -1) {
  24405. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24406. source = "precision mediump float;\n" + source;
  24407. }
  24408. else {
  24409. source = "precision highp float;\n" + source;
  24410. }
  24411. }
  24412. else {
  24413. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24414. source = source.replace("precision highp float", "precision mediump float");
  24415. }
  24416. }
  24417. return source;
  24418. };
  24419. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  24420. try {
  24421. var engine = this._engine;
  24422. // Precision
  24423. vertexSourceCode = this._processPrecision(vertexSourceCode);
  24424. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  24425. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  24426. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24427. this._attributes = engine.getAttributes(this._program, attributesNames);
  24428. var index;
  24429. for (index = 0; index < this._samplers.length; index++) {
  24430. var sampler = this.getUniform(this._samplers[index]);
  24431. if (sampler == null) {
  24432. this._samplers.splice(index, 1);
  24433. index--;
  24434. }
  24435. }
  24436. engine.bindSamplers(this);
  24437. this._isReady = true;
  24438. if (this.onCompiled) {
  24439. this.onCompiled(this);
  24440. }
  24441. }
  24442. catch (e) {
  24443. // Let's go through fallbacks then
  24444. if (fallbacks && fallbacks.isMoreFallbacks) {
  24445. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  24446. this._dumpShadersName();
  24447. defines = fallbacks.reduce(defines);
  24448. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  24449. }
  24450. else {
  24451. BABYLON.Tools.Error("Unable to compile effect: ");
  24452. this._dumpShadersName();
  24453. BABYLON.Tools.Error("Defines: " + defines);
  24454. BABYLON.Tools.Error("Error: " + e.message);
  24455. this._compilationError = e.message;
  24456. if (this.onError) {
  24457. this.onError(this, this._compilationError);
  24458. }
  24459. }
  24460. }
  24461. };
  24462. Object.defineProperty(Effect.prototype, "isSupported", {
  24463. get: function () {
  24464. return this._compilationError === "";
  24465. },
  24466. enumerable: true,
  24467. configurable: true
  24468. });
  24469. Effect.prototype._bindTexture = function (channel, texture) {
  24470. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24471. };
  24472. Effect.prototype.setTexture = function (channel, texture) {
  24473. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24474. };
  24475. Effect.prototype.setTextureArray = function (channel, textures) {
  24476. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24477. var initialPos = this._samplers.indexOf(channel);
  24478. for (var index = 1; index < textures.length; index++) {
  24479. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24480. }
  24481. }
  24482. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24483. };
  24484. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24485. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24486. };
  24487. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24488. var changed = false;
  24489. var cache = this._valueCache[uniformName];
  24490. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  24491. changed = true;
  24492. cache = new BABYLON.Matrix();
  24493. }
  24494. var tm = cache.m;
  24495. var om = matrix.m;
  24496. for (var index = 0; index < 16; index++) {
  24497. if (tm[index] !== om[index]) {
  24498. tm[index] = om[index];
  24499. changed = true;
  24500. }
  24501. }
  24502. this._valueCache[uniformName] = cache;
  24503. return changed;
  24504. };
  24505. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24506. var cache = this._valueCache[uniformName];
  24507. if (!cache) {
  24508. cache = [x, y];
  24509. this._valueCache[uniformName] = cache;
  24510. return true;
  24511. }
  24512. var changed = false;
  24513. if (cache[0] !== x) {
  24514. cache[0] = x;
  24515. changed = true;
  24516. }
  24517. if (cache[1] !== y) {
  24518. cache[1] = y;
  24519. changed = true;
  24520. }
  24521. return changed;
  24522. };
  24523. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24524. var cache = this._valueCache[uniformName];
  24525. if (!cache) {
  24526. cache = [x, y, z];
  24527. this._valueCache[uniformName] = cache;
  24528. return true;
  24529. }
  24530. var changed = false;
  24531. if (cache[0] !== x) {
  24532. cache[0] = x;
  24533. changed = true;
  24534. }
  24535. if (cache[1] !== y) {
  24536. cache[1] = y;
  24537. changed = true;
  24538. }
  24539. if (cache[2] !== z) {
  24540. cache[2] = z;
  24541. changed = true;
  24542. }
  24543. return changed;
  24544. };
  24545. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24546. var cache = this._valueCache[uniformName];
  24547. if (!cache) {
  24548. cache = [x, y, z, w];
  24549. this._valueCache[uniformName] = cache;
  24550. return true;
  24551. }
  24552. var changed = false;
  24553. if (cache[0] !== x) {
  24554. cache[0] = x;
  24555. changed = true;
  24556. }
  24557. if (cache[1] !== y) {
  24558. cache[1] = y;
  24559. changed = true;
  24560. }
  24561. if (cache[2] !== z) {
  24562. cache[2] = z;
  24563. changed = true;
  24564. }
  24565. if (cache[3] !== w) {
  24566. cache[3] = w;
  24567. changed = true;
  24568. }
  24569. return changed;
  24570. };
  24571. Effect.prototype.setIntArray = function (uniformName, array) {
  24572. this._valueCache[uniformName] = null;
  24573. this._engine.setIntArray(this.getUniform(uniformName), array);
  24574. return this;
  24575. };
  24576. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24577. this._valueCache[uniformName] = null;
  24578. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24579. return this;
  24580. };
  24581. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24582. this._valueCache[uniformName] = null;
  24583. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24584. return this;
  24585. };
  24586. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24587. this._valueCache[uniformName] = null;
  24588. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24589. return this;
  24590. };
  24591. Effect.prototype.setFloatArray = function (uniformName, array) {
  24592. this._valueCache[uniformName] = null;
  24593. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24594. return this;
  24595. };
  24596. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24597. this._valueCache[uniformName] = null;
  24598. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24599. return this;
  24600. };
  24601. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24602. this._valueCache[uniformName] = null;
  24603. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24604. return this;
  24605. };
  24606. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24607. this._valueCache[uniformName] = null;
  24608. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24609. return this;
  24610. };
  24611. Effect.prototype.setArray = function (uniformName, array) {
  24612. this._valueCache[uniformName] = null;
  24613. this._engine.setArray(this.getUniform(uniformName), array);
  24614. return this;
  24615. };
  24616. Effect.prototype.setArray2 = function (uniformName, array) {
  24617. this._valueCache[uniformName] = null;
  24618. this._engine.setArray2(this.getUniform(uniformName), array);
  24619. return this;
  24620. };
  24621. Effect.prototype.setArray3 = function (uniformName, array) {
  24622. this._valueCache[uniformName] = null;
  24623. this._engine.setArray3(this.getUniform(uniformName), array);
  24624. return this;
  24625. };
  24626. Effect.prototype.setArray4 = function (uniformName, array) {
  24627. this._valueCache[uniformName] = null;
  24628. this._engine.setArray4(this.getUniform(uniformName), array);
  24629. return this;
  24630. };
  24631. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24632. this._valueCache[uniformName] = null;
  24633. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24634. return this;
  24635. };
  24636. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24637. if (this._cacheMatrix(uniformName, matrix)) {
  24638. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24639. }
  24640. return this;
  24641. };
  24642. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24643. this._valueCache[uniformName] = null;
  24644. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24645. return this;
  24646. };
  24647. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24648. this._valueCache[uniformName] = null;
  24649. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24650. return this;
  24651. };
  24652. Effect.prototype.setFloat = function (uniformName, value) {
  24653. var cache = this._valueCache[uniformName];
  24654. if (cache !== undefined && cache === value)
  24655. return this;
  24656. this._valueCache[uniformName] = value;
  24657. this._engine.setFloat(this.getUniform(uniformName), value);
  24658. return this;
  24659. };
  24660. Effect.prototype.setBool = function (uniformName, bool) {
  24661. var cache = this._valueCache[uniformName];
  24662. if (cache !== undefined && cache === bool)
  24663. return this;
  24664. this._valueCache[uniformName] = bool;
  24665. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24666. return this;
  24667. };
  24668. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24669. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24670. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24671. }
  24672. return this;
  24673. };
  24674. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24675. if (this._cacheFloat2(uniformName, x, y)) {
  24676. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24677. }
  24678. return this;
  24679. };
  24680. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24681. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24682. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24683. }
  24684. return this;
  24685. };
  24686. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24687. if (this._cacheFloat3(uniformName, x, y, z)) {
  24688. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24689. }
  24690. return this;
  24691. };
  24692. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24693. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24694. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24695. }
  24696. return this;
  24697. };
  24698. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24699. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24700. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24701. }
  24702. return this;
  24703. };
  24704. Effect.prototype.setColor3 = function (uniformName, color3) {
  24705. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24706. this._engine.setColor3(this.getUniform(uniformName), color3);
  24707. }
  24708. return this;
  24709. };
  24710. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24711. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24712. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24713. }
  24714. return this;
  24715. };
  24716. // Statics
  24717. Effect.ShadersStore = {};
  24718. Effect.IncludesShadersStore = {};
  24719. return Effect;
  24720. }());
  24721. BABYLON.Effect = Effect;
  24722. })(BABYLON || (BABYLON = {}));
  24723. var BABYLON;
  24724. (function (BABYLON) {
  24725. var MaterialHelper = (function () {
  24726. function MaterialHelper() {
  24727. }
  24728. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24729. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24730. var lightIndex = 0;
  24731. var needNormals = false;
  24732. var needRebuild = false;
  24733. var needShadows = false;
  24734. var lightmapMode = false;
  24735. for (var index = 0; index < scene.lights.length; index++) {
  24736. var light = scene.lights[index];
  24737. if (!light.isEnabled()) {
  24738. continue;
  24739. }
  24740. // Excluded check
  24741. if (light._excludedMeshesIds.length > 0) {
  24742. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24743. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24744. if (excludedMesh) {
  24745. light.excludedMeshes.push(excludedMesh);
  24746. }
  24747. }
  24748. light._excludedMeshesIds = [];
  24749. }
  24750. // Included check
  24751. if (light._includedOnlyMeshesIds.length > 0) {
  24752. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24753. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24754. if (includedOnlyMesh) {
  24755. light.includedOnlyMeshes.push(includedOnlyMesh);
  24756. }
  24757. }
  24758. light._includedOnlyMeshesIds = [];
  24759. }
  24760. if (!light.canAffectMesh(mesh)) {
  24761. continue;
  24762. }
  24763. needNormals = true;
  24764. if (defines["LIGHT" + lightIndex] === undefined) {
  24765. needRebuild = true;
  24766. }
  24767. defines["LIGHT" + lightIndex] = true;
  24768. var type;
  24769. if (light instanceof BABYLON.SpotLight) {
  24770. type = "SPOTLIGHT" + lightIndex;
  24771. }
  24772. else if (light instanceof BABYLON.HemisphericLight) {
  24773. type = "HEMILIGHT" + lightIndex;
  24774. }
  24775. else if (light instanceof BABYLON.PointLight) {
  24776. type = "POINTLIGHT" + lightIndex;
  24777. }
  24778. else {
  24779. type = "DIRLIGHT" + lightIndex;
  24780. }
  24781. if (defines[type] === undefined) {
  24782. needRebuild = true;
  24783. }
  24784. defines[type] = true;
  24785. // Specular
  24786. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  24787. defines["SPECULARTERM"] = true;
  24788. }
  24789. // Shadows
  24790. if (scene.shadowsEnabled) {
  24791. var shadowGenerator = light.getShadowGenerator();
  24792. if (mesh && mesh.receiveShadows && shadowGenerator) {
  24793. if (defines["SHADOW" + lightIndex] === undefined) {
  24794. needRebuild = true;
  24795. }
  24796. defines["SHADOW" + lightIndex] = true;
  24797. defines["SHADOWS"] = true;
  24798. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  24799. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  24800. needRebuild = true;
  24801. }
  24802. defines["SHADOWVSM" + lightIndex] = true;
  24803. }
  24804. if (shadowGenerator.usePoissonSampling) {
  24805. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  24806. needRebuild = true;
  24807. }
  24808. defines["SHADOWPCF" + lightIndex] = true;
  24809. }
  24810. needShadows = true;
  24811. }
  24812. }
  24813. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24814. lightmapMode = true;
  24815. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  24816. needRebuild = true;
  24817. }
  24818. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  24819. needRebuild = true;
  24820. }
  24821. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24822. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  24823. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  24824. }
  24825. }
  24826. lightIndex++;
  24827. if (lightIndex === maxSimultaneousLights)
  24828. break;
  24829. }
  24830. var caps = scene.getEngine().getCaps();
  24831. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  24832. if (defines["SHADOWFULLFLOAT"] === undefined) {
  24833. needRebuild = true;
  24834. }
  24835. defines["SHADOWFULLFLOAT"] = true;
  24836. }
  24837. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  24838. needRebuild = true;
  24839. }
  24840. if (lightmapMode) {
  24841. defines["LIGHTMAPEXCLUDED"] = true;
  24842. }
  24843. if (needRebuild) {
  24844. defines.rebuild();
  24845. }
  24846. return needNormals;
  24847. };
  24848. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  24849. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24850. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24851. if (!defines["LIGHT" + lightIndex]) {
  24852. break;
  24853. }
  24854. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  24855. samplersList.push("shadowSampler" + lightIndex);
  24856. }
  24857. };
  24858. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24859. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24860. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24861. if (!defines["LIGHT" + lightIndex]) {
  24862. break;
  24863. }
  24864. if (lightIndex > 0) {
  24865. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24866. }
  24867. if (defines["SHADOW" + lightIndex]) {
  24868. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24869. }
  24870. if (defines["SHADOWPCF" + lightIndex]) {
  24871. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24872. }
  24873. if (defines["SHADOWVSM" + lightIndex]) {
  24874. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  24875. }
  24876. }
  24877. };
  24878. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24879. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24880. fallbacks.addCPUSkinningFallback(0, mesh);
  24881. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24882. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24883. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24884. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24885. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24886. }
  24887. }
  24888. };
  24889. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24890. if (defines["INSTANCES"]) {
  24891. attribs.push("world0");
  24892. attribs.push("world1");
  24893. attribs.push("world2");
  24894. attribs.push("world3");
  24895. }
  24896. };
  24897. // Bindings
  24898. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  24899. var shadowGenerator = light.getShadowGenerator();
  24900. if (mesh.receiveShadows && shadowGenerator) {
  24901. if (!light.needCube()) {
  24902. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  24903. }
  24904. else {
  24905. if (!depthValuesAlreadySet) {
  24906. depthValuesAlreadySet = true;
  24907. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  24908. }
  24909. }
  24910. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  24911. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  24912. }
  24913. return depthValuesAlreadySet;
  24914. };
  24915. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24916. if (light instanceof BABYLON.PointLight) {
  24917. // Point Light
  24918. light.transferToEffect(effect, "vLightData" + lightIndex);
  24919. }
  24920. else if (light instanceof BABYLON.DirectionalLight) {
  24921. // Directional Light
  24922. light.transferToEffect(effect, "vLightData" + lightIndex);
  24923. }
  24924. else if (light instanceof BABYLON.SpotLight) {
  24925. // Spot Light
  24926. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  24927. }
  24928. else if (light instanceof BABYLON.HemisphericLight) {
  24929. // Hemispheric Light
  24930. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  24931. }
  24932. };
  24933. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  24934. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24935. var lightIndex = 0;
  24936. var depthValuesAlreadySet = false;
  24937. for (var index = 0; index < scene.lights.length; index++) {
  24938. var light = scene.lights[index];
  24939. if (!light.isEnabled()) {
  24940. continue;
  24941. }
  24942. if (!light.canAffectMesh(mesh)) {
  24943. continue;
  24944. }
  24945. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24946. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  24947. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  24948. if (defines["SPECULARTERM"]) {
  24949. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  24950. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  24951. }
  24952. // Shadows
  24953. if (scene.shadowsEnabled) {
  24954. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  24955. }
  24956. lightIndex++;
  24957. if (lightIndex === maxSimultaneousLights)
  24958. break;
  24959. }
  24960. };
  24961. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24962. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24963. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24964. effect.setColor3("vFogColor", scene.fogColor);
  24965. }
  24966. };
  24967. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24968. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24969. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  24970. if (matrices) {
  24971. effect.setMatrices("mBones", matrices);
  24972. }
  24973. }
  24974. };
  24975. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24976. if (defines["LOGARITHMICDEPTH"]) {
  24977. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24978. }
  24979. };
  24980. MaterialHelper.BindClipPlane = function (effect, scene) {
  24981. if (scene.clipPlane) {
  24982. var clipPlane = scene.clipPlane;
  24983. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24984. }
  24985. };
  24986. return MaterialHelper;
  24987. }());
  24988. BABYLON.MaterialHelper = MaterialHelper;
  24989. })(BABYLON || (BABYLON = {}));
  24990. var BABYLON;
  24991. (function (BABYLON) {
  24992. var FresnelParameters = (function () {
  24993. function FresnelParameters() {
  24994. this.isEnabled = true;
  24995. this.leftColor = BABYLON.Color3.White();
  24996. this.rightColor = BABYLON.Color3.Black();
  24997. this.bias = 0;
  24998. this.power = 1;
  24999. }
  25000. FresnelParameters.prototype.clone = function () {
  25001. var newFresnelParameters = new FresnelParameters();
  25002. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25003. return new FresnelParameters;
  25004. };
  25005. FresnelParameters.prototype.serialize = function () {
  25006. var serializationObject = {};
  25007. serializationObject.isEnabled = this.isEnabled;
  25008. serializationObject.leftColor = this.leftColor;
  25009. serializationObject.rightColor = this.rightColor;
  25010. serializationObject.bias = this.bias;
  25011. serializationObject.power = this.power;
  25012. return serializationObject;
  25013. };
  25014. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25015. var fresnelParameters = new FresnelParameters();
  25016. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25017. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25018. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25019. fresnelParameters.bias = parsedFresnelParameters.bias;
  25020. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25021. return fresnelParameters;
  25022. };
  25023. return FresnelParameters;
  25024. }());
  25025. BABYLON.FresnelParameters = FresnelParameters;
  25026. })(BABYLON || (BABYLON = {}));
  25027. var BABYLON;
  25028. (function (BABYLON) {
  25029. var MaterialDefines = (function () {
  25030. function MaterialDefines() {
  25031. }
  25032. MaterialDefines.prototype.rebuild = function () {
  25033. if (this._keys) {
  25034. delete this._keys;
  25035. }
  25036. this._keys = Object.keys(this);
  25037. };
  25038. MaterialDefines.prototype.isEqual = function (other) {
  25039. if (this._keys.length !== other._keys.length) {
  25040. return false;
  25041. }
  25042. for (var index = 0; index < this._keys.length; index++) {
  25043. var prop = this._keys[index];
  25044. if (this[prop] !== other[prop]) {
  25045. return false;
  25046. }
  25047. }
  25048. return true;
  25049. };
  25050. MaterialDefines.prototype.cloneTo = function (other) {
  25051. if (this._keys.length !== other._keys.length) {
  25052. other._keys = this._keys.slice(0);
  25053. }
  25054. for (var index = 0; index < this._keys.length; index++) {
  25055. var prop = this._keys[index];
  25056. other[prop] = this[prop];
  25057. }
  25058. };
  25059. MaterialDefines.prototype.reset = function () {
  25060. for (var index = 0; index < this._keys.length; index++) {
  25061. var prop = this._keys[index];
  25062. if (typeof (this[prop]) === "number") {
  25063. this[prop] = 0;
  25064. }
  25065. else {
  25066. this[prop] = false;
  25067. }
  25068. }
  25069. };
  25070. MaterialDefines.prototype.toString = function () {
  25071. var result = "";
  25072. for (var index = 0; index < this._keys.length; index++) {
  25073. var prop = this._keys[index];
  25074. if (typeof (this[prop]) === "number") {
  25075. result += "#define " + prop + " " + this[prop] + "\n";
  25076. }
  25077. else if (this[prop]) {
  25078. result += "#define " + prop + "\n";
  25079. }
  25080. }
  25081. return result;
  25082. };
  25083. return MaterialDefines;
  25084. }());
  25085. BABYLON.MaterialDefines = MaterialDefines;
  25086. var Material = (function () {
  25087. function Material(name, scene, doNotAdd) {
  25088. this.name = name;
  25089. this.checkReadyOnEveryCall = false;
  25090. this.checkReadyOnlyOnce = false;
  25091. this.state = "";
  25092. this.alpha = 1.0;
  25093. this.backFaceCulling = true;
  25094. /**
  25095. * An event triggered when the material is disposed.
  25096. * @type {BABYLON.Observable}
  25097. */
  25098. this.onDisposeObservable = new BABYLON.Observable();
  25099. /**
  25100. * An event triggered when the material is bound.
  25101. * @type {BABYLON.Observable}
  25102. */
  25103. this.onBindObservable = new BABYLON.Observable();
  25104. /**
  25105. * An event triggered when the material is unbound.
  25106. * @type {BABYLON.Observable}
  25107. */
  25108. this.onUnBindObservable = new BABYLON.Observable();
  25109. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25110. this.disableDepthWrite = false;
  25111. this.fogEnabled = true;
  25112. this.pointSize = 1.0;
  25113. this.zOffset = 0;
  25114. this._wasPreviouslyReady = false;
  25115. this._fillMode = Material.TriangleFillMode;
  25116. this.id = name;
  25117. this._scene = scene;
  25118. if (scene.useRightHandedSystem) {
  25119. this.sideOrientation = Material.ClockWiseSideOrientation;
  25120. }
  25121. else {
  25122. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25123. }
  25124. if (!doNotAdd) {
  25125. scene.materials.push(this);
  25126. }
  25127. }
  25128. Object.defineProperty(Material, "TriangleFillMode", {
  25129. get: function () {
  25130. return Material._TriangleFillMode;
  25131. },
  25132. enumerable: true,
  25133. configurable: true
  25134. });
  25135. Object.defineProperty(Material, "WireFrameFillMode", {
  25136. get: function () {
  25137. return Material._WireFrameFillMode;
  25138. },
  25139. enumerable: true,
  25140. configurable: true
  25141. });
  25142. Object.defineProperty(Material, "PointFillMode", {
  25143. get: function () {
  25144. return Material._PointFillMode;
  25145. },
  25146. enumerable: true,
  25147. configurable: true
  25148. });
  25149. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25150. get: function () {
  25151. return Material._ClockWiseSideOrientation;
  25152. },
  25153. enumerable: true,
  25154. configurable: true
  25155. });
  25156. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25157. get: function () {
  25158. return Material._CounterClockWiseSideOrientation;
  25159. },
  25160. enumerable: true,
  25161. configurable: true
  25162. });
  25163. Object.defineProperty(Material.prototype, "onDispose", {
  25164. set: function (callback) {
  25165. if (this._onDisposeObserver) {
  25166. this.onDisposeObservable.remove(this._onDisposeObserver);
  25167. }
  25168. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25169. },
  25170. enumerable: true,
  25171. configurable: true
  25172. });
  25173. Object.defineProperty(Material.prototype, "onBind", {
  25174. set: function (callback) {
  25175. if (this._onBindObserver) {
  25176. this.onBindObservable.remove(this._onBindObserver);
  25177. }
  25178. this._onBindObserver = this.onBindObservable.add(callback);
  25179. },
  25180. enumerable: true,
  25181. configurable: true
  25182. });
  25183. Object.defineProperty(Material.prototype, "wireframe", {
  25184. get: function () {
  25185. return this._fillMode === Material.WireFrameFillMode;
  25186. },
  25187. set: function (value) {
  25188. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25189. },
  25190. enumerable: true,
  25191. configurable: true
  25192. });
  25193. Object.defineProperty(Material.prototype, "pointsCloud", {
  25194. get: function () {
  25195. return this._fillMode === Material.PointFillMode;
  25196. },
  25197. set: function (value) {
  25198. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25199. },
  25200. enumerable: true,
  25201. configurable: true
  25202. });
  25203. Object.defineProperty(Material.prototype, "fillMode", {
  25204. get: function () {
  25205. return this._fillMode;
  25206. },
  25207. set: function (value) {
  25208. this._fillMode = value;
  25209. },
  25210. enumerable: true,
  25211. configurable: true
  25212. });
  25213. /**
  25214. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25215. * subclasses should override adding information pertainent to themselves
  25216. */
  25217. Material.prototype.toString = function (fullDetails) {
  25218. var ret = "Name: " + this.name;
  25219. if (fullDetails) {
  25220. }
  25221. return ret;
  25222. };
  25223. Object.defineProperty(Material.prototype, "isFrozen", {
  25224. get: function () {
  25225. return this.checkReadyOnlyOnce;
  25226. },
  25227. enumerable: true,
  25228. configurable: true
  25229. });
  25230. Material.prototype.freeze = function () {
  25231. this.checkReadyOnlyOnce = true;
  25232. };
  25233. Material.prototype.unfreeze = function () {
  25234. this.checkReadyOnlyOnce = false;
  25235. };
  25236. Material.prototype.isReady = function (mesh, useInstances) {
  25237. return true;
  25238. };
  25239. Material.prototype.getEffect = function () {
  25240. return this._effect;
  25241. };
  25242. Material.prototype.getScene = function () {
  25243. return this._scene;
  25244. };
  25245. Material.prototype.needAlphaBlending = function () {
  25246. return (this.alpha < 1.0);
  25247. };
  25248. Material.prototype.needAlphaTesting = function () {
  25249. return false;
  25250. };
  25251. Material.prototype.getAlphaTestTexture = function () {
  25252. return null;
  25253. };
  25254. Material.prototype.markDirty = function () {
  25255. this._wasPreviouslyReady = false;
  25256. };
  25257. Material.prototype._preBind = function () {
  25258. var engine = this._scene.getEngine();
  25259. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25260. engine.enableEffect(this._effect);
  25261. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25262. };
  25263. Material.prototype.bind = function (world, mesh) {
  25264. this._scene._cachedMaterial = this;
  25265. this.onBindObservable.notifyObservers(mesh);
  25266. if (this.disableDepthWrite) {
  25267. var engine = this._scene.getEngine();
  25268. this._cachedDepthWriteState = engine.getDepthWrite();
  25269. engine.setDepthWrite(false);
  25270. }
  25271. };
  25272. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25273. };
  25274. Material.prototype.unbind = function () {
  25275. this.onUnBindObservable.notifyObservers(this);
  25276. if (this.disableDepthWrite) {
  25277. var engine = this._scene.getEngine();
  25278. engine.setDepthWrite(this._cachedDepthWriteState);
  25279. }
  25280. };
  25281. Material.prototype.clone = function (name) {
  25282. return null;
  25283. };
  25284. Material.prototype.getBindedMeshes = function () {
  25285. var result = new Array();
  25286. for (var index = 0; index < this._scene.meshes.length; index++) {
  25287. var mesh = this._scene.meshes[index];
  25288. if (mesh.material === this) {
  25289. result.push(mesh);
  25290. }
  25291. }
  25292. return result;
  25293. };
  25294. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25295. // Animations
  25296. this.getScene().stopAnimation(this);
  25297. // Remove from scene
  25298. var index = this._scene.materials.indexOf(this);
  25299. if (index >= 0) {
  25300. this._scene.materials.splice(index, 1);
  25301. }
  25302. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25303. if (forceDisposeEffect && this._effect) {
  25304. this._scene.getEngine()._releaseEffect(this._effect);
  25305. this._effect = null;
  25306. }
  25307. // Remove from meshes
  25308. for (index = 0; index < this._scene.meshes.length; index++) {
  25309. var mesh = this._scene.meshes[index];
  25310. if (mesh.material === this) {
  25311. mesh.material = null;
  25312. }
  25313. }
  25314. // Callback
  25315. this.onDisposeObservable.notifyObservers(this);
  25316. this.onDisposeObservable.clear();
  25317. this.onBindObservable.clear();
  25318. this.onUnBindObservable.clear();
  25319. };
  25320. Material.prototype.serialize = function () {
  25321. return BABYLON.SerializationHelper.Serialize(this);
  25322. };
  25323. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25324. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25325. multiMaterial.id = parsedMultiMaterial.id;
  25326. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25327. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25328. var subMatId = parsedMultiMaterial.materials[matIndex];
  25329. if (subMatId) {
  25330. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25331. }
  25332. else {
  25333. multiMaterial.subMaterials.push(null);
  25334. }
  25335. }
  25336. return multiMaterial;
  25337. };
  25338. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25339. if (!parsedMaterial.customType) {
  25340. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25341. }
  25342. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25343. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25344. ;
  25345. };
  25346. Material._TriangleFillMode = 0;
  25347. Material._WireFrameFillMode = 1;
  25348. Material._PointFillMode = 2;
  25349. Material._ClockWiseSideOrientation = 0;
  25350. Material._CounterClockWiseSideOrientation = 1;
  25351. __decorate([
  25352. BABYLON.serialize()
  25353. ], Material.prototype, "id", void 0);
  25354. __decorate([
  25355. BABYLON.serialize()
  25356. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25357. __decorate([
  25358. BABYLON.serialize()
  25359. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25360. __decorate([
  25361. BABYLON.serialize()
  25362. ], Material.prototype, "state", void 0);
  25363. __decorate([
  25364. BABYLON.serialize()
  25365. ], Material.prototype, "alpha", void 0);
  25366. __decorate([
  25367. BABYLON.serialize()
  25368. ], Material.prototype, "backFaceCulling", void 0);
  25369. __decorate([
  25370. BABYLON.serialize()
  25371. ], Material.prototype, "sideOrientation", void 0);
  25372. __decorate([
  25373. BABYLON.serialize()
  25374. ], Material.prototype, "alphaMode", void 0);
  25375. __decorate([
  25376. BABYLON.serialize()
  25377. ], Material.prototype, "disableDepthWrite", void 0);
  25378. __decorate([
  25379. BABYLON.serialize()
  25380. ], Material.prototype, "fogEnabled", void 0);
  25381. __decorate([
  25382. BABYLON.serialize()
  25383. ], Material.prototype, "pointSize", void 0);
  25384. __decorate([
  25385. BABYLON.serialize()
  25386. ], Material.prototype, "zOffset", void 0);
  25387. __decorate([
  25388. BABYLON.serialize()
  25389. ], Material.prototype, "wireframe", null);
  25390. __decorate([
  25391. BABYLON.serialize()
  25392. ], Material.prototype, "pointsCloud", null);
  25393. __decorate([
  25394. BABYLON.serialize()
  25395. ], Material.prototype, "fillMode", null);
  25396. return Material;
  25397. }());
  25398. BABYLON.Material = Material;
  25399. })(BABYLON || (BABYLON = {}));
  25400. var BABYLON;
  25401. (function (BABYLON) {
  25402. var StandardMaterialDefines = (function (_super) {
  25403. __extends(StandardMaterialDefines, _super);
  25404. function StandardMaterialDefines() {
  25405. _super.call(this);
  25406. this.DIFFUSE = false;
  25407. this.AMBIENT = false;
  25408. this.OPACITY = false;
  25409. this.OPACITYRGB = false;
  25410. this.REFLECTION = false;
  25411. this.EMISSIVE = false;
  25412. this.SPECULAR = false;
  25413. this.BUMP = false;
  25414. this.PARALLAX = false;
  25415. this.PARALLAXOCCLUSION = false;
  25416. this.SPECULAROVERALPHA = false;
  25417. this.CLIPPLANE = false;
  25418. this.ALPHATEST = false;
  25419. this.ALPHAFROMDIFFUSE = false;
  25420. this.POINTSIZE = false;
  25421. this.FOG = false;
  25422. this.SPECULARTERM = false;
  25423. this.DIFFUSEFRESNEL = false;
  25424. this.OPACITYFRESNEL = false;
  25425. this.REFLECTIONFRESNEL = false;
  25426. this.REFRACTIONFRESNEL = false;
  25427. this.EMISSIVEFRESNEL = false;
  25428. this.FRESNEL = false;
  25429. this.NORMAL = false;
  25430. this.UV1 = false;
  25431. this.UV2 = false;
  25432. this.VERTEXCOLOR = false;
  25433. this.VERTEXALPHA = false;
  25434. this.NUM_BONE_INFLUENCERS = 0;
  25435. this.BonesPerMesh = 0;
  25436. this.INSTANCES = false;
  25437. this.GLOSSINESS = false;
  25438. this.ROUGHNESS = false;
  25439. this.EMISSIVEASILLUMINATION = false;
  25440. this.LINKEMISSIVEWITHDIFFUSE = false;
  25441. this.REFLECTIONFRESNELFROMSPECULAR = false;
  25442. this.LIGHTMAP = false;
  25443. this.USELIGHTMAPASSHADOWMAP = false;
  25444. this.REFLECTIONMAP_3D = false;
  25445. this.REFLECTIONMAP_SPHERICAL = false;
  25446. this.REFLECTIONMAP_PLANAR = false;
  25447. this.REFLECTIONMAP_CUBIC = false;
  25448. this.REFLECTIONMAP_PROJECTION = false;
  25449. this.REFLECTIONMAP_SKYBOX = false;
  25450. this.REFLECTIONMAP_EXPLICIT = false;
  25451. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  25452. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  25453. this.INVERTCUBICMAP = false;
  25454. this.LOGARITHMICDEPTH = false;
  25455. this.REFRACTION = false;
  25456. this.REFRACTIONMAP_3D = false;
  25457. this.REFLECTIONOVERALPHA = false;
  25458. this.INVERTNORMALMAPX = false;
  25459. this.INVERTNORMALMAPY = false;
  25460. this.SHADOWFULLFLOAT = false;
  25461. this.CAMERACOLORGRADING = false;
  25462. this.CAMERACOLORCURVES = false;
  25463. this.rebuild();
  25464. }
  25465. return StandardMaterialDefines;
  25466. }(BABYLON.MaterialDefines));
  25467. var StandardMaterial = (function (_super) {
  25468. __extends(StandardMaterial, _super);
  25469. function StandardMaterial(name, scene) {
  25470. var _this = this;
  25471. _super.call(this, name, scene);
  25472. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25473. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  25474. this.specularColor = new BABYLON.Color3(1, 1, 1);
  25475. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  25476. this.specularPower = 64;
  25477. this.useAlphaFromDiffuseTexture = false;
  25478. this.useEmissiveAsIllumination = false;
  25479. this.linkEmissiveWithDiffuse = false;
  25480. this.useReflectionFresnelFromSpecular = false;
  25481. this.useSpecularOverAlpha = false;
  25482. this.useReflectionOverAlpha = false;
  25483. this.disableLighting = false;
  25484. this.useParallax = false;
  25485. this.useParallaxOcclusion = false;
  25486. this.parallaxScaleBias = 0.05;
  25487. this.roughness = 0;
  25488. this.indexOfRefraction = 0.98;
  25489. this.invertRefractionY = true;
  25490. this.useLightmapAsShadowmap = false;
  25491. this.useGlossinessFromSpecularMapAlpha = false;
  25492. this.maxSimultaneousLights = 4;
  25493. /**
  25494. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  25495. */
  25496. this.invertNormalMapX = false;
  25497. /**
  25498. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  25499. */
  25500. this.invertNormalMapY = false;
  25501. /**
  25502. * Color Grading 2D Lookup Texture.
  25503. * This allows special effects like sepia, black and white to sixties rendering style.
  25504. */
  25505. this.cameraColorGradingTexture = null;
  25506. /**
  25507. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  25508. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  25509. * 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;
  25510. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  25511. */
  25512. this.cameraColorCurves = null;
  25513. this._renderTargets = new BABYLON.SmartArray(16);
  25514. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  25515. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  25516. this._defines = new StandardMaterialDefines();
  25517. this._cachedDefines = new StandardMaterialDefines();
  25518. this._cachedDefines.BonesPerMesh = -1;
  25519. this.getRenderTargetTextures = function () {
  25520. _this._renderTargets.reset();
  25521. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  25522. _this._renderTargets.push(_this.reflectionTexture);
  25523. }
  25524. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  25525. _this._renderTargets.push(_this.refractionTexture);
  25526. }
  25527. return _this._renderTargets;
  25528. };
  25529. }
  25530. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  25531. get: function () {
  25532. return this._useLogarithmicDepth;
  25533. },
  25534. set: function (value) {
  25535. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  25536. },
  25537. enumerable: true,
  25538. configurable: true
  25539. });
  25540. StandardMaterial.prototype.needAlphaBlending = function () {
  25541. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  25542. };
  25543. StandardMaterial.prototype.needAlphaTesting = function () {
  25544. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  25545. };
  25546. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  25547. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  25548. };
  25549. StandardMaterial.prototype.getAlphaTestTexture = function () {
  25550. return this.diffuseTexture;
  25551. };
  25552. // Methods
  25553. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  25554. if (!mesh) {
  25555. return true;
  25556. }
  25557. if (this._defines.INSTANCES !== useInstances) {
  25558. return false;
  25559. }
  25560. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25561. return true;
  25562. }
  25563. return false;
  25564. };
  25565. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25566. if (this.isFrozen) {
  25567. if (this._wasPreviouslyReady) {
  25568. return true;
  25569. }
  25570. }
  25571. var scene = this.getScene();
  25572. if (!this.checkReadyOnEveryCall) {
  25573. if (this._renderId === scene.getRenderId()) {
  25574. if (this._checkCache(scene, mesh, useInstances)) {
  25575. return true;
  25576. }
  25577. }
  25578. }
  25579. var engine = scene.getEngine();
  25580. var needNormals = false;
  25581. var needUVs = false;
  25582. this._defines.reset();
  25583. // Textures
  25584. if (scene.texturesEnabled) {
  25585. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25586. if (!this.diffuseTexture.isReady()) {
  25587. return false;
  25588. }
  25589. else {
  25590. needUVs = true;
  25591. this._defines.DIFFUSE = true;
  25592. }
  25593. }
  25594. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25595. if (!this.ambientTexture.isReady()) {
  25596. return false;
  25597. }
  25598. else {
  25599. needUVs = true;
  25600. this._defines.AMBIENT = true;
  25601. }
  25602. }
  25603. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25604. if (!this.opacityTexture.isReady()) {
  25605. return false;
  25606. }
  25607. else {
  25608. needUVs = true;
  25609. this._defines.OPACITY = true;
  25610. if (this.opacityTexture.getAlphaFromRGB) {
  25611. this._defines.OPACITYRGB = true;
  25612. }
  25613. }
  25614. }
  25615. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25616. if (!this.reflectionTexture.isReady()) {
  25617. return false;
  25618. }
  25619. else {
  25620. needNormals = true;
  25621. this._defines.REFLECTION = true;
  25622. if (this.roughness > 0) {
  25623. this._defines.ROUGHNESS = true;
  25624. }
  25625. if (this.useReflectionOverAlpha) {
  25626. this._defines.REFLECTIONOVERALPHA = true;
  25627. }
  25628. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25629. this._defines.INVERTCUBICMAP = true;
  25630. }
  25631. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25632. switch (this.reflectionTexture.coordinatesMode) {
  25633. case BABYLON.Texture.CUBIC_MODE:
  25634. case BABYLON.Texture.INVCUBIC_MODE:
  25635. this._defines.REFLECTIONMAP_CUBIC = true;
  25636. break;
  25637. case BABYLON.Texture.EXPLICIT_MODE:
  25638. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25639. break;
  25640. case BABYLON.Texture.PLANAR_MODE:
  25641. this._defines.REFLECTIONMAP_PLANAR = true;
  25642. break;
  25643. case BABYLON.Texture.PROJECTION_MODE:
  25644. this._defines.REFLECTIONMAP_PROJECTION = true;
  25645. break;
  25646. case BABYLON.Texture.SKYBOX_MODE:
  25647. this._defines.REFLECTIONMAP_SKYBOX = true;
  25648. break;
  25649. case BABYLON.Texture.SPHERICAL_MODE:
  25650. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25651. break;
  25652. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25653. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25654. break;
  25655. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25656. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25657. break;
  25658. }
  25659. }
  25660. }
  25661. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25662. if (!this.emissiveTexture.isReady()) {
  25663. return false;
  25664. }
  25665. else {
  25666. needUVs = true;
  25667. this._defines.EMISSIVE = true;
  25668. }
  25669. }
  25670. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25671. if (!this.lightmapTexture.isReady()) {
  25672. return false;
  25673. }
  25674. else {
  25675. needUVs = true;
  25676. this._defines.LIGHTMAP = true;
  25677. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25678. }
  25679. }
  25680. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25681. if (!this.specularTexture.isReady()) {
  25682. return false;
  25683. }
  25684. else {
  25685. needUVs = true;
  25686. this._defines.SPECULAR = true;
  25687. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25688. }
  25689. }
  25690. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25691. if (!this.bumpTexture.isReady()) {
  25692. return false;
  25693. }
  25694. else {
  25695. needUVs = true;
  25696. this._defines.BUMP = true;
  25697. if (this.useParallax) {
  25698. this._defines.PARALLAX = true;
  25699. if (this.useParallaxOcclusion) {
  25700. this._defines.PARALLAXOCCLUSION = true;
  25701. }
  25702. }
  25703. if (this.invertNormalMapX) {
  25704. this._defines.INVERTNORMALMAPX = true;
  25705. }
  25706. if (this.invertNormalMapY) {
  25707. this._defines.INVERTNORMALMAPY = true;
  25708. }
  25709. }
  25710. }
  25711. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25712. if (!this.refractionTexture.isReady()) {
  25713. return false;
  25714. }
  25715. else {
  25716. needUVs = true;
  25717. this._defines.REFRACTION = true;
  25718. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25719. }
  25720. }
  25721. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25722. if (!this.cameraColorGradingTexture.isReady()) {
  25723. return false;
  25724. }
  25725. else {
  25726. this._defines.CAMERACOLORGRADING = true;
  25727. }
  25728. }
  25729. }
  25730. // Effect
  25731. if (scene.clipPlane) {
  25732. this._defines.CLIPPLANE = true;
  25733. }
  25734. if (engine.getAlphaTesting()) {
  25735. this._defines.ALPHATEST = true;
  25736. }
  25737. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25738. this._defines.ALPHAFROMDIFFUSE = true;
  25739. }
  25740. if (this.useEmissiveAsIllumination) {
  25741. this._defines.EMISSIVEASILLUMINATION = true;
  25742. }
  25743. if (this.linkEmissiveWithDiffuse) {
  25744. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25745. }
  25746. if (this.useLogarithmicDepth) {
  25747. this._defines.LOGARITHMICDEPTH = true;
  25748. }
  25749. if (this.cameraColorCurves) {
  25750. this._defines.CAMERACOLORCURVES = true;
  25751. }
  25752. // Point size
  25753. if (this.pointsCloud || scene.forcePointsCloud) {
  25754. this._defines.POINTSIZE = true;
  25755. }
  25756. // Fog
  25757. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25758. this._defines.FOG = true;
  25759. }
  25760. if (scene.lightsEnabled && !this.disableLighting) {
  25761. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25762. }
  25763. if (StandardMaterial.FresnelEnabled) {
  25764. // Fresnel
  25765. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25766. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25767. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25768. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25769. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25770. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25771. this._defines.DIFFUSEFRESNEL = true;
  25772. }
  25773. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25774. this._defines.OPACITYFRESNEL = true;
  25775. }
  25776. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25777. this._defines.REFLECTIONFRESNEL = true;
  25778. if (this.useReflectionFresnelFromSpecular) {
  25779. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  25780. }
  25781. }
  25782. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25783. this._defines.REFRACTIONFRESNEL = true;
  25784. }
  25785. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25786. this._defines.EMISSIVEFRESNEL = true;
  25787. }
  25788. needNormals = true;
  25789. this._defines.FRESNEL = true;
  25790. }
  25791. }
  25792. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  25793. this._defines.SPECULAROVERALPHA = true;
  25794. }
  25795. // Attribs
  25796. if (mesh) {
  25797. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25798. this._defines.NORMAL = true;
  25799. }
  25800. if (needUVs) {
  25801. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25802. this._defines.UV1 = true;
  25803. }
  25804. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25805. this._defines.UV2 = true;
  25806. }
  25807. }
  25808. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25809. this._defines.VERTEXCOLOR = true;
  25810. if (mesh.hasVertexAlpha) {
  25811. this._defines.VERTEXALPHA = true;
  25812. }
  25813. }
  25814. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25815. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  25816. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  25817. }
  25818. // Instances
  25819. if (useInstances) {
  25820. this._defines.INSTANCES = true;
  25821. }
  25822. }
  25823. // Get correct effect
  25824. if (!this._defines.isEqual(this._cachedDefines)) {
  25825. this._defines.cloneTo(this._cachedDefines);
  25826. scene.resetCachedMaterial();
  25827. // Fallbacks
  25828. var fallbacks = new BABYLON.EffectFallbacks();
  25829. if (this._defines.REFLECTION) {
  25830. fallbacks.addFallback(0, "REFLECTION");
  25831. }
  25832. if (this._defines.SPECULAR) {
  25833. fallbacks.addFallback(0, "SPECULAR");
  25834. }
  25835. if (this._defines.BUMP) {
  25836. fallbacks.addFallback(0, "BUMP");
  25837. }
  25838. if (this._defines.PARALLAX) {
  25839. fallbacks.addFallback(1, "PARALLAX");
  25840. }
  25841. if (this._defines.PARALLAXOCCLUSION) {
  25842. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  25843. }
  25844. if (this._defines.SPECULAROVERALPHA) {
  25845. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  25846. }
  25847. if (this._defines.FOG) {
  25848. fallbacks.addFallback(1, "FOG");
  25849. }
  25850. if (this._defines.POINTSIZE) {
  25851. fallbacks.addFallback(0, "POINTSIZE");
  25852. }
  25853. if (this._defines.LOGARITHMICDEPTH) {
  25854. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  25855. }
  25856. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  25857. if (this._defines.SPECULARTERM) {
  25858. fallbacks.addFallback(0, "SPECULARTERM");
  25859. }
  25860. if (this._defines.DIFFUSEFRESNEL) {
  25861. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  25862. }
  25863. if (this._defines.OPACITYFRESNEL) {
  25864. fallbacks.addFallback(2, "OPACITYFRESNEL");
  25865. }
  25866. if (this._defines.REFLECTIONFRESNEL) {
  25867. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  25868. }
  25869. if (this._defines.EMISSIVEFRESNEL) {
  25870. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  25871. }
  25872. if (this._defines.FRESNEL) {
  25873. fallbacks.addFallback(4, "FRESNEL");
  25874. }
  25875. //Attributes
  25876. var attribs = [BABYLON.VertexBuffer.PositionKind];
  25877. if (this._defines.NORMAL) {
  25878. attribs.push(BABYLON.VertexBuffer.NormalKind);
  25879. }
  25880. if (this._defines.UV1) {
  25881. attribs.push(BABYLON.VertexBuffer.UVKind);
  25882. }
  25883. if (this._defines.UV2) {
  25884. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25885. }
  25886. if (this._defines.VERTEXCOLOR) {
  25887. attribs.push(BABYLON.VertexBuffer.ColorKind);
  25888. }
  25889. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  25890. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  25891. var shaderName = "default";
  25892. var join = this._defines.toString();
  25893. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  25894. "vFogInfos", "vFogColor", "pointSize",
  25895. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  25896. "mBones",
  25897. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  25898. "depthValues",
  25899. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  25900. "logarithmicDepthConstant"
  25901. ];
  25902. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  25903. if (this._defines.CAMERACOLORCURVES) {
  25904. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  25905. }
  25906. if (this._defines.CAMERACOLORGRADING) {
  25907. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  25908. }
  25909. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  25910. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  25911. }
  25912. if (!this._effect.isReady()) {
  25913. return false;
  25914. }
  25915. this._renderId = scene.getRenderId();
  25916. this._wasPreviouslyReady = true;
  25917. if (mesh) {
  25918. if (!mesh._materialDefines) {
  25919. mesh._materialDefines = new StandardMaterialDefines();
  25920. }
  25921. this._defines.cloneTo(mesh._materialDefines);
  25922. }
  25923. return true;
  25924. };
  25925. StandardMaterial.prototype.unbind = function () {
  25926. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  25927. this._effect.setTexture("reflection2DSampler", null);
  25928. }
  25929. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  25930. this._effect.setTexture("refraction2DSampler", null);
  25931. }
  25932. _super.prototype.unbind.call(this);
  25933. };
  25934. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25935. this._effect.setMatrix("world", world);
  25936. };
  25937. StandardMaterial.prototype.bind = function (world, mesh) {
  25938. var scene = this.getScene();
  25939. // Matrices
  25940. this.bindOnlyWorldMatrix(world);
  25941. // Bones
  25942. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  25943. if (scene.getCachedMaterial() !== this) {
  25944. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25945. if (StandardMaterial.FresnelEnabled) {
  25946. // Fresnel
  25947. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25948. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  25949. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  25950. }
  25951. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25952. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  25953. }
  25954. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25955. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  25956. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  25957. }
  25958. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25959. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  25960. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  25961. }
  25962. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25963. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  25964. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  25965. }
  25966. }
  25967. // Textures
  25968. if (scene.texturesEnabled) {
  25969. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25970. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  25971. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  25972. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  25973. }
  25974. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25975. this._effect.setTexture("ambientSampler", this.ambientTexture);
  25976. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  25977. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  25978. }
  25979. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25980. this._effect.setTexture("opacitySampler", this.opacityTexture);
  25981. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  25982. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  25983. }
  25984. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25985. if (this.reflectionTexture.isCube) {
  25986. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  25987. }
  25988. else {
  25989. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  25990. }
  25991. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  25992. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  25993. }
  25994. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25995. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  25996. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  25997. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  25998. }
  25999. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26000. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26001. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26002. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26003. }
  26004. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26005. this._effect.setTexture("specularSampler", this.specularTexture);
  26006. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26007. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26008. }
  26009. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26010. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26011. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26012. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26013. }
  26014. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26015. var depth = 1.0;
  26016. if (this.refractionTexture.isCube) {
  26017. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26018. }
  26019. else {
  26020. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26021. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26022. if (this.refractionTexture.depth) {
  26023. depth = this.refractionTexture.depth;
  26024. }
  26025. }
  26026. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26027. }
  26028. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26029. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26030. }
  26031. }
  26032. // Clip plane
  26033. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26034. // Point size
  26035. if (this.pointsCloud) {
  26036. this._effect.setFloat("pointSize", this.pointSize);
  26037. }
  26038. // Colors
  26039. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26040. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26041. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26042. if (this._defines.SPECULARTERM) {
  26043. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26044. }
  26045. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26046. }
  26047. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26048. // Diffuse
  26049. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26050. // Lights
  26051. if (scene.lightsEnabled && !this.disableLighting) {
  26052. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26053. }
  26054. // View
  26055. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26056. this._effect.setMatrix("view", scene.getViewMatrix());
  26057. }
  26058. // Fog
  26059. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26060. // Log. depth
  26061. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26062. // Color Curves
  26063. if (this.cameraColorCurves) {
  26064. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26065. }
  26066. }
  26067. _super.prototype.bind.call(this, world, mesh);
  26068. };
  26069. StandardMaterial.prototype.getAnimatables = function () {
  26070. var results = [];
  26071. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26072. results.push(this.diffuseTexture);
  26073. }
  26074. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26075. results.push(this.ambientTexture);
  26076. }
  26077. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26078. results.push(this.opacityTexture);
  26079. }
  26080. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26081. results.push(this.reflectionTexture);
  26082. }
  26083. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26084. results.push(this.emissiveTexture);
  26085. }
  26086. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26087. results.push(this.specularTexture);
  26088. }
  26089. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26090. results.push(this.bumpTexture);
  26091. }
  26092. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26093. results.push(this.lightmapTexture);
  26094. }
  26095. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26096. results.push(this.refractionTexture);
  26097. }
  26098. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26099. results.push(this.cameraColorGradingTexture);
  26100. }
  26101. return results;
  26102. };
  26103. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26104. if (forceDisposeTextures) {
  26105. if (this.diffuseTexture) {
  26106. this.diffuseTexture.dispose();
  26107. }
  26108. if (this.ambientTexture) {
  26109. this.ambientTexture.dispose();
  26110. }
  26111. if (this.opacityTexture) {
  26112. this.opacityTexture.dispose();
  26113. }
  26114. if (this.reflectionTexture) {
  26115. this.reflectionTexture.dispose();
  26116. }
  26117. if (this.emissiveTexture) {
  26118. this.emissiveTexture.dispose();
  26119. }
  26120. if (this.specularTexture) {
  26121. this.specularTexture.dispose();
  26122. }
  26123. if (this.bumpTexture) {
  26124. this.bumpTexture.dispose();
  26125. }
  26126. if (this.lightmapTexture) {
  26127. this.lightmapTexture.dispose();
  26128. }
  26129. if (this.refractionTexture) {
  26130. this.refractionTexture.dispose();
  26131. }
  26132. if (this.cameraColorGradingTexture) {
  26133. this.cameraColorGradingTexture.dispose();
  26134. }
  26135. }
  26136. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  26137. };
  26138. StandardMaterial.prototype.clone = function (name) {
  26139. var _this = this;
  26140. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  26141. };
  26142. StandardMaterial.prototype.serialize = function () {
  26143. return BABYLON.SerializationHelper.Serialize(this);
  26144. };
  26145. // Statics
  26146. StandardMaterial.Parse = function (source, scene, rootUrl) {
  26147. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  26148. };
  26149. // Flags used to enable or disable a type of texture for all Standard Materials
  26150. StandardMaterial.DiffuseTextureEnabled = true;
  26151. StandardMaterial.AmbientTextureEnabled = true;
  26152. StandardMaterial.OpacityTextureEnabled = true;
  26153. StandardMaterial.ReflectionTextureEnabled = true;
  26154. StandardMaterial.EmissiveTextureEnabled = true;
  26155. StandardMaterial.SpecularTextureEnabled = true;
  26156. StandardMaterial.BumpTextureEnabled = true;
  26157. StandardMaterial.FresnelEnabled = true;
  26158. StandardMaterial.LightmapTextureEnabled = true;
  26159. StandardMaterial.RefractionTextureEnabled = true;
  26160. StandardMaterial.ColorGradingTextureEnabled = true;
  26161. __decorate([
  26162. BABYLON.serializeAsTexture()
  26163. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  26164. __decorate([
  26165. BABYLON.serializeAsTexture()
  26166. ], StandardMaterial.prototype, "ambientTexture", void 0);
  26167. __decorate([
  26168. BABYLON.serializeAsTexture()
  26169. ], StandardMaterial.prototype, "opacityTexture", void 0);
  26170. __decorate([
  26171. BABYLON.serializeAsTexture()
  26172. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  26173. __decorate([
  26174. BABYLON.serializeAsTexture()
  26175. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  26176. __decorate([
  26177. BABYLON.serializeAsTexture()
  26178. ], StandardMaterial.prototype, "specularTexture", void 0);
  26179. __decorate([
  26180. BABYLON.serializeAsTexture()
  26181. ], StandardMaterial.prototype, "bumpTexture", void 0);
  26182. __decorate([
  26183. BABYLON.serializeAsTexture()
  26184. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  26185. __decorate([
  26186. BABYLON.serializeAsTexture()
  26187. ], StandardMaterial.prototype, "refractionTexture", void 0);
  26188. __decorate([
  26189. BABYLON.serializeAsColor3("ambient")
  26190. ], StandardMaterial.prototype, "ambientColor", void 0);
  26191. __decorate([
  26192. BABYLON.serializeAsColor3("diffuse")
  26193. ], StandardMaterial.prototype, "diffuseColor", void 0);
  26194. __decorate([
  26195. BABYLON.serializeAsColor3("specular")
  26196. ], StandardMaterial.prototype, "specularColor", void 0);
  26197. __decorate([
  26198. BABYLON.serializeAsColor3("emissive")
  26199. ], StandardMaterial.prototype, "emissiveColor", void 0);
  26200. __decorate([
  26201. BABYLON.serialize()
  26202. ], StandardMaterial.prototype, "specularPower", void 0);
  26203. __decorate([
  26204. BABYLON.serialize()
  26205. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  26206. __decorate([
  26207. BABYLON.serialize()
  26208. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  26209. __decorate([
  26210. BABYLON.serialize()
  26211. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  26212. __decorate([
  26213. BABYLON.serialize()
  26214. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  26215. __decorate([
  26216. BABYLON.serialize()
  26217. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  26218. __decorate([
  26219. BABYLON.serialize()
  26220. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  26221. __decorate([
  26222. BABYLON.serialize()
  26223. ], StandardMaterial.prototype, "disableLighting", void 0);
  26224. __decorate([
  26225. BABYLON.serialize()
  26226. ], StandardMaterial.prototype, "useParallax", void 0);
  26227. __decorate([
  26228. BABYLON.serialize()
  26229. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  26230. __decorate([
  26231. BABYLON.serialize()
  26232. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  26233. __decorate([
  26234. BABYLON.serialize()
  26235. ], StandardMaterial.prototype, "roughness", void 0);
  26236. __decorate([
  26237. BABYLON.serialize()
  26238. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  26239. __decorate([
  26240. BABYLON.serialize()
  26241. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  26242. __decorate([
  26243. BABYLON.serialize()
  26244. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  26245. __decorate([
  26246. BABYLON.serializeAsFresnelParameters()
  26247. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  26248. __decorate([
  26249. BABYLON.serializeAsFresnelParameters()
  26250. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  26251. __decorate([
  26252. BABYLON.serializeAsFresnelParameters()
  26253. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  26254. __decorate([
  26255. BABYLON.serializeAsFresnelParameters()
  26256. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  26257. __decorate([
  26258. BABYLON.serializeAsFresnelParameters()
  26259. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  26260. __decorate([
  26261. BABYLON.serialize()
  26262. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  26263. __decorate([
  26264. BABYLON.serialize()
  26265. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  26266. __decorate([
  26267. BABYLON.serialize()
  26268. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  26269. __decorate([
  26270. BABYLON.serialize()
  26271. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  26272. __decorate([
  26273. BABYLON.serializeAsTexture()
  26274. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  26275. __decorate([
  26276. BABYLON.serializeAsColorCurves()
  26277. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  26278. __decorate([
  26279. BABYLON.serialize()
  26280. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  26281. return StandardMaterial;
  26282. }(BABYLON.Material));
  26283. BABYLON.StandardMaterial = StandardMaterial;
  26284. })(BABYLON || (BABYLON = {}));
  26285. var BABYLON;
  26286. (function (BABYLON) {
  26287. var MultiMaterial = (function (_super) {
  26288. __extends(MultiMaterial, _super);
  26289. function MultiMaterial(name, scene) {
  26290. _super.call(this, name, scene, true);
  26291. this.subMaterials = new Array();
  26292. scene.multiMaterials.push(this);
  26293. }
  26294. // Properties
  26295. MultiMaterial.prototype.getSubMaterial = function (index) {
  26296. if (index < 0 || index >= this.subMaterials.length) {
  26297. return this.getScene().defaultMaterial;
  26298. }
  26299. return this.subMaterials[index];
  26300. };
  26301. // Methods
  26302. MultiMaterial.prototype.isReady = function (mesh) {
  26303. for (var index = 0; index < this.subMaterials.length; index++) {
  26304. var subMaterial = this.subMaterials[index];
  26305. if (subMaterial) {
  26306. if (!this.subMaterials[index].isReady(mesh)) {
  26307. return false;
  26308. }
  26309. }
  26310. }
  26311. return true;
  26312. };
  26313. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  26314. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  26315. for (var index = 0; index < this.subMaterials.length; index++) {
  26316. var subMaterial = null;
  26317. if (cloneChildren) {
  26318. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  26319. }
  26320. else {
  26321. subMaterial = this.subMaterials[index];
  26322. }
  26323. newMultiMaterial.subMaterials.push(subMaterial);
  26324. }
  26325. return newMultiMaterial;
  26326. };
  26327. MultiMaterial.prototype.serialize = function () {
  26328. var serializationObject = {};
  26329. serializationObject.name = this.name;
  26330. serializationObject.id = this.id;
  26331. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26332. serializationObject.materials = [];
  26333. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  26334. var subMat = this.subMaterials[matIndex];
  26335. if (subMat) {
  26336. serializationObject.materials.push(subMat.id);
  26337. }
  26338. else {
  26339. serializationObject.materials.push(null);
  26340. }
  26341. }
  26342. return serializationObject;
  26343. };
  26344. return MultiMaterial;
  26345. }(BABYLON.Material));
  26346. BABYLON.MultiMaterial = MultiMaterial;
  26347. })(BABYLON || (BABYLON = {}));
  26348. var BABYLON;
  26349. (function (BABYLON) {
  26350. var SceneLoader = (function () {
  26351. function SceneLoader() {
  26352. }
  26353. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  26354. get: function () {
  26355. return 0;
  26356. },
  26357. enumerable: true,
  26358. configurable: true
  26359. });
  26360. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  26361. get: function () {
  26362. return 1;
  26363. },
  26364. enumerable: true,
  26365. configurable: true
  26366. });
  26367. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  26368. get: function () {
  26369. return 2;
  26370. },
  26371. enumerable: true,
  26372. configurable: true
  26373. });
  26374. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  26375. get: function () {
  26376. return 3;
  26377. },
  26378. enumerable: true,
  26379. configurable: true
  26380. });
  26381. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  26382. get: function () {
  26383. return SceneLoader._ForceFullSceneLoadingForIncremental;
  26384. },
  26385. set: function (value) {
  26386. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  26387. },
  26388. enumerable: true,
  26389. configurable: true
  26390. });
  26391. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  26392. get: function () {
  26393. return SceneLoader._ShowLoadingScreen;
  26394. },
  26395. set: function (value) {
  26396. SceneLoader._ShowLoadingScreen = value;
  26397. },
  26398. enumerable: true,
  26399. configurable: true
  26400. });
  26401. Object.defineProperty(SceneLoader, "loggingLevel", {
  26402. get: function () {
  26403. return SceneLoader._loggingLevel;
  26404. },
  26405. set: function (value) {
  26406. SceneLoader._loggingLevel = value;
  26407. },
  26408. enumerable: true,
  26409. configurable: true
  26410. });
  26411. SceneLoader._getDefaultPlugin = function () {
  26412. return SceneLoader._registeredPlugins[".babylon"];
  26413. };
  26414. SceneLoader._getPluginForExtension = function (extension) {
  26415. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  26416. if (registeredPlugin) {
  26417. return registeredPlugin;
  26418. }
  26419. return SceneLoader._getDefaultPlugin();
  26420. };
  26421. SceneLoader._getPluginForFilename = function (sceneFilename) {
  26422. if (sceneFilename.name) {
  26423. sceneFilename = sceneFilename.name;
  26424. }
  26425. var dotPosition = sceneFilename.lastIndexOf(".");
  26426. var queryStringPosition = sceneFilename.indexOf("?");
  26427. if (queryStringPosition === -1) {
  26428. queryStringPosition = sceneFilename.length;
  26429. }
  26430. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  26431. return SceneLoader._getPluginForExtension(extension);
  26432. };
  26433. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  26434. SceneLoader._getDirectLoad = function (sceneFilename) {
  26435. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26436. return sceneFilename.substr(5);
  26437. }
  26438. return null;
  26439. };
  26440. // Public functions
  26441. SceneLoader.GetPluginForExtension = function (extension) {
  26442. return SceneLoader._getPluginForExtension(extension).plugin;
  26443. };
  26444. SceneLoader.RegisterPlugin = function (plugin) {
  26445. if (typeof plugin.extensions === "string") {
  26446. var extension = plugin.extensions;
  26447. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26448. plugin: plugin,
  26449. isBinary: false
  26450. };
  26451. }
  26452. else {
  26453. var extensions = plugin.extensions;
  26454. Object.keys(extensions).forEach(function (extension) {
  26455. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26456. plugin: plugin,
  26457. isBinary: extensions[extension].isBinary
  26458. };
  26459. });
  26460. }
  26461. };
  26462. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26463. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26464. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26465. return;
  26466. }
  26467. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26468. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26469. return;
  26470. }
  26471. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26472. var loadingToken = {};
  26473. scene._addPendingData(loadingToken);
  26474. var manifestChecked = function (success) {
  26475. scene.database = database;
  26476. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26477. var plugin = registeredPlugin.plugin;
  26478. var useArrayBuffer = registeredPlugin.isBinary;
  26479. var importMeshFromData = function (data) {
  26480. var meshes = [];
  26481. var particleSystems = [];
  26482. var skeletons = [];
  26483. try {
  26484. if (plugin.importMesh) {
  26485. var syncedPlugin = plugin;
  26486. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  26487. if (onerror) {
  26488. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26489. }
  26490. scene._removePendingData(loadingToken);
  26491. return;
  26492. }
  26493. if (onsuccess) {
  26494. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26495. onsuccess(meshes, particleSystems, skeletons);
  26496. scene._removePendingData(loadingToken);
  26497. }
  26498. }
  26499. else {
  26500. var asyncedPlugin = plugin;
  26501. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  26502. if (onsuccess) {
  26503. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26504. onsuccess(meshes, particleSystems, skeletons);
  26505. scene._removePendingData(loadingToken);
  26506. }
  26507. }, function () {
  26508. if (onerror) {
  26509. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26510. }
  26511. scene._removePendingData(loadingToken);
  26512. });
  26513. }
  26514. }
  26515. catch (e) {
  26516. if (onerror) {
  26517. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  26518. }
  26519. scene._removePendingData(loadingToken);
  26520. }
  26521. };
  26522. if (directLoad) {
  26523. importMeshFromData(directLoad);
  26524. return;
  26525. }
  26526. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  26527. importMeshFromData(data);
  26528. }, progressCallBack, database, useArrayBuffer);
  26529. };
  26530. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  26531. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26532. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26533. }
  26534. else {
  26535. // If the scene is a data stream or offline support is not enabled, it's a direct load
  26536. manifestChecked(true);
  26537. }
  26538. };
  26539. /**
  26540. * Load a scene
  26541. * @param rootUrl a string that defines the root url for scene and resources
  26542. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26543. * @param engine is the instance of BABYLON.Engine to use to create the scene
  26544. */
  26545. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  26546. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  26547. };
  26548. /**
  26549. * Append a scene
  26550. * @param rootUrl a string that defines the root url for scene and resources
  26551. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26552. * @param scene is the instance of BABYLON.Scene to append to
  26553. */
  26554. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26555. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26556. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26557. return;
  26558. }
  26559. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26560. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26561. var plugin = registeredPlugin.plugin;
  26562. var useArrayBuffer = registeredPlugin.isBinary;
  26563. var database;
  26564. var loadingToken = {};
  26565. scene._addPendingData(loadingToken);
  26566. if (SceneLoader.ShowLoadingScreen) {
  26567. scene.getEngine().displayLoadingUI();
  26568. }
  26569. var loadSceneFromData = function (data) {
  26570. scene.database = database;
  26571. if (plugin.load) {
  26572. var syncedPlugin = plugin;
  26573. if (!syncedPlugin.load(scene, data, rootUrl)) {
  26574. if (onerror) {
  26575. onerror(scene);
  26576. }
  26577. scene._removePendingData(loadingToken);
  26578. scene.getEngine().hideLoadingUI();
  26579. return;
  26580. }
  26581. if (onsuccess) {
  26582. onsuccess(scene);
  26583. }
  26584. scene._removePendingData(loadingToken);
  26585. }
  26586. else {
  26587. var asyncedPlugin = plugin;
  26588. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26589. if (onsuccess) {
  26590. onsuccess(scene);
  26591. }
  26592. scene._removePendingData(loadingToken);
  26593. }, function () {
  26594. if (onerror) {
  26595. onerror(scene);
  26596. }
  26597. scene._removePendingData(loadingToken);
  26598. scene.getEngine().hideLoadingUI();
  26599. });
  26600. }
  26601. if (SceneLoader.ShowLoadingScreen) {
  26602. scene.executeWhenReady(function () {
  26603. scene.getEngine().hideLoadingUI();
  26604. });
  26605. }
  26606. };
  26607. var manifestChecked = function (success) {
  26608. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  26609. };
  26610. if (directLoad) {
  26611. loadSceneFromData(directLoad);
  26612. return;
  26613. }
  26614. if (rootUrl.indexOf("file:") === -1) {
  26615. if (scene.getEngine().enableOfflineSupport) {
  26616. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26617. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26618. }
  26619. else {
  26620. manifestChecked(true);
  26621. }
  26622. }
  26623. else {
  26624. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  26625. }
  26626. };
  26627. // Flags
  26628. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26629. SceneLoader._ShowLoadingScreen = true;
  26630. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26631. // Members
  26632. SceneLoader._registeredPlugins = {};
  26633. return SceneLoader;
  26634. }());
  26635. BABYLON.SceneLoader = SceneLoader;
  26636. ;
  26637. })(BABYLON || (BABYLON = {}));
  26638. var BABYLON;
  26639. (function (BABYLON) {
  26640. var Internals;
  26641. (function (Internals) {
  26642. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26643. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26644. var parsedMaterial = parsedData.materials[index];
  26645. if (parsedMaterial.id === id) {
  26646. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26647. }
  26648. }
  26649. return null;
  26650. };
  26651. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26652. names = (names instanceof Array) ? names : [names];
  26653. for (var i in names) {
  26654. if (mesh.name === names[i]) {
  26655. hierarchyIds.push(mesh.id);
  26656. return true;
  26657. }
  26658. }
  26659. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26660. hierarchyIds.push(mesh.id);
  26661. return true;
  26662. }
  26663. return false;
  26664. };
  26665. var logOperation = function (operation, producer) {
  26666. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26667. };
  26668. BABYLON.SceneLoader.RegisterPlugin({
  26669. extensions: ".babylon",
  26670. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26671. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26672. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26673. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26674. // and avoid problems with multiple concurrent .babylon loads.
  26675. var log = "importMesh has failed JSON parse";
  26676. try {
  26677. var parsedData = JSON.parse(data);
  26678. log = "";
  26679. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26680. var loadedSkeletonsIds = [];
  26681. var loadedMaterialsIds = [];
  26682. var hierarchyIds = [];
  26683. var index;
  26684. var cache;
  26685. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26686. var parsedMesh = parsedData.meshes[index];
  26687. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26688. if (meshesNames instanceof Array) {
  26689. // Remove found mesh name from list.
  26690. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26691. }
  26692. //Geometry?
  26693. if (parsedMesh.geometryId) {
  26694. //does the file contain geometries?
  26695. if (parsedData.geometries) {
  26696. //find the correct geometry and add it to the scene
  26697. var found = false;
  26698. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  26699. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  26700. return;
  26701. }
  26702. else {
  26703. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  26704. if (parsedGeometryData.id === parsedMesh.geometryId) {
  26705. switch (geometryType) {
  26706. case "boxes":
  26707. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  26708. break;
  26709. case "spheres":
  26710. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  26711. break;
  26712. case "cylinders":
  26713. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  26714. break;
  26715. case "toruses":
  26716. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26717. break;
  26718. case "grounds":
  26719. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26720. break;
  26721. case "planes":
  26722. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26723. break;
  26724. case "torusKnots":
  26725. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26726. break;
  26727. case "vertexData":
  26728. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26729. break;
  26730. }
  26731. found = true;
  26732. }
  26733. });
  26734. }
  26735. });
  26736. if (!found) {
  26737. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26738. }
  26739. }
  26740. }
  26741. // Material ?
  26742. if (parsedMesh.materialId) {
  26743. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26744. if (!materialFound && parsedData.multiMaterials) {
  26745. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26746. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26747. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26748. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26749. var subMatId = parsedMultiMaterial.materials[matIndex];
  26750. loadedMaterialsIds.push(subMatId);
  26751. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26752. log += "\n\tMaterial " + mat.toString(fullDetails);
  26753. }
  26754. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26755. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26756. materialFound = true;
  26757. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26758. break;
  26759. }
  26760. }
  26761. }
  26762. if (!materialFound) {
  26763. loadedMaterialsIds.push(parsedMesh.materialId);
  26764. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26765. if (!mat) {
  26766. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26767. }
  26768. else {
  26769. log += "\n\tMaterial " + mat.toString(fullDetails);
  26770. }
  26771. }
  26772. }
  26773. // Skeleton ?
  26774. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  26775. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  26776. if (!skeletonAlreadyLoaded) {
  26777. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  26778. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  26779. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  26780. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26781. skeletons.push(skeleton);
  26782. loadedSkeletonsIds.push(parsedSkeleton.id);
  26783. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  26784. }
  26785. }
  26786. }
  26787. }
  26788. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26789. meshes.push(mesh);
  26790. log += "\n\tMesh " + mesh.toString(fullDetails);
  26791. }
  26792. }
  26793. // Connecting parents
  26794. var currentMesh;
  26795. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26796. currentMesh = scene.meshes[index];
  26797. if (currentMesh._waitingParentId) {
  26798. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  26799. currentMesh._waitingParentId = undefined;
  26800. }
  26801. }
  26802. // freeze and compute world matrix application
  26803. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26804. currentMesh = scene.meshes[index];
  26805. if (currentMesh._waitingFreezeWorldMatrix) {
  26806. currentMesh.freezeWorldMatrix();
  26807. currentMesh._waitingFreezeWorldMatrix = undefined;
  26808. }
  26809. else {
  26810. currentMesh.computeWorldMatrix(true);
  26811. }
  26812. }
  26813. // Particles
  26814. if (parsedData.particleSystems) {
  26815. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26816. var parsedParticleSystem = parsedData.particleSystems[index];
  26817. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  26818. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  26819. }
  26820. }
  26821. }
  26822. return true;
  26823. }
  26824. catch (err) {
  26825. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  26826. log = null;
  26827. throw err;
  26828. }
  26829. finally {
  26830. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26831. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26832. }
  26833. }
  26834. },
  26835. load: function (scene, data, rootUrl) {
  26836. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26837. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26838. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26839. // and avoid problems with multiple concurrent .babylon loads.
  26840. var log = "importScene has failed JSON parse";
  26841. try {
  26842. var parsedData = JSON.parse(data);
  26843. log = "";
  26844. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26845. // Scene
  26846. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  26847. scene.autoClear = parsedData.autoClear;
  26848. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  26849. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  26850. if (parsedData.gravity) {
  26851. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  26852. }
  26853. // Fog
  26854. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  26855. scene.fogMode = parsedData.fogMode;
  26856. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  26857. scene.fogStart = parsedData.fogStart;
  26858. scene.fogEnd = parsedData.fogEnd;
  26859. scene.fogDensity = parsedData.fogDensity;
  26860. log += "\tFog mode for scene: ";
  26861. switch (scene.fogMode) {
  26862. // getters not compiling, so using hardcoded
  26863. case 1:
  26864. log += "exp\n";
  26865. break;
  26866. case 2:
  26867. log += "exp2\n";
  26868. break;
  26869. case 3:
  26870. log += "linear\n";
  26871. break;
  26872. }
  26873. }
  26874. //Physics
  26875. if (parsedData.physicsEnabled) {
  26876. var physicsPlugin;
  26877. if (parsedData.physicsEngine === "cannon") {
  26878. physicsPlugin = new BABYLON.CannonJSPlugin();
  26879. }
  26880. else if (parsedData.physicsEngine === "oimo") {
  26881. physicsPlugin = new BABYLON.OimoJSPlugin();
  26882. }
  26883. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  26884. //else - default engine, which is currently oimo
  26885. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  26886. scene.enablePhysics(physicsGravity, physicsPlugin);
  26887. }
  26888. //collisions, if defined. otherwise, default is true
  26889. if (parsedData.collisionsEnabled != undefined) {
  26890. scene.collisionsEnabled = parsedData.collisionsEnabled;
  26891. }
  26892. scene.workerCollisions = !!parsedData.workerCollisions;
  26893. var index;
  26894. var cache;
  26895. // Lights
  26896. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  26897. var parsedLight = parsedData.lights[index];
  26898. var light = BABYLON.Light.Parse(parsedLight, scene);
  26899. log += (index === 0 ? "\n\tLights:" : "");
  26900. log += "\n\t\t" + light.toString(fullDetails);
  26901. }
  26902. // Animations
  26903. if (parsedData.animations) {
  26904. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  26905. var parsedAnimation = parsedData.animations[index];
  26906. var animation = BABYLON.Animation.Parse(parsedAnimation);
  26907. scene.animations.push(animation);
  26908. log += (index === 0 ? "\n\tAnimations:" : "");
  26909. log += "\n\t\t" + animation.toString(fullDetails);
  26910. }
  26911. }
  26912. if (parsedData.autoAnimate) {
  26913. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  26914. }
  26915. // Materials
  26916. if (parsedData.materials) {
  26917. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26918. var parsedMaterial = parsedData.materials[index];
  26919. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26920. log += (index === 0 ? "\n\tMaterials:" : "");
  26921. log += "\n\t\t" + mat.toString(fullDetails);
  26922. }
  26923. }
  26924. if (parsedData.multiMaterials) {
  26925. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  26926. var parsedMultiMaterial = parsedData.multiMaterials[index];
  26927. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26928. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  26929. log += "\n\t\t" + mmat.toString(fullDetails);
  26930. }
  26931. }
  26932. // Skeletons
  26933. if (parsedData.skeletons) {
  26934. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  26935. var parsedSkeleton = parsedData.skeletons[index];
  26936. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26937. log += (index === 0 ? "\n\tSkeletons:" : "");
  26938. log += "\n\t\t" + skeleton.toString(fullDetails);
  26939. }
  26940. }
  26941. // Geometries
  26942. var geometries = parsedData.geometries;
  26943. if (geometries) {
  26944. // Boxes
  26945. var boxes = geometries.boxes;
  26946. if (boxes) {
  26947. for (index = 0, cache = boxes.length; index < cache; index++) {
  26948. var parsedBox = boxes[index];
  26949. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  26950. }
  26951. }
  26952. // Spheres
  26953. var spheres = geometries.spheres;
  26954. if (spheres) {
  26955. for (index = 0, cache = spheres.length; index < cache; index++) {
  26956. var parsedSphere = spheres[index];
  26957. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  26958. }
  26959. }
  26960. // Cylinders
  26961. var cylinders = geometries.cylinders;
  26962. if (cylinders) {
  26963. for (index = 0, cache = cylinders.length; index < cache; index++) {
  26964. var parsedCylinder = cylinders[index];
  26965. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  26966. }
  26967. }
  26968. // Toruses
  26969. var toruses = geometries.toruses;
  26970. if (toruses) {
  26971. for (index = 0, cache = toruses.length; index < cache; index++) {
  26972. var parsedTorus = toruses[index];
  26973. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  26974. }
  26975. }
  26976. // Grounds
  26977. var grounds = geometries.grounds;
  26978. if (grounds) {
  26979. for (index = 0, cache = grounds.length; index < cache; index++) {
  26980. var parsedGround = grounds[index];
  26981. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  26982. }
  26983. }
  26984. // Planes
  26985. var planes = geometries.planes;
  26986. if (planes) {
  26987. for (index = 0, cache = planes.length; index < cache; index++) {
  26988. var parsedPlane = planes[index];
  26989. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  26990. }
  26991. }
  26992. // TorusKnots
  26993. var torusKnots = geometries.torusKnots;
  26994. if (torusKnots) {
  26995. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  26996. var parsedTorusKnot = torusKnots[index];
  26997. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  26998. }
  26999. }
  27000. // VertexData
  27001. var vertexData = geometries.vertexData;
  27002. if (vertexData) {
  27003. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27004. var parsedVertexData = vertexData[index];
  27005. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27006. }
  27007. }
  27008. }
  27009. // Meshes
  27010. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27011. var parsedMesh = parsedData.meshes[index];
  27012. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27013. log += (index === 0 ? "\n\tMeshes:" : "");
  27014. log += "\n\t\t" + mesh.toString(fullDetails);
  27015. }
  27016. // Cameras
  27017. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27018. var parsedCamera = parsedData.cameras[index];
  27019. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27020. log += (index === 0 ? "\n\tCameras:" : "");
  27021. log += "\n\t\t" + camera.toString(fullDetails);
  27022. }
  27023. if (parsedData.activeCameraID) {
  27024. scene.setActiveCameraByID(parsedData.activeCameraID);
  27025. }
  27026. // Browsing all the graph to connect the dots
  27027. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27028. var camera = scene.cameras[index];
  27029. if (camera._waitingParentId) {
  27030. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27031. camera._waitingParentId = undefined;
  27032. }
  27033. }
  27034. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27035. var light = scene.lights[index];
  27036. if (light._waitingParentId) {
  27037. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27038. light._waitingParentId = undefined;
  27039. }
  27040. }
  27041. // Sounds
  27042. var loadedSounds = [];
  27043. var loadedSound;
  27044. if (BABYLON.AudioEngine && parsedData.sounds) {
  27045. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27046. var parsedSound = parsedData.sounds[index];
  27047. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27048. if (!parsedSound.url)
  27049. parsedSound.url = parsedSound.name;
  27050. if (!loadedSounds[parsedSound.url]) {
  27051. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27052. loadedSounds[parsedSound.url] = loadedSound;
  27053. }
  27054. else {
  27055. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27056. }
  27057. }
  27058. else {
  27059. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27060. }
  27061. }
  27062. }
  27063. loadedSounds = [];
  27064. // Connect parents & children and parse actions
  27065. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27066. var mesh = scene.meshes[index];
  27067. if (mesh._waitingParentId) {
  27068. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27069. mesh._waitingParentId = undefined;
  27070. }
  27071. if (mesh._waitingActions) {
  27072. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27073. mesh._waitingActions = undefined;
  27074. }
  27075. }
  27076. // freeze world matrix application
  27077. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27078. var currentMesh = scene.meshes[index];
  27079. if (currentMesh._waitingFreezeWorldMatrix) {
  27080. currentMesh.freezeWorldMatrix();
  27081. currentMesh._waitingFreezeWorldMatrix = undefined;
  27082. }
  27083. else {
  27084. currentMesh.computeWorldMatrix(true);
  27085. }
  27086. }
  27087. // Particles Systems
  27088. if (parsedData.particleSystems) {
  27089. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27090. var parsedParticleSystem = parsedData.particleSystems[index];
  27091. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27092. }
  27093. }
  27094. // Lens flares
  27095. if (parsedData.lensFlareSystems) {
  27096. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27097. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27098. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27099. }
  27100. }
  27101. // Shadows
  27102. if (parsedData.shadowGenerators) {
  27103. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27104. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27105. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27106. }
  27107. }
  27108. // Actions (scene)
  27109. if (parsedData.actions) {
  27110. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27111. }
  27112. // Finish
  27113. return true;
  27114. }
  27115. catch (err) {
  27116. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  27117. log = null;
  27118. throw err;
  27119. }
  27120. finally {
  27121. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27122. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27123. }
  27124. }
  27125. }
  27126. });
  27127. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27128. })(BABYLON || (BABYLON = {}));
  27129. var BABYLON;
  27130. (function (BABYLON) {
  27131. var SpriteManager = (function () {
  27132. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  27133. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27134. this.name = name;
  27135. this.sprites = new Array();
  27136. this.renderingGroupId = 0;
  27137. this.layerMask = 0x0FFFFFFF;
  27138. this.fogEnabled = true;
  27139. this.isPickable = false;
  27140. /**
  27141. * An event triggered when the manager is disposed.
  27142. * @type {BABYLON.Observable}
  27143. */
  27144. this.onDisposeObservable = new BABYLON.Observable();
  27145. this._vertexBuffers = {};
  27146. this._capacity = capacity;
  27147. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  27148. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27149. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27150. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  27151. if (cellSize.width) {
  27152. this.cellWidth = cellSize.width;
  27153. this.cellHeight = cellSize.height;
  27154. }
  27155. else {
  27156. this.cellWidth = cellSize;
  27157. this.cellHeight = cellSize;
  27158. }
  27159. this._scene = scene;
  27160. this._scene.spriteManagers.push(this);
  27161. var indices = [];
  27162. var index = 0;
  27163. for (var count = 0; count < capacity; count++) {
  27164. indices.push(index);
  27165. indices.push(index + 1);
  27166. indices.push(index + 2);
  27167. indices.push(index);
  27168. indices.push(index + 2);
  27169. indices.push(index + 3);
  27170. index += 4;
  27171. }
  27172. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27173. // VBO
  27174. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  27175. this._vertexData = new Float32Array(capacity * 16 * 4);
  27176. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  27177. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  27178. var options = this._buffer.createVertexBuffer("options", 4, 4);
  27179. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  27180. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  27181. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27182. this._vertexBuffers["options"] = options;
  27183. this._vertexBuffers["cellInfo"] = cellInfo;
  27184. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27185. // Effects
  27186. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  27187. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  27188. }
  27189. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  27190. set: function (callback) {
  27191. if (this._onDisposeObserver) {
  27192. this.onDisposeObservable.remove(this._onDisposeObserver);
  27193. }
  27194. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27195. },
  27196. enumerable: true,
  27197. configurable: true
  27198. });
  27199. Object.defineProperty(SpriteManager.prototype, "texture", {
  27200. get: function () {
  27201. return this._spriteTexture;
  27202. },
  27203. set: function (value) {
  27204. this._spriteTexture = value;
  27205. },
  27206. enumerable: true,
  27207. configurable: true
  27208. });
  27209. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  27210. var arrayOffset = index * 16;
  27211. if (offsetX === 0)
  27212. offsetX = this._epsilon;
  27213. else if (offsetX === 1)
  27214. offsetX = 1 - this._epsilon;
  27215. if (offsetY === 0)
  27216. offsetY = this._epsilon;
  27217. else if (offsetY === 1)
  27218. offsetY = 1 - this._epsilon;
  27219. this._vertexData[arrayOffset] = sprite.position.x;
  27220. this._vertexData[arrayOffset + 1] = sprite.position.y;
  27221. this._vertexData[arrayOffset + 2] = sprite.position.z;
  27222. this._vertexData[arrayOffset + 3] = sprite.angle;
  27223. this._vertexData[arrayOffset + 4] = sprite.width;
  27224. this._vertexData[arrayOffset + 5] = sprite.height;
  27225. this._vertexData[arrayOffset + 6] = offsetX;
  27226. this._vertexData[arrayOffset + 7] = offsetY;
  27227. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  27228. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  27229. var offset = (sprite.cellIndex / rowSize) >> 0;
  27230. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  27231. this._vertexData[arrayOffset + 11] = offset;
  27232. // Color
  27233. this._vertexData[arrayOffset + 12] = sprite.color.r;
  27234. this._vertexData[arrayOffset + 13] = sprite.color.g;
  27235. this._vertexData[arrayOffset + 14] = sprite.color.b;
  27236. this._vertexData[arrayOffset + 15] = sprite.color.a;
  27237. };
  27238. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  27239. var count = Math.min(this._capacity, this.sprites.length);
  27240. var min = BABYLON.Vector3.Zero();
  27241. var max = BABYLON.Vector3.Zero();
  27242. var distance = Number.MAX_VALUE;
  27243. var currentSprite;
  27244. var cameraSpacePosition = BABYLON.Vector3.Zero();
  27245. var cameraView = camera.getViewMatrix();
  27246. for (var index = 0; index < count; index++) {
  27247. var sprite = this.sprites[index];
  27248. if (!sprite) {
  27249. continue;
  27250. }
  27251. if (predicate) {
  27252. if (!predicate(sprite)) {
  27253. continue;
  27254. }
  27255. }
  27256. else if (!sprite.isPickable) {
  27257. continue;
  27258. }
  27259. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  27260. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  27261. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  27262. if (ray.intersectsBoxMinMax(min, max)) {
  27263. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  27264. if (distance > currentDistance) {
  27265. distance = currentDistance;
  27266. currentSprite = sprite;
  27267. if (fastCheck) {
  27268. break;
  27269. }
  27270. }
  27271. }
  27272. }
  27273. if (currentSprite) {
  27274. var result = new BABYLON.PickingInfo();
  27275. result.hit = true;
  27276. result.pickedSprite = currentSprite;
  27277. result.distance = distance;
  27278. return result;
  27279. }
  27280. return null;
  27281. };
  27282. SpriteManager.prototype.render = function () {
  27283. // Check
  27284. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  27285. return;
  27286. var engine = this._scene.getEngine();
  27287. var baseSize = this._spriteTexture.getBaseSize();
  27288. // Sprites
  27289. var deltaTime = engine.getDeltaTime();
  27290. var max = Math.min(this._capacity, this.sprites.length);
  27291. var rowSize = baseSize.width / this.cellWidth;
  27292. var offset = 0;
  27293. for (var index = 0; index < max; index++) {
  27294. var sprite = this.sprites[index];
  27295. if (!sprite) {
  27296. continue;
  27297. }
  27298. sprite._animate(deltaTime);
  27299. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  27300. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  27301. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  27302. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  27303. }
  27304. this._buffer.update(this._vertexData);
  27305. // Render
  27306. var effect = this._effectBase;
  27307. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27308. effect = this._effectFog;
  27309. }
  27310. engine.enableEffect(effect);
  27311. var viewMatrix = this._scene.getViewMatrix();
  27312. effect.setTexture("diffuseSampler", this._spriteTexture);
  27313. effect.setMatrix("view", viewMatrix);
  27314. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27315. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  27316. // Fog
  27317. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27318. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  27319. effect.setColor3("vFogColor", this._scene.fogColor);
  27320. }
  27321. // VBOs
  27322. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27323. // Draw order
  27324. engine.setDepthFunctionToLessOrEqual();
  27325. effect.setBool("alphaTest", true);
  27326. engine.setColorWrite(false);
  27327. engine.draw(true, 0, max * 6);
  27328. engine.setColorWrite(true);
  27329. effect.setBool("alphaTest", false);
  27330. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27331. engine.draw(true, 0, max * 6);
  27332. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27333. };
  27334. SpriteManager.prototype.dispose = function () {
  27335. if (this._buffer) {
  27336. this._buffer.dispose();
  27337. this._buffer = null;
  27338. }
  27339. if (this._indexBuffer) {
  27340. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27341. this._indexBuffer = null;
  27342. }
  27343. if (this._spriteTexture) {
  27344. this._spriteTexture.dispose();
  27345. this._spriteTexture = null;
  27346. }
  27347. // Remove from scene
  27348. var index = this._scene.spriteManagers.indexOf(this);
  27349. this._scene.spriteManagers.splice(index, 1);
  27350. // Callback
  27351. this.onDisposeObservable.notifyObservers(this);
  27352. this.onDisposeObservable.clear();
  27353. };
  27354. return SpriteManager;
  27355. }());
  27356. BABYLON.SpriteManager = SpriteManager;
  27357. })(BABYLON || (BABYLON = {}));
  27358. var BABYLON;
  27359. (function (BABYLON) {
  27360. var Sprite = (function () {
  27361. function Sprite(name, manager) {
  27362. this.name = name;
  27363. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27364. this.width = 1.0;
  27365. this.height = 1.0;
  27366. this.angle = 0;
  27367. this.cellIndex = 0;
  27368. this.invertU = 0;
  27369. this.invertV = 0;
  27370. this.animations = new Array();
  27371. this.isPickable = false;
  27372. this._animationStarted = false;
  27373. this._loopAnimation = false;
  27374. this._fromIndex = 0;
  27375. this._toIndex = 0;
  27376. this._delay = 0;
  27377. this._direction = 1;
  27378. this._frameCount = 0;
  27379. this._time = 0;
  27380. this._manager = manager;
  27381. this._manager.sprites.push(this);
  27382. this.position = BABYLON.Vector3.Zero();
  27383. }
  27384. Object.defineProperty(Sprite.prototype, "size", {
  27385. get: function () {
  27386. return this.width;
  27387. },
  27388. set: function (value) {
  27389. this.width = value;
  27390. this.height = value;
  27391. },
  27392. enumerable: true,
  27393. configurable: true
  27394. });
  27395. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  27396. this._fromIndex = from;
  27397. this._toIndex = to;
  27398. this._loopAnimation = loop;
  27399. this._delay = delay;
  27400. this._animationStarted = true;
  27401. this._direction = from < to ? 1 : -1;
  27402. this.cellIndex = from;
  27403. this._time = 0;
  27404. this._onAnimationEnd = onAnimationEnd;
  27405. };
  27406. Sprite.prototype.stopAnimation = function () {
  27407. this._animationStarted = false;
  27408. };
  27409. Sprite.prototype._animate = function (deltaTime) {
  27410. if (!this._animationStarted)
  27411. return;
  27412. this._time += deltaTime;
  27413. if (this._time > this._delay) {
  27414. this._time = this._time % this._delay;
  27415. this.cellIndex += this._direction;
  27416. if (this.cellIndex === this._toIndex) {
  27417. if (this._loopAnimation) {
  27418. this.cellIndex = this._fromIndex;
  27419. }
  27420. else {
  27421. this._animationStarted = false;
  27422. if (this._onAnimationEnd) {
  27423. this._onAnimationEnd();
  27424. }
  27425. if (this.disposeWhenFinishedAnimating) {
  27426. this.dispose();
  27427. }
  27428. }
  27429. }
  27430. }
  27431. };
  27432. Sprite.prototype.dispose = function () {
  27433. for (var i = 0; i < this._manager.sprites.length; i++) {
  27434. if (this._manager.sprites[i] == this) {
  27435. this._manager.sprites.splice(i, 1);
  27436. }
  27437. }
  27438. };
  27439. return Sprite;
  27440. }());
  27441. BABYLON.Sprite = Sprite;
  27442. })(BABYLON || (BABYLON = {}));
  27443. var BABYLON;
  27444. (function (BABYLON) {
  27445. var Layer = (function () {
  27446. function Layer(name, imgUrl, scene, isBackground, color) {
  27447. this.name = name;
  27448. this.scale = new BABYLON.Vector2(1, 1);
  27449. this.offset = new BABYLON.Vector2(0, 0);
  27450. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  27451. this._vertexBuffers = {};
  27452. // Events
  27453. /**
  27454. * An event triggered when the layer is disposed.
  27455. * @type {BABYLON.Observable}
  27456. */
  27457. this.onDisposeObservable = new BABYLON.Observable();
  27458. /**
  27459. * An event triggered before rendering the scene
  27460. * @type {BABYLON.Observable}
  27461. */
  27462. this.onBeforeRenderObservable = new BABYLON.Observable();
  27463. /**
  27464. * An event triggered after rendering the scene
  27465. * @type {BABYLON.Observable}
  27466. */
  27467. this.onAfterRenderObservable = new BABYLON.Observable();
  27468. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  27469. this.isBackground = isBackground === undefined ? true : isBackground;
  27470. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  27471. this._scene = scene;
  27472. this._scene.layers.push(this);
  27473. var engine = scene.getEngine();
  27474. // VBO
  27475. var vertices = [];
  27476. vertices.push(1, 1);
  27477. vertices.push(-1, 1);
  27478. vertices.push(-1, -1);
  27479. vertices.push(1, -1);
  27480. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27481. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  27482. // Indices
  27483. var indices = [];
  27484. indices.push(0);
  27485. indices.push(1);
  27486. indices.push(2);
  27487. indices.push(0);
  27488. indices.push(2);
  27489. indices.push(3);
  27490. this._indexBuffer = engine.createIndexBuffer(indices);
  27491. // Effects
  27492. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  27493. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  27494. }
  27495. Object.defineProperty(Layer.prototype, "onDispose", {
  27496. set: function (callback) {
  27497. if (this._onDisposeObserver) {
  27498. this.onDisposeObservable.remove(this._onDisposeObserver);
  27499. }
  27500. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27501. },
  27502. enumerable: true,
  27503. configurable: true
  27504. });
  27505. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  27506. set: function (callback) {
  27507. if (this._onBeforeRenderObserver) {
  27508. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27509. }
  27510. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27511. },
  27512. enumerable: true,
  27513. configurable: true
  27514. });
  27515. Object.defineProperty(Layer.prototype, "onAfterRender", {
  27516. set: function (callback) {
  27517. if (this._onAfterRenderObserver) {
  27518. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27519. }
  27520. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27521. },
  27522. enumerable: true,
  27523. configurable: true
  27524. });
  27525. Layer.prototype.render = function () {
  27526. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  27527. // Check
  27528. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  27529. return;
  27530. var engine = this._scene.getEngine();
  27531. this.onBeforeRenderObservable.notifyObservers(this);
  27532. // Render
  27533. engine.enableEffect(currentEffect);
  27534. engine.setState(false);
  27535. // Texture
  27536. currentEffect.setTexture("textureSampler", this.texture);
  27537. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  27538. // Color
  27539. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  27540. // Scale / offset
  27541. currentEffect.setVector2("offset", this.offset);
  27542. currentEffect.setVector2("scale", this.scale);
  27543. // VBOs
  27544. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  27545. // Draw order
  27546. if (!this.alphaTest) {
  27547. engine.setAlphaMode(this.alphaBlendingMode);
  27548. engine.draw(true, 0, 6);
  27549. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27550. }
  27551. else {
  27552. engine.draw(true, 0, 6);
  27553. }
  27554. this.onAfterRenderObservable.notifyObservers(this);
  27555. };
  27556. Layer.prototype.dispose = function () {
  27557. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27558. if (vertexBuffer) {
  27559. vertexBuffer.dispose();
  27560. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27561. }
  27562. if (this._indexBuffer) {
  27563. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27564. this._indexBuffer = null;
  27565. }
  27566. if (this.texture) {
  27567. this.texture.dispose();
  27568. this.texture = null;
  27569. }
  27570. // Remove from scene
  27571. var index = this._scene.layers.indexOf(this);
  27572. this._scene.layers.splice(index, 1);
  27573. // Callback
  27574. this.onDisposeObservable.notifyObservers(this);
  27575. this.onDisposeObservable.clear();
  27576. this.onAfterRenderObservable.clear();
  27577. this.onBeforeRenderObservable.clear();
  27578. };
  27579. return Layer;
  27580. }());
  27581. BABYLON.Layer = Layer;
  27582. })(BABYLON || (BABYLON = {}));
  27583. var BABYLON;
  27584. (function (BABYLON) {
  27585. var Particle = (function () {
  27586. function Particle() {
  27587. this.position = BABYLON.Vector3.Zero();
  27588. this.direction = BABYLON.Vector3.Zero();
  27589. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27590. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27591. this.lifeTime = 1.0;
  27592. this.age = 0;
  27593. this.size = 0;
  27594. this.angle = 0;
  27595. this.angularSpeed = 0;
  27596. }
  27597. Particle.prototype.copyTo = function (other) {
  27598. other.position.copyFrom(this.position);
  27599. other.direction.copyFrom(this.direction);
  27600. other.color.copyFrom(this.color);
  27601. other.colorStep.copyFrom(this.colorStep);
  27602. other.lifeTime = this.lifeTime;
  27603. other.age = this.age;
  27604. other.size = this.size;
  27605. other.angle = this.angle;
  27606. other.angularSpeed = this.angularSpeed;
  27607. };
  27608. return Particle;
  27609. }());
  27610. BABYLON.Particle = Particle;
  27611. })(BABYLON || (BABYLON = {}));
  27612. var BABYLON;
  27613. (function (BABYLON) {
  27614. var randomNumber = function (min, max) {
  27615. if (min === max) {
  27616. return (min);
  27617. }
  27618. var random = Math.random();
  27619. return ((random * (max - min)) + min);
  27620. };
  27621. var ParticleSystem = (function () {
  27622. function ParticleSystem(name, capacity, scene, customEffect) {
  27623. var _this = this;
  27624. this.name = name;
  27625. // Members
  27626. this.animations = [];
  27627. this.renderingGroupId = 0;
  27628. this.emitter = null;
  27629. this.emitRate = 10;
  27630. this.manualEmitCount = -1;
  27631. this.updateSpeed = 0.01;
  27632. this.targetStopDuration = 0;
  27633. this.disposeOnStop = false;
  27634. this.minEmitPower = 1;
  27635. this.maxEmitPower = 1;
  27636. this.minLifeTime = 1;
  27637. this.maxLifeTime = 1;
  27638. this.minSize = 1;
  27639. this.maxSize = 1;
  27640. this.minAngularSpeed = 0;
  27641. this.maxAngularSpeed = 0;
  27642. this.layerMask = 0x0FFFFFFF;
  27643. /**
  27644. * An event triggered when the system is disposed.
  27645. * @type {BABYLON.Observable}
  27646. */
  27647. this.onDisposeObservable = new BABYLON.Observable();
  27648. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27649. this.forceDepthWrite = false;
  27650. this.gravity = BABYLON.Vector3.Zero();
  27651. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27652. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27653. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27654. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27655. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27656. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27657. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27658. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27659. this.particles = new Array();
  27660. this._stockParticles = new Array();
  27661. this._newPartsExcess = 0;
  27662. this._vertexBuffers = {};
  27663. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27664. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27665. this._scaledDirection = BABYLON.Vector3.Zero();
  27666. this._scaledGravity = BABYLON.Vector3.Zero();
  27667. this._currentRenderId = -1;
  27668. this._started = false;
  27669. this._stopped = false;
  27670. this._actualFrame = 0;
  27671. this.id = name;
  27672. this._capacity = capacity;
  27673. this._scene = scene;
  27674. this._customEffect = customEffect;
  27675. scene.particleSystems.push(this);
  27676. var indices = [];
  27677. var index = 0;
  27678. for (var count = 0; count < capacity; count++) {
  27679. indices.push(index);
  27680. indices.push(index + 1);
  27681. indices.push(index + 2);
  27682. indices.push(index);
  27683. indices.push(index + 2);
  27684. indices.push(index + 3);
  27685. index += 4;
  27686. }
  27687. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27688. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  27689. this._vertexData = new Float32Array(capacity * 11 * 4);
  27690. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  27691. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  27692. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  27693. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  27694. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27695. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27696. this._vertexBuffers["options"] = options;
  27697. // Default behaviors
  27698. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  27699. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  27700. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  27701. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  27702. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  27703. };
  27704. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  27705. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  27706. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  27707. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  27708. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  27709. };
  27710. this.updateFunction = function (particles) {
  27711. for (var index = 0; index < particles.length; index++) {
  27712. var particle = particles[index];
  27713. particle.age += _this._scaledUpdateSpeed;
  27714. if (particle.age >= particle.lifeTime) {
  27715. _this.recycleParticle(particle);
  27716. index--;
  27717. continue;
  27718. }
  27719. else {
  27720. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27721. particle.color.addInPlace(_this._scaledColorStep);
  27722. if (particle.color.a < 0)
  27723. particle.color.a = 0;
  27724. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27725. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27726. particle.position.addInPlace(_this._scaledDirection);
  27727. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27728. particle.direction.addInPlace(_this._scaledGravity);
  27729. }
  27730. }
  27731. };
  27732. }
  27733. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27734. set: function (callback) {
  27735. if (this._onDisposeObserver) {
  27736. this.onDisposeObservable.remove(this._onDisposeObserver);
  27737. }
  27738. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27739. },
  27740. enumerable: true,
  27741. configurable: true
  27742. });
  27743. ParticleSystem.prototype.recycleParticle = function (particle) {
  27744. var lastParticle = this.particles.pop();
  27745. if (lastParticle !== particle) {
  27746. lastParticle.copyTo(particle);
  27747. this._stockParticles.push(lastParticle);
  27748. }
  27749. };
  27750. ParticleSystem.prototype.getCapacity = function () {
  27751. return this._capacity;
  27752. };
  27753. ParticleSystem.prototype.isAlive = function () {
  27754. return this._alive;
  27755. };
  27756. ParticleSystem.prototype.isStarted = function () {
  27757. return this._started;
  27758. };
  27759. ParticleSystem.prototype.start = function () {
  27760. this._started = true;
  27761. this._stopped = false;
  27762. this._actualFrame = 0;
  27763. };
  27764. ParticleSystem.prototype.stop = function () {
  27765. this._stopped = true;
  27766. };
  27767. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27768. var offset = index * 11;
  27769. this._vertexData[offset] = particle.position.x;
  27770. this._vertexData[offset + 1] = particle.position.y;
  27771. this._vertexData[offset + 2] = particle.position.z;
  27772. this._vertexData[offset + 3] = particle.color.r;
  27773. this._vertexData[offset + 4] = particle.color.g;
  27774. this._vertexData[offset + 5] = particle.color.b;
  27775. this._vertexData[offset + 6] = particle.color.a;
  27776. this._vertexData[offset + 7] = particle.angle;
  27777. this._vertexData[offset + 8] = particle.size;
  27778. this._vertexData[offset + 9] = offsetX;
  27779. this._vertexData[offset + 10] = offsetY;
  27780. };
  27781. ParticleSystem.prototype._update = function (newParticles) {
  27782. // Update current
  27783. this._alive = this.particles.length > 0;
  27784. this.updateFunction(this.particles);
  27785. // Add new ones
  27786. var worldMatrix;
  27787. if (this.emitter.position) {
  27788. worldMatrix = this.emitter.getWorldMatrix();
  27789. }
  27790. else {
  27791. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  27792. }
  27793. var particle;
  27794. for (var index = 0; index < newParticles; index++) {
  27795. if (this.particles.length === this._capacity) {
  27796. break;
  27797. }
  27798. if (this._stockParticles.length !== 0) {
  27799. particle = this._stockParticles.pop();
  27800. particle.age = 0;
  27801. }
  27802. else {
  27803. particle = new BABYLON.Particle();
  27804. }
  27805. this.particles.push(particle);
  27806. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  27807. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  27808. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  27809. particle.size = randomNumber(this.minSize, this.maxSize);
  27810. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  27811. this.startPositionFunction(worldMatrix, particle.position, particle);
  27812. var step = randomNumber(0, 1.0);
  27813. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  27814. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  27815. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  27816. }
  27817. };
  27818. ParticleSystem.prototype._getEffect = function () {
  27819. if (this._customEffect) {
  27820. return this._customEffect;
  27821. }
  27822. ;
  27823. var defines = [];
  27824. if (this._scene.clipPlane) {
  27825. defines.push("#define CLIPPLANE");
  27826. }
  27827. // Effect
  27828. var join = defines.join("\n");
  27829. if (this._cachedDefines !== join) {
  27830. this._cachedDefines = join;
  27831. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  27832. }
  27833. return this._effect;
  27834. };
  27835. ParticleSystem.prototype.animate = function () {
  27836. if (!this._started)
  27837. return;
  27838. var effect = this._getEffect();
  27839. // Check
  27840. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  27841. return;
  27842. if (this._currentRenderId === this._scene.getRenderId()) {
  27843. return;
  27844. }
  27845. this._currentRenderId = this._scene.getRenderId();
  27846. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  27847. // determine the number of particles we need to create
  27848. var newParticles;
  27849. if (this.manualEmitCount > -1) {
  27850. newParticles = this.manualEmitCount;
  27851. this._newPartsExcess = 0;
  27852. this.manualEmitCount = 0;
  27853. }
  27854. else {
  27855. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  27856. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  27857. }
  27858. if (this._newPartsExcess > 1.0) {
  27859. newParticles += this._newPartsExcess >> 0;
  27860. this._newPartsExcess -= this._newPartsExcess >> 0;
  27861. }
  27862. this._alive = false;
  27863. if (!this._stopped) {
  27864. this._actualFrame += this._scaledUpdateSpeed;
  27865. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  27866. this.stop();
  27867. }
  27868. else {
  27869. newParticles = 0;
  27870. }
  27871. this._update(newParticles);
  27872. // Stopped?
  27873. if (this._stopped) {
  27874. if (!this._alive) {
  27875. this._started = false;
  27876. if (this.disposeOnStop) {
  27877. this._scene._toBeDisposed.push(this);
  27878. }
  27879. }
  27880. }
  27881. // Update VBO
  27882. var offset = 0;
  27883. for (var index = 0; index < this.particles.length; index++) {
  27884. var particle = this.particles[index];
  27885. this._appendParticleVertex(offset++, particle, 0, 0);
  27886. this._appendParticleVertex(offset++, particle, 1, 0);
  27887. this._appendParticleVertex(offset++, particle, 1, 1);
  27888. this._appendParticleVertex(offset++, particle, 0, 1);
  27889. }
  27890. this._vertexBuffer.update(this._vertexData);
  27891. };
  27892. ParticleSystem.prototype.render = function () {
  27893. var effect = this._getEffect();
  27894. // Check
  27895. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  27896. return 0;
  27897. var engine = this._scene.getEngine();
  27898. // Render
  27899. engine.enableEffect(effect);
  27900. engine.setState(false);
  27901. var viewMatrix = this._scene.getViewMatrix();
  27902. effect.setTexture("diffuseSampler", this.particleTexture);
  27903. effect.setMatrix("view", viewMatrix);
  27904. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27905. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  27906. if (this._scene.clipPlane) {
  27907. var clipPlane = this._scene.clipPlane;
  27908. var invView = viewMatrix.clone();
  27909. invView.invert();
  27910. effect.setMatrix("invView", invView);
  27911. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27912. }
  27913. // VBOs
  27914. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27915. // Draw order
  27916. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  27917. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  27918. }
  27919. else {
  27920. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27921. }
  27922. if (this.forceDepthWrite) {
  27923. engine.setDepthWrite(true);
  27924. }
  27925. engine.draw(true, 0, this.particles.length * 6);
  27926. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27927. return this.particles.length;
  27928. };
  27929. ParticleSystem.prototype.dispose = function () {
  27930. if (this._vertexBuffer) {
  27931. this._vertexBuffer.dispose();
  27932. this._vertexBuffer = null;
  27933. }
  27934. if (this._indexBuffer) {
  27935. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27936. this._indexBuffer = null;
  27937. }
  27938. if (this.particleTexture) {
  27939. this.particleTexture.dispose();
  27940. this.particleTexture = null;
  27941. }
  27942. // Remove from scene
  27943. var index = this._scene.particleSystems.indexOf(this);
  27944. this._scene.particleSystems.splice(index, 1);
  27945. // Callback
  27946. this.onDisposeObservable.notifyObservers(this);
  27947. this.onDisposeObservable.clear();
  27948. };
  27949. // Clone
  27950. ParticleSystem.prototype.clone = function (name, newEmitter) {
  27951. var result = new ParticleSystem(name, this._capacity, this._scene);
  27952. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  27953. if (newEmitter === undefined) {
  27954. newEmitter = this.emitter;
  27955. }
  27956. result.emitter = newEmitter;
  27957. if (this.particleTexture) {
  27958. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  27959. }
  27960. result.start();
  27961. return result;
  27962. };
  27963. ParticleSystem.prototype.serialize = function () {
  27964. var serializationObject = {};
  27965. serializationObject.name = this.name;
  27966. serializationObject.id = this.id;
  27967. // Emitter
  27968. if (this.emitter.position) {
  27969. serializationObject.emitterId = this.emitter.id;
  27970. }
  27971. else {
  27972. serializationObject.emitter = this.emitter.asArray();
  27973. }
  27974. serializationObject.capacity = this.getCapacity();
  27975. if (this.particleTexture) {
  27976. serializationObject.textureName = this.particleTexture.name;
  27977. }
  27978. // Animations
  27979. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27980. // Particle system
  27981. serializationObject.minAngularSpeed = this.minAngularSpeed;
  27982. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  27983. serializationObject.minSize = this.minSize;
  27984. serializationObject.maxSize = this.maxSize;
  27985. serializationObject.minEmitPower = this.minEmitPower;
  27986. serializationObject.maxEmitPower = this.maxEmitPower;
  27987. serializationObject.minLifeTime = this.minLifeTime;
  27988. serializationObject.maxLifeTime = this.maxLifeTime;
  27989. serializationObject.emitRate = this.emitRate;
  27990. serializationObject.minEmitBox = this.minEmitBox.asArray();
  27991. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  27992. serializationObject.gravity = this.gravity.asArray();
  27993. serializationObject.direction1 = this.direction1.asArray();
  27994. serializationObject.direction2 = this.direction2.asArray();
  27995. serializationObject.color1 = this.color1.asArray();
  27996. serializationObject.color2 = this.color2.asArray();
  27997. serializationObject.colorDead = this.colorDead.asArray();
  27998. serializationObject.updateSpeed = this.updateSpeed;
  27999. serializationObject.targetStopDuration = this.targetStopDuration;
  28000. serializationObject.textureMask = this.textureMask.asArray();
  28001. serializationObject.blendMode = this.blendMode;
  28002. return serializationObject;
  28003. };
  28004. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28005. var name = parsedParticleSystem.name;
  28006. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28007. if (parsedParticleSystem.id) {
  28008. particleSystem.id = parsedParticleSystem.id;
  28009. }
  28010. // Texture
  28011. if (parsedParticleSystem.textureName) {
  28012. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28013. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28014. }
  28015. // Emitter
  28016. if (parsedParticleSystem.emitterId) {
  28017. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28018. }
  28019. else {
  28020. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28021. }
  28022. // Animations
  28023. if (parsedParticleSystem.animations) {
  28024. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28025. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28026. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28027. }
  28028. }
  28029. if (parsedParticleSystem.autoAnimate) {
  28030. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28031. }
  28032. // Particle system
  28033. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28034. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28035. particleSystem.minSize = parsedParticleSystem.minSize;
  28036. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28037. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28038. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28039. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28040. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28041. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28042. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28043. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28044. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28045. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28046. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28047. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28048. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28049. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28050. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28051. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28052. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28053. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28054. if (!parsedParticleSystem.preventAutoStart) {
  28055. particleSystem.start();
  28056. }
  28057. return particleSystem;
  28058. };
  28059. // Statics
  28060. ParticleSystem.BLENDMODE_ONEONE = 0;
  28061. ParticleSystem.BLENDMODE_STANDARD = 1;
  28062. return ParticleSystem;
  28063. }());
  28064. BABYLON.ParticleSystem = ParticleSystem;
  28065. })(BABYLON || (BABYLON = {}));
  28066. var BABYLON;
  28067. (function (BABYLON) {
  28068. var AnimationRange = (function () {
  28069. function AnimationRange(name, from, to) {
  28070. this.name = name;
  28071. this.from = from;
  28072. this.to = to;
  28073. }
  28074. AnimationRange.prototype.clone = function () {
  28075. return new AnimationRange(this.name, this.from, this.to);
  28076. };
  28077. return AnimationRange;
  28078. }());
  28079. BABYLON.AnimationRange = AnimationRange;
  28080. /**
  28081. * Composed of a frame, and an action function
  28082. */
  28083. var AnimationEvent = (function () {
  28084. function AnimationEvent(frame, action, onlyOnce) {
  28085. this.frame = frame;
  28086. this.action = action;
  28087. this.onlyOnce = onlyOnce;
  28088. this.isDone = false;
  28089. }
  28090. return AnimationEvent;
  28091. }());
  28092. BABYLON.AnimationEvent = AnimationEvent;
  28093. var PathCursor = (function () {
  28094. function PathCursor(path) {
  28095. this.path = path;
  28096. this._onchange = new Array();
  28097. this.value = 0;
  28098. this.animations = new Array();
  28099. }
  28100. PathCursor.prototype.getPoint = function () {
  28101. var point = this.path.getPointAtLengthPosition(this.value);
  28102. return new BABYLON.Vector3(point.x, 0, point.y);
  28103. };
  28104. PathCursor.prototype.moveAhead = function (step) {
  28105. if (step === void 0) { step = 0.002; }
  28106. this.move(step);
  28107. return this;
  28108. };
  28109. PathCursor.prototype.moveBack = function (step) {
  28110. if (step === void 0) { step = 0.002; }
  28111. this.move(-step);
  28112. return this;
  28113. };
  28114. PathCursor.prototype.move = function (step) {
  28115. if (Math.abs(step) > 1) {
  28116. throw "step size should be less than 1.";
  28117. }
  28118. this.value += step;
  28119. this.ensureLimits();
  28120. this.raiseOnChange();
  28121. return this;
  28122. };
  28123. PathCursor.prototype.ensureLimits = function () {
  28124. while (this.value > 1) {
  28125. this.value -= 1;
  28126. }
  28127. while (this.value < 0) {
  28128. this.value += 1;
  28129. }
  28130. return this;
  28131. };
  28132. // used by animation engine
  28133. PathCursor.prototype.markAsDirty = function (propertyName) {
  28134. this.ensureLimits();
  28135. this.raiseOnChange();
  28136. return this;
  28137. };
  28138. PathCursor.prototype.raiseOnChange = function () {
  28139. var _this = this;
  28140. this._onchange.forEach(function (f) { return f(_this); });
  28141. return this;
  28142. };
  28143. PathCursor.prototype.onchange = function (f) {
  28144. this._onchange.push(f);
  28145. return this;
  28146. };
  28147. return PathCursor;
  28148. }());
  28149. BABYLON.PathCursor = PathCursor;
  28150. var Animation = (function () {
  28151. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28152. this.name = name;
  28153. this.targetProperty = targetProperty;
  28154. this.framePerSecond = framePerSecond;
  28155. this.dataType = dataType;
  28156. this.loopMode = loopMode;
  28157. this.enableBlending = enableBlending;
  28158. this._offsetsCache = {};
  28159. this._highLimitsCache = {};
  28160. this._stopped = false;
  28161. this._blendingFactor = 0;
  28162. // The set of event that will be linked to this animation
  28163. this._events = new Array();
  28164. this.allowMatricesInterpolation = false;
  28165. this.blendingSpeed = 0.01;
  28166. this._ranges = {};
  28167. this.targetPropertyPath = targetProperty.split(".");
  28168. this.dataType = dataType;
  28169. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28170. }
  28171. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28172. var dataType = undefined;
  28173. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28174. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28175. }
  28176. else if (from instanceof BABYLON.Quaternion) {
  28177. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28178. }
  28179. else if (from instanceof BABYLON.Vector3) {
  28180. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28181. }
  28182. else if (from instanceof BABYLON.Vector2) {
  28183. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28184. }
  28185. else if (from instanceof BABYLON.Color3) {
  28186. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28187. }
  28188. else if (from instanceof BABYLON.Size) {
  28189. dataType = Animation.ANIMATIONTYPE_SIZE;
  28190. }
  28191. if (dataType == undefined) {
  28192. return null;
  28193. }
  28194. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28195. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28196. animation.setKeys(keys);
  28197. if (easingFunction !== undefined) {
  28198. animation.setEasingFunction(easingFunction);
  28199. }
  28200. return animation;
  28201. };
  28202. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28203. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28204. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28205. };
  28206. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28207. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28208. node.animations.push(animation);
  28209. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28210. };
  28211. // Methods
  28212. /**
  28213. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28214. */
  28215. Animation.prototype.toString = function (fullDetails) {
  28216. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28217. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28218. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28219. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28220. if (fullDetails) {
  28221. ret += ", Ranges: {";
  28222. var first = true;
  28223. for (var name in this._ranges) {
  28224. if (first) {
  28225. ret += ", ";
  28226. first = false;
  28227. }
  28228. ret += name;
  28229. }
  28230. ret += "}";
  28231. }
  28232. return ret;
  28233. };
  28234. /**
  28235. * Add an event to this animation.
  28236. */
  28237. Animation.prototype.addEvent = function (event) {
  28238. this._events.push(event);
  28239. };
  28240. /**
  28241. * Remove all events found at the given frame
  28242. * @param frame
  28243. */
  28244. Animation.prototype.removeEvents = function (frame) {
  28245. for (var index = 0; index < this._events.length; index++) {
  28246. if (this._events[index].frame === frame) {
  28247. this._events.splice(index, 1);
  28248. index--;
  28249. }
  28250. }
  28251. };
  28252. Animation.prototype.createRange = function (name, from, to) {
  28253. // check name not already in use; could happen for bones after serialized
  28254. if (!this._ranges[name]) {
  28255. this._ranges[name] = new AnimationRange(name, from, to);
  28256. }
  28257. };
  28258. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28259. if (deleteFrames === void 0) { deleteFrames = true; }
  28260. if (this._ranges[name]) {
  28261. if (deleteFrames) {
  28262. var from = this._ranges[name].from;
  28263. var to = this._ranges[name].to;
  28264. // this loop MUST go high to low for multiple splices to work
  28265. for (var key = this._keys.length - 1; key >= 0; key--) {
  28266. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28267. this._keys.splice(key, 1);
  28268. }
  28269. }
  28270. }
  28271. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28272. }
  28273. };
  28274. Animation.prototype.getRange = function (name) {
  28275. return this._ranges[name];
  28276. };
  28277. Animation.prototype.reset = function () {
  28278. this._offsetsCache = {};
  28279. this._highLimitsCache = {};
  28280. this.currentFrame = 0;
  28281. this._blendingFactor = 0;
  28282. this._originalBlendValue = null;
  28283. };
  28284. Animation.prototype.isStopped = function () {
  28285. return this._stopped;
  28286. };
  28287. Animation.prototype.getKeys = function () {
  28288. return this._keys;
  28289. };
  28290. Animation.prototype.getHighestFrame = function () {
  28291. var ret = 0;
  28292. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28293. if (ret < this._keys[key].frame) {
  28294. ret = this._keys[key].frame;
  28295. }
  28296. }
  28297. return ret;
  28298. };
  28299. Animation.prototype.getEasingFunction = function () {
  28300. return this._easingFunction;
  28301. };
  28302. Animation.prototype.setEasingFunction = function (easingFunction) {
  28303. this._easingFunction = easingFunction;
  28304. };
  28305. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28306. return startValue + (endValue - startValue) * gradient;
  28307. };
  28308. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28309. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28310. };
  28311. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28312. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28313. };
  28314. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28315. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28316. };
  28317. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28318. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28319. };
  28320. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28321. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28322. };
  28323. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28324. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28325. };
  28326. Animation.prototype.clone = function () {
  28327. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28328. if (this._keys) {
  28329. clone.setKeys(this._keys);
  28330. }
  28331. if (this._ranges) {
  28332. clone._ranges = {};
  28333. for (var name in this._ranges) {
  28334. clone._ranges[name] = this._ranges[name].clone();
  28335. }
  28336. }
  28337. return clone;
  28338. };
  28339. Animation.prototype.setKeys = function (values) {
  28340. this._keys = values.slice(0);
  28341. this._offsetsCache = {};
  28342. this._highLimitsCache = {};
  28343. };
  28344. Animation.prototype._getKeyValue = function (value) {
  28345. if (typeof value === "function") {
  28346. return value();
  28347. }
  28348. return value;
  28349. };
  28350. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28351. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28352. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28353. }
  28354. this.currentFrame = currentFrame;
  28355. // Try to get a hash to find the right key
  28356. 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));
  28357. if (this._keys[startKey].frame >= currentFrame) {
  28358. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  28359. startKey--;
  28360. }
  28361. }
  28362. for (var key = startKey; key < this._keys.length; key++) {
  28363. if (this._keys[key + 1].frame >= currentFrame) {
  28364. var startValue = this._getKeyValue(this._keys[key].value);
  28365. var endValue = this._getKeyValue(this._keys[key + 1].value);
  28366. // gradient : percent of currentFrame between the frame inf and the frame sup
  28367. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  28368. // check for easingFunction and correction of gradient
  28369. if (this._easingFunction != null) {
  28370. gradient = this._easingFunction.ease(gradient);
  28371. }
  28372. switch (this.dataType) {
  28373. // Float
  28374. case Animation.ANIMATIONTYPE_FLOAT:
  28375. switch (loopMode) {
  28376. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28377. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28378. return this.floatInterpolateFunction(startValue, endValue, gradient);
  28379. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28380. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  28381. }
  28382. break;
  28383. // Quaternion
  28384. case Animation.ANIMATIONTYPE_QUATERNION:
  28385. var quaternion = null;
  28386. switch (loopMode) {
  28387. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28388. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28389. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28390. break;
  28391. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28392. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28393. break;
  28394. }
  28395. return quaternion;
  28396. // Vector3
  28397. case Animation.ANIMATIONTYPE_VECTOR3:
  28398. switch (loopMode) {
  28399. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28400. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28401. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  28402. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28403. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28404. }
  28405. // Vector2
  28406. case Animation.ANIMATIONTYPE_VECTOR2:
  28407. switch (loopMode) {
  28408. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28409. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28410. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  28411. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28412. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28413. }
  28414. // Size
  28415. case Animation.ANIMATIONTYPE_SIZE:
  28416. switch (loopMode) {
  28417. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28418. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28419. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28420. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28421. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28422. }
  28423. // Color3
  28424. case Animation.ANIMATIONTYPE_COLOR3:
  28425. switch (loopMode) {
  28426. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28427. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28428. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28429. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28430. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28431. }
  28432. // Matrix
  28433. case Animation.ANIMATIONTYPE_MATRIX:
  28434. switch (loopMode) {
  28435. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28436. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28437. if (this.allowMatricesInterpolation) {
  28438. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28439. }
  28440. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28441. return startValue;
  28442. }
  28443. default:
  28444. break;
  28445. }
  28446. break;
  28447. }
  28448. }
  28449. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28450. };
  28451. Animation.prototype.setValue = function (currentValue, blend) {
  28452. if (blend === void 0) { blend = false; }
  28453. // Set value
  28454. var path;
  28455. var destination;
  28456. if (this.targetPropertyPath.length > 1) {
  28457. var property = this._target[this.targetPropertyPath[0]];
  28458. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28459. property = property[this.targetPropertyPath[index]];
  28460. }
  28461. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28462. destination = property;
  28463. }
  28464. else {
  28465. path = this.targetPropertyPath[0];
  28466. destination = this._target;
  28467. }
  28468. // Blending
  28469. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28470. if (!this._originalBlendValue) {
  28471. if (destination[path].clone) {
  28472. this._originalBlendValue = destination[path].clone();
  28473. }
  28474. else {
  28475. this._originalBlendValue = destination[path];
  28476. }
  28477. }
  28478. if (this._originalBlendValue.prototype) {
  28479. if (this._originalBlendValue.prototype.Lerp) {
  28480. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28481. }
  28482. else {
  28483. destination[path] = currentValue;
  28484. }
  28485. }
  28486. else if (this._originalBlendValue.m) {
  28487. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28488. }
  28489. else {
  28490. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28491. }
  28492. this._blendingFactor += this.blendingSpeed;
  28493. }
  28494. else {
  28495. destination[path] = currentValue;
  28496. }
  28497. if (this._target.markAsDirty) {
  28498. this._target.markAsDirty(this.targetProperty);
  28499. }
  28500. };
  28501. Animation.prototype.goToFrame = function (frame) {
  28502. if (frame < this._keys[0].frame) {
  28503. frame = this._keys[0].frame;
  28504. }
  28505. else if (frame > this._keys[this._keys.length - 1].frame) {
  28506. frame = this._keys[this._keys.length - 1].frame;
  28507. }
  28508. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28509. this.setValue(currentValue);
  28510. };
  28511. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28512. if (blend === void 0) { blend = false; }
  28513. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28514. this._stopped = true;
  28515. return false;
  28516. }
  28517. var returnValue = true;
  28518. // Adding a start key at frame 0 if missing
  28519. if (this._keys[0].frame !== 0) {
  28520. var newKey = { frame: 0, value: this._keys[0].value };
  28521. this._keys.splice(0, 0, newKey);
  28522. }
  28523. // Check limits
  28524. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28525. from = this._keys[0].frame;
  28526. }
  28527. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28528. to = this._keys[this._keys.length - 1].frame;
  28529. }
  28530. // Compute ratio
  28531. var range = to - from;
  28532. var offsetValue;
  28533. // ratio represents the frame delta between from and to
  28534. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28535. var highLimitValue = 0;
  28536. if (ratio > range && !loop) {
  28537. returnValue = false;
  28538. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28539. }
  28540. else {
  28541. // Get max value if required
  28542. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28543. var keyOffset = to.toString() + from.toString();
  28544. if (!this._offsetsCache[keyOffset]) {
  28545. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28546. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28547. switch (this.dataType) {
  28548. // Float
  28549. case Animation.ANIMATIONTYPE_FLOAT:
  28550. this._offsetsCache[keyOffset] = toValue - fromValue;
  28551. break;
  28552. // Quaternion
  28553. case Animation.ANIMATIONTYPE_QUATERNION:
  28554. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28555. break;
  28556. // Vector3
  28557. case Animation.ANIMATIONTYPE_VECTOR3:
  28558. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28559. // Vector2
  28560. case Animation.ANIMATIONTYPE_VECTOR2:
  28561. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28562. // Size
  28563. case Animation.ANIMATIONTYPE_SIZE:
  28564. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28565. // Color3
  28566. case Animation.ANIMATIONTYPE_COLOR3:
  28567. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28568. default:
  28569. break;
  28570. }
  28571. this._highLimitsCache[keyOffset] = toValue;
  28572. }
  28573. highLimitValue = this._highLimitsCache[keyOffset];
  28574. offsetValue = this._offsetsCache[keyOffset];
  28575. }
  28576. }
  28577. if (offsetValue === undefined) {
  28578. switch (this.dataType) {
  28579. // Float
  28580. case Animation.ANIMATIONTYPE_FLOAT:
  28581. offsetValue = 0;
  28582. break;
  28583. // Quaternion
  28584. case Animation.ANIMATIONTYPE_QUATERNION:
  28585. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28586. break;
  28587. // Vector3
  28588. case Animation.ANIMATIONTYPE_VECTOR3:
  28589. offsetValue = BABYLON.Vector3.Zero();
  28590. break;
  28591. // Vector2
  28592. case Animation.ANIMATIONTYPE_VECTOR2:
  28593. offsetValue = BABYLON.Vector2.Zero();
  28594. break;
  28595. // Size
  28596. case Animation.ANIMATIONTYPE_SIZE:
  28597. offsetValue = BABYLON.Size.Zero();
  28598. break;
  28599. // Color3
  28600. case Animation.ANIMATIONTYPE_COLOR3:
  28601. offsetValue = BABYLON.Color3.Black();
  28602. }
  28603. }
  28604. // Compute value
  28605. var repeatCount = (ratio / range) >> 0;
  28606. var currentFrame = returnValue ? from + ratio % range : to;
  28607. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28608. // Set value
  28609. this.setValue(currentValue);
  28610. // Check events
  28611. for (var index = 0; index < this._events.length; index++) {
  28612. if (currentFrame >= this._events[index].frame) {
  28613. var event = this._events[index];
  28614. if (!event.isDone) {
  28615. // If event should be done only once, remove it.
  28616. if (event.onlyOnce) {
  28617. this._events.splice(index, 1);
  28618. index--;
  28619. }
  28620. event.isDone = true;
  28621. event.action();
  28622. } // Don't do anything if the event has already be done.
  28623. }
  28624. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28625. // reset event, the animation is looping
  28626. this._events[index].isDone = false;
  28627. }
  28628. }
  28629. if (!returnValue) {
  28630. this._stopped = true;
  28631. }
  28632. return returnValue;
  28633. };
  28634. Animation.prototype.serialize = function () {
  28635. var serializationObject = {};
  28636. serializationObject.name = this.name;
  28637. serializationObject.property = this.targetProperty;
  28638. serializationObject.framePerSecond = this.framePerSecond;
  28639. serializationObject.dataType = this.dataType;
  28640. serializationObject.loopBehavior = this.loopMode;
  28641. var dataType = this.dataType;
  28642. serializationObject.keys = [];
  28643. var keys = this.getKeys();
  28644. for (var index = 0; index < keys.length; index++) {
  28645. var animationKey = keys[index];
  28646. var key = {};
  28647. key.frame = animationKey.frame;
  28648. switch (dataType) {
  28649. case Animation.ANIMATIONTYPE_FLOAT:
  28650. key.values = [animationKey.value];
  28651. break;
  28652. case Animation.ANIMATIONTYPE_QUATERNION:
  28653. case Animation.ANIMATIONTYPE_MATRIX:
  28654. case Animation.ANIMATIONTYPE_VECTOR3:
  28655. case Animation.ANIMATIONTYPE_COLOR3:
  28656. key.values = animationKey.value.asArray();
  28657. break;
  28658. }
  28659. serializationObject.keys.push(key);
  28660. }
  28661. serializationObject.ranges = [];
  28662. for (var name in this._ranges) {
  28663. var range = {};
  28664. range.name = name;
  28665. range.from = this._ranges[name].from;
  28666. range.to = this._ranges[name].to;
  28667. serializationObject.ranges.push(range);
  28668. }
  28669. return serializationObject;
  28670. };
  28671. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28672. get: function () {
  28673. return Animation._ANIMATIONTYPE_FLOAT;
  28674. },
  28675. enumerable: true,
  28676. configurable: true
  28677. });
  28678. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28679. get: function () {
  28680. return Animation._ANIMATIONTYPE_VECTOR3;
  28681. },
  28682. enumerable: true,
  28683. configurable: true
  28684. });
  28685. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28686. get: function () {
  28687. return Animation._ANIMATIONTYPE_VECTOR2;
  28688. },
  28689. enumerable: true,
  28690. configurable: true
  28691. });
  28692. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28693. get: function () {
  28694. return Animation._ANIMATIONTYPE_SIZE;
  28695. },
  28696. enumerable: true,
  28697. configurable: true
  28698. });
  28699. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28700. get: function () {
  28701. return Animation._ANIMATIONTYPE_QUATERNION;
  28702. },
  28703. enumerable: true,
  28704. configurable: true
  28705. });
  28706. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28707. get: function () {
  28708. return Animation._ANIMATIONTYPE_MATRIX;
  28709. },
  28710. enumerable: true,
  28711. configurable: true
  28712. });
  28713. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28714. get: function () {
  28715. return Animation._ANIMATIONTYPE_COLOR3;
  28716. },
  28717. enumerable: true,
  28718. configurable: true
  28719. });
  28720. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28721. get: function () {
  28722. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28723. },
  28724. enumerable: true,
  28725. configurable: true
  28726. });
  28727. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28728. get: function () {
  28729. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28730. },
  28731. enumerable: true,
  28732. configurable: true
  28733. });
  28734. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28735. get: function () {
  28736. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28737. },
  28738. enumerable: true,
  28739. configurable: true
  28740. });
  28741. Animation.Parse = function (parsedAnimation) {
  28742. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28743. var dataType = parsedAnimation.dataType;
  28744. var keys = [];
  28745. var data;
  28746. var index;
  28747. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28748. var key = parsedAnimation.keys[index];
  28749. switch (dataType) {
  28750. case Animation.ANIMATIONTYPE_FLOAT:
  28751. data = key.values[0];
  28752. break;
  28753. case Animation.ANIMATIONTYPE_QUATERNION:
  28754. data = BABYLON.Quaternion.FromArray(key.values);
  28755. break;
  28756. case Animation.ANIMATIONTYPE_MATRIX:
  28757. data = BABYLON.Matrix.FromArray(key.values);
  28758. break;
  28759. case Animation.ANIMATIONTYPE_COLOR3:
  28760. data = BABYLON.Color3.FromArray(key.values);
  28761. break;
  28762. case Animation.ANIMATIONTYPE_VECTOR3:
  28763. default:
  28764. data = BABYLON.Vector3.FromArray(key.values);
  28765. break;
  28766. }
  28767. keys.push({
  28768. frame: key.frame,
  28769. value: data
  28770. });
  28771. }
  28772. animation.setKeys(keys);
  28773. if (parsedAnimation.ranges) {
  28774. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28775. data = parsedAnimation.ranges[index];
  28776. animation.createRange(data.name, data.from, data.to);
  28777. }
  28778. }
  28779. return animation;
  28780. };
  28781. Animation.AppendSerializedAnimations = function (source, destination) {
  28782. if (source.animations) {
  28783. destination.animations = [];
  28784. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28785. var animation = source.animations[animationIndex];
  28786. destination.animations.push(animation.serialize());
  28787. }
  28788. }
  28789. };
  28790. // Statics
  28791. Animation._ANIMATIONTYPE_FLOAT = 0;
  28792. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28793. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28794. Animation._ANIMATIONTYPE_MATRIX = 3;
  28795. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28796. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28797. Animation._ANIMATIONTYPE_SIZE = 6;
  28798. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28799. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28800. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28801. return Animation;
  28802. }());
  28803. BABYLON.Animation = Animation;
  28804. })(BABYLON || (BABYLON = {}));
  28805. var BABYLON;
  28806. (function (BABYLON) {
  28807. var Animatable = (function () {
  28808. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28809. if (fromFrame === void 0) { fromFrame = 0; }
  28810. if (toFrame === void 0) { toFrame = 100; }
  28811. if (loopAnimation === void 0) { loopAnimation = false; }
  28812. if (speedRatio === void 0) { speedRatio = 1.0; }
  28813. this.target = target;
  28814. this.fromFrame = fromFrame;
  28815. this.toFrame = toFrame;
  28816. this.loopAnimation = loopAnimation;
  28817. this.speedRatio = speedRatio;
  28818. this.onAnimationEnd = onAnimationEnd;
  28819. this._animations = new Array();
  28820. this._paused = false;
  28821. this.animationStarted = false;
  28822. if (animations) {
  28823. this.appendAnimations(target, animations);
  28824. }
  28825. this._scene = scene;
  28826. scene._activeAnimatables.push(this);
  28827. }
  28828. // Methods
  28829. Animatable.prototype.getAnimations = function () {
  28830. return this._animations;
  28831. };
  28832. Animatable.prototype.appendAnimations = function (target, animations) {
  28833. for (var index = 0; index < animations.length; index++) {
  28834. var animation = animations[index];
  28835. animation._target = target;
  28836. this._animations.push(animation);
  28837. }
  28838. };
  28839. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28840. var animations = this._animations;
  28841. for (var index = 0; index < animations.length; index++) {
  28842. if (animations[index].targetProperty === property) {
  28843. return animations[index];
  28844. }
  28845. }
  28846. return null;
  28847. };
  28848. Animatable.prototype.reset = function () {
  28849. var animations = this._animations;
  28850. for (var index = 0; index < animations.length; index++) {
  28851. animations[index].reset();
  28852. }
  28853. this._localDelayOffset = null;
  28854. this._pausedDelay = null;
  28855. };
  28856. Animatable.prototype.enableBlending = function (blendingSpeed) {
  28857. var animations = this._animations;
  28858. for (var index = 0; index < animations.length; index++) {
  28859. animations[index].enableBlending = true;
  28860. animations[index].blendingSpeed = blendingSpeed;
  28861. }
  28862. };
  28863. Animatable.prototype.disableBlending = function () {
  28864. var animations = this._animations;
  28865. for (var index = 0; index < animations.length; index++) {
  28866. animations[index].enableBlending = false;
  28867. }
  28868. };
  28869. Animatable.prototype.goToFrame = function (frame) {
  28870. var animations = this._animations;
  28871. for (var index = 0; index < animations.length; index++) {
  28872. animations[index].goToFrame(frame);
  28873. }
  28874. };
  28875. Animatable.prototype.pause = function () {
  28876. if (this._paused) {
  28877. return;
  28878. }
  28879. this._paused = true;
  28880. };
  28881. Animatable.prototype.restart = function () {
  28882. this._paused = false;
  28883. };
  28884. Animatable.prototype.stop = function (animationName) {
  28885. var index = this._scene._activeAnimatables.indexOf(this);
  28886. if (index > -1) {
  28887. var animations = this._animations;
  28888. var numberOfAnimationsStopped = 0;
  28889. for (var index = animations.length - 1; index >= 0; index--) {
  28890. if (typeof animationName === "string" && animations[index].name != animationName) {
  28891. continue;
  28892. }
  28893. animations[index].reset();
  28894. animations.splice(index, 1);
  28895. numberOfAnimationsStopped++;
  28896. }
  28897. if (animations.length == numberOfAnimationsStopped) {
  28898. this._scene._activeAnimatables.splice(index, 1);
  28899. if (this.onAnimationEnd) {
  28900. this.onAnimationEnd();
  28901. }
  28902. }
  28903. }
  28904. };
  28905. Animatable.prototype._animate = function (delay) {
  28906. if (this._paused) {
  28907. this.animationStarted = false;
  28908. if (!this._pausedDelay) {
  28909. this._pausedDelay = delay;
  28910. }
  28911. return true;
  28912. }
  28913. if (!this._localDelayOffset) {
  28914. this._localDelayOffset = delay;
  28915. }
  28916. else if (this._pausedDelay) {
  28917. this._localDelayOffset += delay - this._pausedDelay;
  28918. this._pausedDelay = null;
  28919. }
  28920. // Animating
  28921. var running = false;
  28922. var animations = this._animations;
  28923. var index;
  28924. for (index = 0; index < animations.length; index++) {
  28925. var animation = animations[index];
  28926. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  28927. running = running || isRunning;
  28928. }
  28929. this.animationStarted = running;
  28930. if (!running) {
  28931. // Remove from active animatables
  28932. index = this._scene._activeAnimatables.indexOf(this);
  28933. this._scene._activeAnimatables.splice(index, 1);
  28934. }
  28935. if (!running && this.onAnimationEnd) {
  28936. this.onAnimationEnd();
  28937. this.onAnimationEnd = null;
  28938. }
  28939. return running;
  28940. };
  28941. return Animatable;
  28942. }());
  28943. BABYLON.Animatable = Animatable;
  28944. })(BABYLON || (BABYLON = {}));
  28945. var BABYLON;
  28946. (function (BABYLON) {
  28947. var EasingFunction = (function () {
  28948. function EasingFunction() {
  28949. // Properties
  28950. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  28951. }
  28952. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  28953. get: function () {
  28954. return EasingFunction._EASINGMODE_EASEIN;
  28955. },
  28956. enumerable: true,
  28957. configurable: true
  28958. });
  28959. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  28960. get: function () {
  28961. return EasingFunction._EASINGMODE_EASEOUT;
  28962. },
  28963. enumerable: true,
  28964. configurable: true
  28965. });
  28966. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  28967. get: function () {
  28968. return EasingFunction._EASINGMODE_EASEINOUT;
  28969. },
  28970. enumerable: true,
  28971. configurable: true
  28972. });
  28973. EasingFunction.prototype.setEasingMode = function (easingMode) {
  28974. var n = Math.min(Math.max(easingMode, 0), 2);
  28975. this._easingMode = n;
  28976. };
  28977. EasingFunction.prototype.getEasingMode = function () {
  28978. return this._easingMode;
  28979. };
  28980. EasingFunction.prototype.easeInCore = function (gradient) {
  28981. throw new Error('You must implement this method');
  28982. };
  28983. EasingFunction.prototype.ease = function (gradient) {
  28984. switch (this._easingMode) {
  28985. case EasingFunction.EASINGMODE_EASEIN:
  28986. return this.easeInCore(gradient);
  28987. case EasingFunction.EASINGMODE_EASEOUT:
  28988. return (1 - this.easeInCore(1 - gradient));
  28989. }
  28990. if (gradient >= 0.5) {
  28991. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  28992. }
  28993. return (this.easeInCore(gradient * 2) * 0.5);
  28994. };
  28995. //Statics
  28996. EasingFunction._EASINGMODE_EASEIN = 0;
  28997. EasingFunction._EASINGMODE_EASEOUT = 1;
  28998. EasingFunction._EASINGMODE_EASEINOUT = 2;
  28999. return EasingFunction;
  29000. }());
  29001. BABYLON.EasingFunction = EasingFunction;
  29002. var CircleEase = (function (_super) {
  29003. __extends(CircleEase, _super);
  29004. function CircleEase() {
  29005. _super.apply(this, arguments);
  29006. }
  29007. CircleEase.prototype.easeInCore = function (gradient) {
  29008. gradient = Math.max(0, Math.min(1, gradient));
  29009. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29010. };
  29011. return CircleEase;
  29012. }(EasingFunction));
  29013. BABYLON.CircleEase = CircleEase;
  29014. var BackEase = (function (_super) {
  29015. __extends(BackEase, _super);
  29016. function BackEase(amplitude) {
  29017. if (amplitude === void 0) { amplitude = 1; }
  29018. _super.call(this);
  29019. this.amplitude = amplitude;
  29020. }
  29021. BackEase.prototype.easeInCore = function (gradient) {
  29022. var num = Math.max(0, this.amplitude);
  29023. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29024. };
  29025. return BackEase;
  29026. }(EasingFunction));
  29027. BABYLON.BackEase = BackEase;
  29028. var BounceEase = (function (_super) {
  29029. __extends(BounceEase, _super);
  29030. function BounceEase(bounces, bounciness) {
  29031. if (bounces === void 0) { bounces = 3; }
  29032. if (bounciness === void 0) { bounciness = 2; }
  29033. _super.call(this);
  29034. this.bounces = bounces;
  29035. this.bounciness = bounciness;
  29036. }
  29037. BounceEase.prototype.easeInCore = function (gradient) {
  29038. var y = Math.max(0.0, this.bounces);
  29039. var bounciness = this.bounciness;
  29040. if (bounciness <= 1.0) {
  29041. bounciness = 1.001;
  29042. }
  29043. var num9 = Math.pow(bounciness, y);
  29044. var num5 = 1.0 - bounciness;
  29045. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29046. var num15 = gradient * num4;
  29047. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29048. var num3 = Math.floor(num65);
  29049. var num13 = num3 + 1.0;
  29050. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29051. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29052. var num7 = (num8 + num12) * 0.5;
  29053. var num6 = gradient - num7;
  29054. var num2 = num7 - num8;
  29055. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29056. };
  29057. return BounceEase;
  29058. }(EasingFunction));
  29059. BABYLON.BounceEase = BounceEase;
  29060. var CubicEase = (function (_super) {
  29061. __extends(CubicEase, _super);
  29062. function CubicEase() {
  29063. _super.apply(this, arguments);
  29064. }
  29065. CubicEase.prototype.easeInCore = function (gradient) {
  29066. return (gradient * gradient * gradient);
  29067. };
  29068. return CubicEase;
  29069. }(EasingFunction));
  29070. BABYLON.CubicEase = CubicEase;
  29071. var ElasticEase = (function (_super) {
  29072. __extends(ElasticEase, _super);
  29073. function ElasticEase(oscillations, springiness) {
  29074. if (oscillations === void 0) { oscillations = 3; }
  29075. if (springiness === void 0) { springiness = 3; }
  29076. _super.call(this);
  29077. this.oscillations = oscillations;
  29078. this.springiness = springiness;
  29079. }
  29080. ElasticEase.prototype.easeInCore = function (gradient) {
  29081. var num2;
  29082. var num3 = Math.max(0.0, this.oscillations);
  29083. var num = Math.max(0.0, this.springiness);
  29084. if (num == 0) {
  29085. num2 = gradient;
  29086. }
  29087. else {
  29088. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29089. }
  29090. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29091. };
  29092. return ElasticEase;
  29093. }(EasingFunction));
  29094. BABYLON.ElasticEase = ElasticEase;
  29095. var ExponentialEase = (function (_super) {
  29096. __extends(ExponentialEase, _super);
  29097. function ExponentialEase(exponent) {
  29098. if (exponent === void 0) { exponent = 2; }
  29099. _super.call(this);
  29100. this.exponent = exponent;
  29101. }
  29102. ExponentialEase.prototype.easeInCore = function (gradient) {
  29103. if (this.exponent <= 0) {
  29104. return gradient;
  29105. }
  29106. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29107. };
  29108. return ExponentialEase;
  29109. }(EasingFunction));
  29110. BABYLON.ExponentialEase = ExponentialEase;
  29111. var PowerEase = (function (_super) {
  29112. __extends(PowerEase, _super);
  29113. function PowerEase(power) {
  29114. if (power === void 0) { power = 2; }
  29115. _super.call(this);
  29116. this.power = power;
  29117. }
  29118. PowerEase.prototype.easeInCore = function (gradient) {
  29119. var y = Math.max(0.0, this.power);
  29120. return Math.pow(gradient, y);
  29121. };
  29122. return PowerEase;
  29123. }(EasingFunction));
  29124. BABYLON.PowerEase = PowerEase;
  29125. var QuadraticEase = (function (_super) {
  29126. __extends(QuadraticEase, _super);
  29127. function QuadraticEase() {
  29128. _super.apply(this, arguments);
  29129. }
  29130. QuadraticEase.prototype.easeInCore = function (gradient) {
  29131. return (gradient * gradient);
  29132. };
  29133. return QuadraticEase;
  29134. }(EasingFunction));
  29135. BABYLON.QuadraticEase = QuadraticEase;
  29136. var QuarticEase = (function (_super) {
  29137. __extends(QuarticEase, _super);
  29138. function QuarticEase() {
  29139. _super.apply(this, arguments);
  29140. }
  29141. QuarticEase.prototype.easeInCore = function (gradient) {
  29142. return (gradient * gradient * gradient * gradient);
  29143. };
  29144. return QuarticEase;
  29145. }(EasingFunction));
  29146. BABYLON.QuarticEase = QuarticEase;
  29147. var QuinticEase = (function (_super) {
  29148. __extends(QuinticEase, _super);
  29149. function QuinticEase() {
  29150. _super.apply(this, arguments);
  29151. }
  29152. QuinticEase.prototype.easeInCore = function (gradient) {
  29153. return (gradient * gradient * gradient * gradient * gradient);
  29154. };
  29155. return QuinticEase;
  29156. }(EasingFunction));
  29157. BABYLON.QuinticEase = QuinticEase;
  29158. var SineEase = (function (_super) {
  29159. __extends(SineEase, _super);
  29160. function SineEase() {
  29161. _super.apply(this, arguments);
  29162. }
  29163. SineEase.prototype.easeInCore = function (gradient) {
  29164. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29165. };
  29166. return SineEase;
  29167. }(EasingFunction));
  29168. BABYLON.SineEase = SineEase;
  29169. var BezierCurveEase = (function (_super) {
  29170. __extends(BezierCurveEase, _super);
  29171. function BezierCurveEase(x1, y1, x2, y2) {
  29172. if (x1 === void 0) { x1 = 0; }
  29173. if (y1 === void 0) { y1 = 0; }
  29174. if (x2 === void 0) { x2 = 1; }
  29175. if (y2 === void 0) { y2 = 1; }
  29176. _super.call(this);
  29177. this.x1 = x1;
  29178. this.y1 = y1;
  29179. this.x2 = x2;
  29180. this.y2 = y2;
  29181. }
  29182. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29183. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29184. };
  29185. return BezierCurveEase;
  29186. }(EasingFunction));
  29187. BABYLON.BezierCurveEase = BezierCurveEase;
  29188. })(BABYLON || (BABYLON = {}));
  29189. var BABYLON;
  29190. (function (BABYLON) {
  29191. var Bone = (function (_super) {
  29192. __extends(Bone, _super);
  29193. function Bone(name, skeleton, parentBone, matrix, restPose) {
  29194. _super.call(this, name, skeleton.getScene());
  29195. this.name = name;
  29196. this.children = new Array();
  29197. this.animations = new Array();
  29198. this._worldTransform = new BABYLON.Matrix();
  29199. this._absoluteTransform = new BABYLON.Matrix();
  29200. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  29201. this._skeleton = skeleton;
  29202. this._matrix = matrix;
  29203. this._baseMatrix = matrix;
  29204. this._restPose = restPose ? restPose : matrix.clone();
  29205. skeleton.bones.push(this);
  29206. if (parentBone) {
  29207. this._parent = parentBone;
  29208. parentBone.children.push(this);
  29209. }
  29210. else {
  29211. this._parent = null;
  29212. }
  29213. this._updateDifferenceMatrix();
  29214. }
  29215. // Members
  29216. Bone.prototype.getParent = function () {
  29217. return this._parent;
  29218. };
  29219. Bone.prototype.getLocalMatrix = function () {
  29220. return this._matrix;
  29221. };
  29222. Bone.prototype.getBaseMatrix = function () {
  29223. return this._baseMatrix;
  29224. };
  29225. Bone.prototype.getRestPose = function () {
  29226. return this._restPose;
  29227. };
  29228. Bone.prototype.returnToRest = function () {
  29229. this.updateMatrix(this._restPose.clone());
  29230. };
  29231. Bone.prototype.getWorldMatrix = function () {
  29232. return this._worldTransform;
  29233. };
  29234. Bone.prototype.getInvertedAbsoluteTransform = function () {
  29235. return this._invertedAbsoluteTransform;
  29236. };
  29237. Bone.prototype.getAbsoluteTransform = function () {
  29238. return this._absoluteTransform;
  29239. };
  29240. // Methods
  29241. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  29242. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  29243. this._baseMatrix = matrix.clone();
  29244. this._matrix = matrix.clone();
  29245. this._skeleton._markAsDirty();
  29246. if (updateDifferenceMatrix) {
  29247. this._updateDifferenceMatrix();
  29248. }
  29249. };
  29250. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  29251. if (!rootMatrix) {
  29252. rootMatrix = this._baseMatrix;
  29253. }
  29254. if (this._parent) {
  29255. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29256. }
  29257. else {
  29258. this._absoluteTransform.copyFrom(rootMatrix);
  29259. }
  29260. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  29261. for (var index = 0; index < this.children.length; index++) {
  29262. this.children[index]._updateDifferenceMatrix();
  29263. }
  29264. };
  29265. Bone.prototype.markAsDirty = function () {
  29266. this._currentRenderId++;
  29267. this._skeleton._markAsDirty();
  29268. };
  29269. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  29270. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29271. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  29272. // all animation may be coming from a library skeleton, so may need to create animation
  29273. if (this.animations.length === 0) {
  29274. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  29275. this.animations[0].setKeys([]);
  29276. }
  29277. // get animation info / verify there is such a range from the source bone
  29278. var sourceRange = source.animations[0].getRange(rangeName);
  29279. if (!sourceRange) {
  29280. return false;
  29281. }
  29282. var from = sourceRange.from;
  29283. var to = sourceRange.to;
  29284. var sourceKeys = source.animations[0].getKeys();
  29285. // rescaling prep
  29286. var sourceBoneLength = source.length;
  29287. var sourceParent = source.getParent();
  29288. var parent = this.getParent();
  29289. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  29290. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  29291. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  29292. var destKeys = this.animations[0].getKeys();
  29293. // loop vars declaration
  29294. var orig;
  29295. var origTranslation;
  29296. var mat;
  29297. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  29298. orig = sourceKeys[key];
  29299. if (orig.frame >= from && orig.frame <= to) {
  29300. if (rescaleAsRequired) {
  29301. mat = orig.value.clone();
  29302. // scale based on parent ratio, when bone has parent
  29303. if (parentScalingReqd) {
  29304. origTranslation = mat.getTranslation();
  29305. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  29306. }
  29307. else if (dimensionsScalingReqd) {
  29308. origTranslation = mat.getTranslation();
  29309. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  29310. }
  29311. else {
  29312. mat = orig.value;
  29313. }
  29314. }
  29315. else {
  29316. mat = orig.value;
  29317. }
  29318. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  29319. }
  29320. }
  29321. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  29322. return true;
  29323. };
  29324. return Bone;
  29325. }(BABYLON.Node));
  29326. BABYLON.Bone = Bone;
  29327. })(BABYLON || (BABYLON = {}));
  29328. var BABYLON;
  29329. (function (BABYLON) {
  29330. var Skeleton = (function () {
  29331. function Skeleton(name, id, scene) {
  29332. this.name = name;
  29333. this.id = id;
  29334. this.bones = new Array();
  29335. this.needInitialSkinMatrix = false;
  29336. this._isDirty = true;
  29337. this._meshesWithPoseMatrix = new Array();
  29338. this._identity = BABYLON.Matrix.Identity();
  29339. this._ranges = {};
  29340. this.bones = [];
  29341. this._scene = scene;
  29342. scene.skeletons.push(this);
  29343. //make sure it will recalculate the matrix next time prepare is called.
  29344. this._isDirty = true;
  29345. }
  29346. // Members
  29347. Skeleton.prototype.getTransformMatrices = function (mesh) {
  29348. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  29349. return mesh._bonesTransformMatrices;
  29350. }
  29351. return this._transformMatrices;
  29352. };
  29353. Skeleton.prototype.getScene = function () {
  29354. return this._scene;
  29355. };
  29356. // Methods
  29357. /**
  29358. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29359. */
  29360. Skeleton.prototype.toString = function (fullDetails) {
  29361. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  29362. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29363. if (fullDetails) {
  29364. ret += ", Ranges: {";
  29365. var first = true;
  29366. for (var name_1 in this._ranges) {
  29367. if (first) {
  29368. ret += ", ";
  29369. first = false;
  29370. }
  29371. ret += name_1;
  29372. }
  29373. ret += "}";
  29374. }
  29375. return ret;
  29376. };
  29377. /**
  29378. * Get bone's index searching by name
  29379. * @param {string} name is bone's name to search for
  29380. * @return {number} Indice of the bone. Returns -1 if not found
  29381. */
  29382. Skeleton.prototype.getBoneIndexByName = function (name) {
  29383. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  29384. if (this.bones[boneIndex].name === name) {
  29385. return boneIndex;
  29386. }
  29387. }
  29388. return -1;
  29389. };
  29390. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  29391. // check name not already in use
  29392. if (!this._ranges[name]) {
  29393. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  29394. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29395. if (this.bones[i].animations[0]) {
  29396. this.bones[i].animations[0].createRange(name, from, to);
  29397. }
  29398. }
  29399. }
  29400. };
  29401. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  29402. if (deleteFrames === void 0) { deleteFrames = true; }
  29403. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29404. if (this.bones[i].animations[0]) {
  29405. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  29406. }
  29407. }
  29408. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29409. };
  29410. Skeleton.prototype.getAnimationRange = function (name) {
  29411. return this._ranges[name];
  29412. };
  29413. /**
  29414. * Returns as an Array, all AnimationRanges defined on this skeleton
  29415. */
  29416. Skeleton.prototype.getAnimationRanges = function () {
  29417. var animationRanges = [];
  29418. var name;
  29419. var i = 0;
  29420. for (name in this._ranges) {
  29421. animationRanges[i] = this._ranges[name];
  29422. i++;
  29423. }
  29424. return animationRanges;
  29425. };
  29426. /**
  29427. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  29428. */
  29429. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  29430. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29431. if (this._ranges[name] || !source.getAnimationRange(name)) {
  29432. return false;
  29433. }
  29434. var ret = true;
  29435. var frameOffset = this._getHighestAnimationFrame() + 1;
  29436. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  29437. var boneDict = {};
  29438. var sourceBones = source.bones;
  29439. var nBones;
  29440. var i;
  29441. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  29442. boneDict[sourceBones[i].name] = sourceBones[i];
  29443. }
  29444. if (this.bones.length !== sourceBones.length) {
  29445. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  29446. ret = false;
  29447. }
  29448. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  29449. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  29450. var boneName = this.bones[i].name;
  29451. var sourceBone = boneDict[boneName];
  29452. if (sourceBone) {
  29453. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  29454. }
  29455. else {
  29456. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  29457. ret = false;
  29458. }
  29459. }
  29460. // do not call createAnimationRange(), since it also is done to bones, which was already done
  29461. var range = source.getAnimationRange(name);
  29462. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  29463. return ret;
  29464. };
  29465. Skeleton.prototype.returnToRest = function () {
  29466. for (var index = 0; index < this.bones.length; index++) {
  29467. this.bones[index].returnToRest();
  29468. }
  29469. };
  29470. Skeleton.prototype._getHighestAnimationFrame = function () {
  29471. var ret = 0;
  29472. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29473. if (this.bones[i].animations[0]) {
  29474. var highest = this.bones[i].animations[0].getHighestFrame();
  29475. if (ret < highest) {
  29476. ret = highest;
  29477. }
  29478. }
  29479. }
  29480. return ret;
  29481. };
  29482. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  29483. var range = this.getAnimationRange(name);
  29484. if (!range) {
  29485. return null;
  29486. }
  29487. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  29488. };
  29489. Skeleton.prototype._markAsDirty = function () {
  29490. this._isDirty = true;
  29491. };
  29492. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  29493. this._meshesWithPoseMatrix.push(mesh);
  29494. };
  29495. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  29496. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  29497. if (index > -1) {
  29498. this._meshesWithPoseMatrix.splice(index, 1);
  29499. }
  29500. };
  29501. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  29502. for (var index = 0; index < this.bones.length; index++) {
  29503. var bone = this.bones[index];
  29504. var parentBone = bone.getParent();
  29505. if (parentBone) {
  29506. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  29507. }
  29508. else {
  29509. if (initialSkinMatrix) {
  29510. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  29511. }
  29512. else {
  29513. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  29514. }
  29515. }
  29516. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  29517. }
  29518. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  29519. };
  29520. Skeleton.prototype.prepare = function () {
  29521. if (!this._isDirty) {
  29522. return;
  29523. }
  29524. if (this.needInitialSkinMatrix) {
  29525. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  29526. var mesh = this._meshesWithPoseMatrix[index];
  29527. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  29528. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29529. }
  29530. var poseMatrix = mesh.getPoseMatrix();
  29531. // Prepare bones
  29532. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  29533. var bone = this.bones[boneIndex];
  29534. if (!bone.getParent()) {
  29535. var matrix = bone.getBaseMatrix();
  29536. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  29537. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  29538. }
  29539. }
  29540. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  29541. }
  29542. }
  29543. else {
  29544. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  29545. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29546. }
  29547. this._computeTransformMatrices(this._transformMatrices, null);
  29548. }
  29549. this._isDirty = false;
  29550. this._scene._activeBones.addCount(this.bones.length, false);
  29551. };
  29552. Skeleton.prototype.getAnimatables = function () {
  29553. if (!this._animatables || this._animatables.length !== this.bones.length) {
  29554. this._animatables = [];
  29555. for (var index = 0; index < this.bones.length; index++) {
  29556. this._animatables.push(this.bones[index]);
  29557. }
  29558. }
  29559. return this._animatables;
  29560. };
  29561. Skeleton.prototype.clone = function (name, id) {
  29562. var result = new Skeleton(name, id || name, this._scene);
  29563. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29564. for (var index = 0; index < this.bones.length; index++) {
  29565. var source = this.bones[index];
  29566. var parentBone = null;
  29567. if (source.getParent()) {
  29568. var parentIndex = this.bones.indexOf(source.getParent());
  29569. parentBone = result.bones[parentIndex];
  29570. }
  29571. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  29572. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  29573. }
  29574. if (this._ranges) {
  29575. result._ranges = {};
  29576. for (var rangeName in this._ranges) {
  29577. result._ranges[rangeName] = this._ranges[rangeName].clone();
  29578. }
  29579. }
  29580. this._isDirty = true;
  29581. return result;
  29582. };
  29583. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  29584. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  29585. this.bones.forEach(function (bone) {
  29586. bone.animations.forEach(function (animation) {
  29587. animation.enableBlending = true;
  29588. animation.blendingSpeed = blendingSpeed;
  29589. });
  29590. });
  29591. };
  29592. Skeleton.prototype.dispose = function () {
  29593. this._meshesWithPoseMatrix = [];
  29594. // Animations
  29595. this.getScene().stopAnimation(this);
  29596. // Remove from scene
  29597. this.getScene().removeSkeleton(this);
  29598. };
  29599. Skeleton.prototype.serialize = function () {
  29600. var serializationObject = {};
  29601. serializationObject.name = this.name;
  29602. serializationObject.id = this.id;
  29603. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  29604. serializationObject.bones = [];
  29605. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29606. for (var index = 0; index < this.bones.length; index++) {
  29607. var bone = this.bones[index];
  29608. var serializedBone = {
  29609. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  29610. name: bone.name,
  29611. matrix: bone.getLocalMatrix().toArray(),
  29612. rest: bone.getRestPose().toArray()
  29613. };
  29614. serializationObject.bones.push(serializedBone);
  29615. if (bone.length) {
  29616. serializedBone.length = bone.length;
  29617. }
  29618. if (bone.animations && bone.animations.length > 0) {
  29619. serializedBone.animation = bone.animations[0].serialize();
  29620. }
  29621. serializationObject.ranges = [];
  29622. for (var name in this._ranges) {
  29623. var range = {};
  29624. range.name = name;
  29625. range.from = this._ranges[name].from;
  29626. range.to = this._ranges[name].to;
  29627. serializationObject.ranges.push(range);
  29628. }
  29629. }
  29630. return serializationObject;
  29631. };
  29632. Skeleton.Parse = function (parsedSkeleton, scene) {
  29633. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  29634. if (parsedSkeleton.dimensionsAtRest) {
  29635. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  29636. }
  29637. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  29638. var index;
  29639. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  29640. var parsedBone = parsedSkeleton.bones[index];
  29641. var parentBone = null;
  29642. if (parsedBone.parentBoneIndex > -1) {
  29643. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  29644. }
  29645. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  29646. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  29647. if (parsedBone.length) {
  29648. bone.length = parsedBone.length;
  29649. }
  29650. if (parsedBone.animation) {
  29651. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  29652. }
  29653. }
  29654. // placed after bones, so createAnimationRange can cascade down
  29655. if (parsedSkeleton.ranges) {
  29656. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  29657. var data = parsedSkeleton.ranges[index];
  29658. skeleton.createAnimationRange(data.name, data.from, data.to);
  29659. }
  29660. }
  29661. return skeleton;
  29662. };
  29663. return Skeleton;
  29664. }());
  29665. BABYLON.Skeleton = Skeleton;
  29666. })(BABYLON || (BABYLON = {}));
  29667. var BABYLON;
  29668. (function (BABYLON) {
  29669. var PostProcess = (function () {
  29670. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  29671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  29672. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  29673. this.name = name;
  29674. this.width = -1;
  29675. this.height = -1;
  29676. /*
  29677. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  29678. Can only be used on a single postprocess or on the last one of a chain.
  29679. */
  29680. this.enablePixelPerfectMode = false;
  29681. this._reusable = false;
  29682. this._textures = new BABYLON.SmartArray(2);
  29683. this._currentRenderTextureInd = 0;
  29684. this._scaleRatio = new BABYLON.Vector2(1, 1);
  29685. // Events
  29686. /**
  29687. * An event triggered when the postprocess is activated.
  29688. * @type {BABYLON.Observable}
  29689. */
  29690. this.onActivateObservable = new BABYLON.Observable();
  29691. /**
  29692. * An event triggered when the postprocess changes its size.
  29693. * @type {BABYLON.Observable}
  29694. */
  29695. this.onSizeChangedObservable = new BABYLON.Observable();
  29696. /**
  29697. * An event triggered when the postprocess applies its effect.
  29698. * @type {BABYLON.Observable}
  29699. */
  29700. this.onApplyObservable = new BABYLON.Observable();
  29701. /**
  29702. * An event triggered before rendering the postprocess
  29703. * @type {BABYLON.Observable}
  29704. */
  29705. this.onBeforeRenderObservable = new BABYLON.Observable();
  29706. /**
  29707. * An event triggered after rendering the postprocess
  29708. * @type {BABYLON.Observable}
  29709. */
  29710. this.onAfterRenderObservable = new BABYLON.Observable();
  29711. if (camera != null) {
  29712. this._camera = camera;
  29713. this._scene = camera.getScene();
  29714. camera.attachPostProcess(this);
  29715. this._engine = this._scene.getEngine();
  29716. }
  29717. else {
  29718. this._engine = engine;
  29719. }
  29720. this._options = options;
  29721. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  29722. this._reusable = reusable || false;
  29723. this._textureType = textureType;
  29724. this._samplers = samplers || [];
  29725. this._samplers.push("textureSampler");
  29726. this._fragmentUrl = fragmentUrl;
  29727. this._parameters = parameters || [];
  29728. this._parameters.push("scale");
  29729. this.updateEffect(defines);
  29730. }
  29731. Object.defineProperty(PostProcess.prototype, "onActivate", {
  29732. set: function (callback) {
  29733. if (this._onActivateObserver) {
  29734. this.onActivateObservable.remove(this._onActivateObserver);
  29735. }
  29736. this._onActivateObserver = this.onActivateObservable.add(callback);
  29737. },
  29738. enumerable: true,
  29739. configurable: true
  29740. });
  29741. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  29742. set: function (callback) {
  29743. if (this._onSizeChangedObserver) {
  29744. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  29745. }
  29746. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  29747. },
  29748. enumerable: true,
  29749. configurable: true
  29750. });
  29751. Object.defineProperty(PostProcess.prototype, "onApply", {
  29752. set: function (callback) {
  29753. if (this._onApplyObserver) {
  29754. this.onApplyObservable.remove(this._onApplyObserver);
  29755. }
  29756. this._onApplyObserver = this.onApplyObservable.add(callback);
  29757. },
  29758. enumerable: true,
  29759. configurable: true
  29760. });
  29761. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  29762. set: function (callback) {
  29763. if (this._onBeforeRenderObserver) {
  29764. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29765. }
  29766. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29767. },
  29768. enumerable: true,
  29769. configurable: true
  29770. });
  29771. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  29772. set: function (callback) {
  29773. if (this._onAfterRenderObserver) {
  29774. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29775. }
  29776. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29777. },
  29778. enumerable: true,
  29779. configurable: true
  29780. });
  29781. PostProcess.prototype.updateEffect = function (defines) {
  29782. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  29783. };
  29784. PostProcess.prototype.isReusable = function () {
  29785. return this._reusable;
  29786. };
  29787. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  29788. PostProcess.prototype.markTextureDirty = function () {
  29789. this.width = -1;
  29790. };
  29791. PostProcess.prototype.activate = function (camera, sourceTexture) {
  29792. camera = camera || this._camera;
  29793. var scene = camera.getScene();
  29794. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  29795. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  29796. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  29797. var desiredWidth = this._options.width || requiredWidth;
  29798. var desiredHeight = this._options.height || requiredHeight;
  29799. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  29800. if (!this._options.width) {
  29801. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  29802. }
  29803. if (!this._options.height) {
  29804. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  29805. }
  29806. }
  29807. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  29808. if (this._textures.length > 0) {
  29809. for (var i = 0; i < this._textures.length; i++) {
  29810. this._engine._releaseTexture(this._textures.data[i]);
  29811. }
  29812. this._textures.reset();
  29813. }
  29814. this.width = desiredWidth;
  29815. this.height = desiredHeight;
  29816. var textureSize = { width: this.width, height: this.height };
  29817. var textureOptions = {
  29818. generateMipMaps: false,
  29819. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  29820. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  29821. samplingMode: this.renderTargetSamplingMode,
  29822. type: this._textureType
  29823. };
  29824. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29825. if (this._reusable) {
  29826. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29827. }
  29828. this.onSizeChangedObservable.notifyObservers(this);
  29829. }
  29830. if (this.enablePixelPerfectMode) {
  29831. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  29832. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  29833. }
  29834. else {
  29835. this._scaleRatio.copyFromFloats(1, 1);
  29836. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  29837. }
  29838. this.onActivateObservable.notifyObservers(camera);
  29839. // Clear
  29840. if (this.clearColor) {
  29841. this._engine.clear(this.clearColor, true, true, true);
  29842. }
  29843. else {
  29844. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  29845. }
  29846. if (this._reusable) {
  29847. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  29848. }
  29849. };
  29850. Object.defineProperty(PostProcess.prototype, "isSupported", {
  29851. get: function () {
  29852. return this._effect.isSupported;
  29853. },
  29854. enumerable: true,
  29855. configurable: true
  29856. });
  29857. PostProcess.prototype.apply = function () {
  29858. // Check
  29859. if (!this._effect.isReady())
  29860. return null;
  29861. // States
  29862. this._engine.enableEffect(this._effect);
  29863. this._engine.setState(false);
  29864. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29865. this._engine.setDepthBuffer(false);
  29866. this._engine.setDepthWrite(false);
  29867. // Texture
  29868. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  29869. // Parameters
  29870. this._effect.setVector2("scale", this._scaleRatio);
  29871. this.onApplyObservable.notifyObservers(this._effect);
  29872. return this._effect;
  29873. };
  29874. PostProcess.prototype.dispose = function (camera) {
  29875. camera = camera || this._camera;
  29876. if (this._textures.length > 0) {
  29877. for (var i = 0; i < this._textures.length; i++) {
  29878. this._engine._releaseTexture(this._textures.data[i]);
  29879. }
  29880. this._textures.reset();
  29881. }
  29882. if (!camera) {
  29883. return;
  29884. }
  29885. camera.detachPostProcess(this);
  29886. var index = camera._postProcesses.indexOf(this);
  29887. if (index === 0 && camera._postProcesses.length > 0) {
  29888. this._camera._postProcesses[0].markTextureDirty();
  29889. }
  29890. this.onActivateObservable.clear();
  29891. this.onAfterRenderObservable.clear();
  29892. this.onApplyObservable.clear();
  29893. this.onBeforeRenderObservable.clear();
  29894. this.onSizeChangedObservable.clear();
  29895. };
  29896. return PostProcess;
  29897. }());
  29898. BABYLON.PostProcess = PostProcess;
  29899. })(BABYLON || (BABYLON = {}));
  29900. var BABYLON;
  29901. (function (BABYLON) {
  29902. var PostProcessManager = (function () {
  29903. function PostProcessManager(scene) {
  29904. this._vertexBuffers = {};
  29905. this._scene = scene;
  29906. }
  29907. PostProcessManager.prototype._prepareBuffers = function () {
  29908. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29909. return;
  29910. }
  29911. // VBO
  29912. var vertices = [];
  29913. vertices.push(1, 1);
  29914. vertices.push(-1, 1);
  29915. vertices.push(-1, -1);
  29916. vertices.push(1, -1);
  29917. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29918. // Indices
  29919. var indices = [];
  29920. indices.push(0);
  29921. indices.push(1);
  29922. indices.push(2);
  29923. indices.push(0);
  29924. indices.push(2);
  29925. indices.push(3);
  29926. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29927. };
  29928. // Methods
  29929. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  29930. var postProcesses = this._scene.activeCamera._postProcesses;
  29931. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29932. return false;
  29933. }
  29934. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  29935. return true;
  29936. };
  29937. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29938. var engine = this._scene.getEngine();
  29939. for (var index = 0; index < postProcesses.length; index++) {
  29940. if (index < postProcesses.length - 1) {
  29941. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29942. }
  29943. else {
  29944. if (targetTexture) {
  29945. engine.bindFramebuffer(targetTexture);
  29946. }
  29947. else {
  29948. engine.restoreDefaultFramebuffer();
  29949. }
  29950. }
  29951. var pp = postProcesses[index];
  29952. var effect = pp.apply();
  29953. if (effect) {
  29954. pp.onBeforeRenderObservable.notifyObservers(effect);
  29955. // VBOs
  29956. this._prepareBuffers();
  29957. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29958. // Draw order
  29959. engine.draw(true, 0, 6);
  29960. pp.onAfterRenderObservable.notifyObservers(effect);
  29961. }
  29962. }
  29963. // Restore depth buffer
  29964. engine.setDepthBuffer(true);
  29965. engine.setDepthWrite(true);
  29966. };
  29967. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29968. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29969. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29970. return;
  29971. }
  29972. var engine = this._scene.getEngine();
  29973. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29974. if (index < len - 1) {
  29975. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29976. }
  29977. else {
  29978. if (targetTexture) {
  29979. engine.bindFramebuffer(targetTexture, faceIndex);
  29980. }
  29981. else {
  29982. engine.restoreDefaultFramebuffer();
  29983. }
  29984. }
  29985. if (doNotPresent) {
  29986. break;
  29987. }
  29988. var pp = postProcesses[index];
  29989. var effect = pp.apply();
  29990. if (effect) {
  29991. pp.onBeforeRenderObservable.notifyObservers(effect);
  29992. // VBOs
  29993. this._prepareBuffers();
  29994. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29995. // Draw order
  29996. engine.draw(true, 0, 6);
  29997. pp.onAfterRenderObservable.notifyObservers(effect);
  29998. }
  29999. }
  30000. // Restore depth buffer
  30001. engine.setDepthBuffer(true);
  30002. engine.setDepthWrite(true);
  30003. };
  30004. PostProcessManager.prototype.dispose = function () {
  30005. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30006. if (buffer) {
  30007. buffer.dispose();
  30008. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30009. }
  30010. if (this._indexBuffer) {
  30011. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30012. this._indexBuffer = null;
  30013. }
  30014. };
  30015. return PostProcessManager;
  30016. }());
  30017. BABYLON.PostProcessManager = PostProcessManager;
  30018. })(BABYLON || (BABYLON = {}));
  30019. var BABYLON;
  30020. (function (BABYLON) {
  30021. var PassPostProcess = (function (_super) {
  30022. __extends(PassPostProcess, _super);
  30023. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  30024. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  30025. }
  30026. return PassPostProcess;
  30027. }(BABYLON.PostProcess));
  30028. BABYLON.PassPostProcess = PassPostProcess;
  30029. })(BABYLON || (BABYLON = {}));
  30030. var BABYLON;
  30031. (function (BABYLON) {
  30032. /**
  30033. * This is a holder class for the physics joint created by the physics plugin.
  30034. * It holds a set of functions to control the underlying joint.
  30035. */
  30036. var PhysicsJoint = (function () {
  30037. function PhysicsJoint(type, jointData) {
  30038. this.type = type;
  30039. this.jointData = jointData;
  30040. jointData.nativeParams = jointData.nativeParams || {};
  30041. }
  30042. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  30043. get: function () {
  30044. return this._physicsJoint;
  30045. },
  30046. set: function (newJoint) {
  30047. if (this._physicsJoint) {
  30048. }
  30049. this._physicsJoint = newJoint;
  30050. },
  30051. enumerable: true,
  30052. configurable: true
  30053. });
  30054. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  30055. set: function (physicsPlugin) {
  30056. this._physicsPlugin = physicsPlugin;
  30057. },
  30058. enumerable: true,
  30059. configurable: true
  30060. });
  30061. /**
  30062. * Execute a function that is physics-plugin specific.
  30063. * @param {Function} func the function that will be executed.
  30064. * It accepts two parameters: the physics world and the physics joint.
  30065. */
  30066. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  30067. func(this._physicsPlugin.world, this._physicsJoint);
  30068. };
  30069. //TODO check if the native joints are the same
  30070. //Joint Types
  30071. PhysicsJoint.DistanceJoint = 0;
  30072. PhysicsJoint.HingeJoint = 1;
  30073. PhysicsJoint.BallAndSocketJoint = 2;
  30074. PhysicsJoint.WheelJoint = 3;
  30075. PhysicsJoint.SliderJoint = 4;
  30076. //OIMO
  30077. PhysicsJoint.PrismaticJoint = 5;
  30078. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  30079. PhysicsJoint.UniversalJoint = 6;
  30080. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  30081. //Cannon
  30082. //Similar to a Ball-Joint. Different in params
  30083. PhysicsJoint.PointToPointJoint = 8;
  30084. //Cannon only at the moment
  30085. PhysicsJoint.SpringJoint = 9;
  30086. PhysicsJoint.LockJoint = 10;
  30087. return PhysicsJoint;
  30088. }());
  30089. BABYLON.PhysicsJoint = PhysicsJoint;
  30090. /**
  30091. * A class representing a physics distance joint.
  30092. */
  30093. var DistanceJoint = (function (_super) {
  30094. __extends(DistanceJoint, _super);
  30095. function DistanceJoint(jointData) {
  30096. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  30097. }
  30098. /**
  30099. * Update the predefined distance.
  30100. */
  30101. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  30102. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  30103. };
  30104. return DistanceJoint;
  30105. }(PhysicsJoint));
  30106. BABYLON.DistanceJoint = DistanceJoint;
  30107. var MotorEnabledJoint = (function (_super) {
  30108. __extends(MotorEnabledJoint, _super);
  30109. function MotorEnabledJoint(type, jointData) {
  30110. _super.call(this, type, jointData);
  30111. }
  30112. /**
  30113. * Set the motor values.
  30114. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30115. * @param {number} force the force to apply
  30116. * @param {number} maxForce max force for this motor.
  30117. */
  30118. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  30119. this._physicsPlugin.setMotor(this, force, maxForce);
  30120. };
  30121. /**
  30122. * Set the motor's limits.
  30123. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30124. */
  30125. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30126. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30127. };
  30128. return MotorEnabledJoint;
  30129. }(PhysicsJoint));
  30130. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  30131. /**
  30132. * This class represents a single hinge physics joint
  30133. */
  30134. var HingeJoint = (function (_super) {
  30135. __extends(HingeJoint, _super);
  30136. function HingeJoint(jointData) {
  30137. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  30138. }
  30139. /**
  30140. * Set the motor values.
  30141. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30142. * @param {number} force the force to apply
  30143. * @param {number} maxForce max force for this motor.
  30144. */
  30145. HingeJoint.prototype.setMotor = function (force, maxForce) {
  30146. this._physicsPlugin.setMotor(this, force, maxForce);
  30147. };
  30148. /**
  30149. * Set the motor's limits.
  30150. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30151. */
  30152. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30153. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30154. };
  30155. return HingeJoint;
  30156. }(MotorEnabledJoint));
  30157. BABYLON.HingeJoint = HingeJoint;
  30158. /**
  30159. * This class represents a dual hinge physics joint (same as wheel joint)
  30160. */
  30161. var Hinge2Joint = (function (_super) {
  30162. __extends(Hinge2Joint, _super);
  30163. function Hinge2Joint(jointData) {
  30164. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  30165. }
  30166. /**
  30167. * Set the motor values.
  30168. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30169. * @param {number} force the force to apply
  30170. * @param {number} maxForce max force for this motor.
  30171. * @param {motorIndex} the motor's index, 0 or 1.
  30172. */
  30173. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  30174. if (motorIndex === void 0) { motorIndex = 0; }
  30175. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  30176. };
  30177. /**
  30178. * Set the motor limits.
  30179. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30180. * @param {number} upperLimit the upper limit
  30181. * @param {number} lowerLimit lower limit
  30182. * @param {motorIndex} the motor's index, 0 or 1.
  30183. */
  30184. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  30185. if (motorIndex === void 0) { motorIndex = 0; }
  30186. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  30187. };
  30188. return Hinge2Joint;
  30189. }(MotorEnabledJoint));
  30190. BABYLON.Hinge2Joint = Hinge2Joint;
  30191. })(BABYLON || (BABYLON = {}));
  30192. var BABYLON;
  30193. (function (BABYLON) {
  30194. var PhysicsImpostor = (function () {
  30195. function PhysicsImpostor(object, type, _options, _scene) {
  30196. var _this = this;
  30197. if (_options === void 0) { _options = { mass: 0 }; }
  30198. this.object = object;
  30199. this.type = type;
  30200. this._options = _options;
  30201. this._scene = _scene;
  30202. this._bodyUpdateRequired = false;
  30203. this._onBeforePhysicsStepCallbacks = new Array();
  30204. this._onAfterPhysicsStepCallbacks = new Array();
  30205. this._onPhysicsCollideCallbacks = [];
  30206. this._deltaPosition = BABYLON.Vector3.Zero();
  30207. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  30208. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  30209. /**
  30210. * this function is executed by the physics engine.
  30211. */
  30212. this.beforeStep = function () {
  30213. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  30214. //conjugate deltaRotation
  30215. if (_this._deltaRotationConjugated) {
  30216. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  30217. }
  30218. else {
  30219. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  30220. }
  30221. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  30222. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  30223. func(_this);
  30224. });
  30225. };
  30226. /**
  30227. * this function is executed by the physics engine.
  30228. */
  30229. this.afterStep = function () {
  30230. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  30231. func(_this);
  30232. });
  30233. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  30234. _this.object.position.addInPlace(_this._deltaPosition);
  30235. if (_this._deltaRotation) {
  30236. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  30237. }
  30238. };
  30239. //event and body object due to cannon's event-based architecture.
  30240. this.onCollide = function (e) {
  30241. if (!_this._onPhysicsCollideCallbacks.length)
  30242. return;
  30243. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  30244. if (otherImpostor) {
  30245. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  30246. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  30247. }).forEach(function (obj) {
  30248. obj.callback(_this, otherImpostor);
  30249. });
  30250. }
  30251. };
  30252. //sanity check!
  30253. if (!this.object) {
  30254. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  30255. return;
  30256. }
  30257. //legacy support for old syntax.
  30258. if (!this._scene && object.getScene) {
  30259. this._scene = object.getScene();
  30260. }
  30261. this._physicsEngine = this._scene.getPhysicsEngine();
  30262. if (!this._physicsEngine) {
  30263. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  30264. }
  30265. else {
  30266. //set the object's quaternion, if not set
  30267. if (!this.object.rotationQuaternion) {
  30268. if (this.object.rotation) {
  30269. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  30270. }
  30271. else {
  30272. this.object.rotationQuaternion = new BABYLON.Quaternion();
  30273. }
  30274. }
  30275. //default options params
  30276. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  30277. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  30278. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  30279. this._joints = [];
  30280. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  30281. if (!this.object.parent) {
  30282. this._init();
  30283. }
  30284. }
  30285. }
  30286. /**
  30287. * This function will completly initialize this impostor.
  30288. * It will create a new body - but only if this mesh has no parent.
  30289. * If it has, this impostor will not be used other than to define the impostor
  30290. * of the child mesh.
  30291. */
  30292. PhysicsImpostor.prototype._init = function () {
  30293. this._physicsEngine.removeImpostor(this);
  30294. this.physicsBody = null;
  30295. this._parent = this._parent || this._getPhysicsParent();
  30296. if (!this.parent) {
  30297. this._physicsEngine.addImpostor(this);
  30298. }
  30299. };
  30300. PhysicsImpostor.prototype._getPhysicsParent = function () {
  30301. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  30302. var parentMesh = this.object.parent;
  30303. return parentMesh.physicsImpostor;
  30304. }
  30305. return;
  30306. };
  30307. /**
  30308. * Should a new body be generated.
  30309. */
  30310. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  30311. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  30312. };
  30313. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  30314. this.forceUpdate();
  30315. };
  30316. /**
  30317. * Force a regeneration of this or the parent's impostor's body.
  30318. * Use under cautious - This will remove all joints already implemented.
  30319. */
  30320. PhysicsImpostor.prototype.forceUpdate = function () {
  30321. this._init();
  30322. if (this.parent) {
  30323. this.parent.forceUpdate();
  30324. }
  30325. };
  30326. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  30327. /*public get mesh(): AbstractMesh {
  30328. return this._mesh;
  30329. }*/
  30330. /**
  30331. * Gets the body that holds this impostor. Either its own, or its parent.
  30332. */
  30333. get: function () {
  30334. return this._parent ? this._parent.physicsBody : this._physicsBody;
  30335. },
  30336. /**
  30337. * Set the physics body. Used mainly by the physics engine/plugin
  30338. */
  30339. set: function (physicsBody) {
  30340. if (this._physicsBody) {
  30341. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  30342. }
  30343. this._physicsBody = physicsBody;
  30344. this.resetUpdateFlags();
  30345. },
  30346. enumerable: true,
  30347. configurable: true
  30348. });
  30349. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  30350. get: function () {
  30351. return this._parent;
  30352. },
  30353. set: function (value) {
  30354. this._parent = value;
  30355. },
  30356. enumerable: true,
  30357. configurable: true
  30358. });
  30359. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  30360. this._bodyUpdateRequired = false;
  30361. };
  30362. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  30363. if (this.object.getBoundingInfo) {
  30364. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  30365. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  30366. }
  30367. else {
  30368. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  30369. }
  30370. };
  30371. PhysicsImpostor.prototype.getObjectCenter = function () {
  30372. if (this.object.getBoundingInfo) {
  30373. return this.object.getBoundingInfo().boundingBox.center;
  30374. }
  30375. else {
  30376. return this.object.position;
  30377. }
  30378. };
  30379. /**
  30380. * Get a specific parametes from the options parameter.
  30381. */
  30382. PhysicsImpostor.prototype.getParam = function (paramName) {
  30383. return this._options[paramName];
  30384. };
  30385. /**
  30386. * Sets a specific parameter in the options given to the physics plugin
  30387. */
  30388. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  30389. this._options[paramName] = value;
  30390. this._bodyUpdateRequired = true;
  30391. };
  30392. /**
  30393. * Specifically change the body's mass option. Won't recreate the physics body object
  30394. */
  30395. PhysicsImpostor.prototype.setMass = function (mass) {
  30396. if (this.getParam("mass") !== mass) {
  30397. this.setParam("mass", mass);
  30398. }
  30399. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  30400. };
  30401. PhysicsImpostor.prototype.getLinearVelocity = function () {
  30402. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  30403. };
  30404. /**
  30405. * Set the body's linear velocity.
  30406. */
  30407. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  30408. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  30409. };
  30410. PhysicsImpostor.prototype.getAngularVelocity = function () {
  30411. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  30412. };
  30413. /**
  30414. * Set the body's linear velocity.
  30415. */
  30416. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  30417. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  30418. };
  30419. /**
  30420. * Execute a function with the physics plugin native code.
  30421. * Provide a function the will have two variables - the world object and the physics body object.
  30422. */
  30423. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  30424. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  30425. };
  30426. /**
  30427. * Register a function that will be executed before the physics world is stepping forward.
  30428. */
  30429. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  30430. this._onBeforePhysicsStepCallbacks.push(func);
  30431. };
  30432. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  30433. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  30434. if (index > -1) {
  30435. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  30436. }
  30437. else {
  30438. BABYLON.Tools.Warn("Function to remove was not found");
  30439. }
  30440. };
  30441. /**
  30442. * Register a function that will be executed after the physics step
  30443. */
  30444. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  30445. this._onAfterPhysicsStepCallbacks.push(func);
  30446. };
  30447. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  30448. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  30449. if (index > -1) {
  30450. this._onAfterPhysicsStepCallbacks.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 when this impostor collides against a different body.
  30458. */
  30459. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  30460. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30461. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  30462. };
  30463. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  30464. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30465. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  30466. if (index > -1) {
  30467. this._onPhysicsCollideCallbacks.splice(index, 1);
  30468. }
  30469. else {
  30470. BABYLON.Tools.Warn("Function to remove was not found");
  30471. }
  30472. };
  30473. /**
  30474. * Apply a force
  30475. */
  30476. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  30477. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  30478. };
  30479. /**
  30480. * Apply an impulse
  30481. */
  30482. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  30483. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  30484. };
  30485. /**
  30486. * A help function to create a joint.
  30487. */
  30488. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  30489. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  30490. this.addJoint(otherImpostor, joint);
  30491. };
  30492. /**
  30493. * Add a joint to this impostor with a different impostor.
  30494. */
  30495. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  30496. this._joints.push({
  30497. otherImpostor: otherImpostor,
  30498. joint: joint
  30499. });
  30500. this._physicsEngine.addJoint(this, otherImpostor, joint);
  30501. };
  30502. /**
  30503. * Will keep this body still, in a sleep mode.
  30504. */
  30505. PhysicsImpostor.prototype.sleep = function () {
  30506. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  30507. };
  30508. /**
  30509. * Wake the body up.
  30510. */
  30511. PhysicsImpostor.prototype.wakeUp = function () {
  30512. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  30513. };
  30514. PhysicsImpostor.prototype.clone = function (newObject) {
  30515. if (!newObject)
  30516. return null;
  30517. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  30518. };
  30519. PhysicsImpostor.prototype.dispose = function () {
  30520. var _this = this;
  30521. //no dispose if no physics engine is available.
  30522. if (!this._physicsEngine) {
  30523. return;
  30524. }
  30525. this._joints.forEach(function (j) {
  30526. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  30527. });
  30528. //dispose the physics body
  30529. this._physicsEngine.removeImpostor(this);
  30530. if (this.parent) {
  30531. this.parent.forceUpdate();
  30532. }
  30533. else {
  30534. }
  30535. };
  30536. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  30537. this._deltaPosition.copyFrom(position);
  30538. };
  30539. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  30540. if (!this._deltaRotation) {
  30541. this._deltaRotation = new BABYLON.Quaternion();
  30542. }
  30543. this._deltaRotation.copyFrom(rotation);
  30544. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  30545. };
  30546. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  30547. //Impostor types
  30548. PhysicsImpostor.NoImpostor = 0;
  30549. PhysicsImpostor.SphereImpostor = 1;
  30550. PhysicsImpostor.BoxImpostor = 2;
  30551. PhysicsImpostor.PlaneImpostor = 3;
  30552. PhysicsImpostor.MeshImpostor = 4;
  30553. PhysicsImpostor.CylinderImpostor = 7;
  30554. PhysicsImpostor.ParticleImpostor = 8;
  30555. PhysicsImpostor.HeightmapImpostor = 9;
  30556. return PhysicsImpostor;
  30557. }());
  30558. BABYLON.PhysicsImpostor = PhysicsImpostor;
  30559. })(BABYLON || (BABYLON = {}));
  30560. var BABYLON;
  30561. (function (BABYLON) {
  30562. var PhysicsEngine = (function () {
  30563. function PhysicsEngine(gravity, _physicsPlugin) {
  30564. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  30565. this._physicsPlugin = _physicsPlugin;
  30566. //new methods and parameters
  30567. this._impostors = [];
  30568. this._joints = [];
  30569. if (!this._physicsPlugin.isSupported()) {
  30570. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  30571. + "Please make sure it is included.");
  30572. }
  30573. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  30574. this.setGravity(gravity);
  30575. this.setTimeStep();
  30576. }
  30577. PhysicsEngine.prototype.setGravity = function (gravity) {
  30578. this.gravity = gravity;
  30579. this._physicsPlugin.setGravity(this.gravity);
  30580. };
  30581. /**
  30582. * Set the time step of the physics engine.
  30583. * default is 1/60.
  30584. * To slow it down, enter 1/600 for example.
  30585. * To speed it up, 1/30
  30586. * @param {number} newTimeStep the new timestep to apply to this world.
  30587. */
  30588. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  30589. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  30590. this._physicsPlugin.setTimeStep(newTimeStep);
  30591. };
  30592. PhysicsEngine.prototype.dispose = function () {
  30593. this._impostors.forEach(function (impostor) {
  30594. impostor.dispose();
  30595. });
  30596. this._physicsPlugin.dispose();
  30597. };
  30598. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  30599. return this._physicsPlugin.name;
  30600. };
  30601. /**
  30602. * Adding a new impostor for the impostor tracking.
  30603. * This will be done by the impostor itself.
  30604. * @param {PhysicsImpostor} impostor the impostor to add
  30605. */
  30606. PhysicsEngine.prototype.addImpostor = function (impostor) {
  30607. impostor.uniqueId = this._impostors.push(impostor);
  30608. //if no parent, generate the body
  30609. if (!impostor.parent) {
  30610. this._physicsPlugin.generatePhysicsBody(impostor);
  30611. }
  30612. };
  30613. /**
  30614. * Remove an impostor from the engine.
  30615. * This impostor and its mesh will not longer be updated by the physics engine.
  30616. * @param {PhysicsImpostor} impostor the impostor to remove
  30617. */
  30618. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  30619. var index = this._impostors.indexOf(impostor);
  30620. if (index > -1) {
  30621. var removed = this._impostors.splice(index, 1);
  30622. //Is it needed?
  30623. if (removed.length) {
  30624. //this will also remove it from the world.
  30625. removed[0].physicsBody = null;
  30626. }
  30627. }
  30628. };
  30629. /**
  30630. * Add a joint to the physics engine
  30631. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  30632. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  30633. * @param {PhysicsJoint} the joint that will connect both impostors.
  30634. */
  30635. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  30636. var impostorJoint = {
  30637. mainImpostor: mainImpostor,
  30638. connectedImpostor: connectedImpostor,
  30639. joint: joint
  30640. };
  30641. joint.physicsPlugin = this._physicsPlugin;
  30642. this._joints.push(impostorJoint);
  30643. this._physicsPlugin.generateJoint(impostorJoint);
  30644. };
  30645. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  30646. var matchingJoints = this._joints.filter(function (impostorJoint) {
  30647. return (impostorJoint.connectedImpostor === connectedImpostor
  30648. && impostorJoint.joint === joint
  30649. && impostorJoint.mainImpostor === mainImpostor);
  30650. });
  30651. if (matchingJoints.length) {
  30652. this._physicsPlugin.removeJoint(matchingJoints[0]);
  30653. }
  30654. };
  30655. /**
  30656. * Called by the scene. no need to call it.
  30657. */
  30658. PhysicsEngine.prototype._step = function (delta) {
  30659. var _this = this;
  30660. //check if any mesh has no body / requires an update
  30661. this._impostors.forEach(function (impostor) {
  30662. if (impostor.isBodyInitRequired()) {
  30663. _this._physicsPlugin.generatePhysicsBody(impostor);
  30664. }
  30665. });
  30666. if (delta > 0.1) {
  30667. delta = 0.1;
  30668. }
  30669. else if (delta <= 0) {
  30670. delta = 1.0 / 60.0;
  30671. }
  30672. this._physicsPlugin.executeStep(delta, this._impostors);
  30673. };
  30674. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  30675. return this._physicsPlugin;
  30676. };
  30677. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  30678. for (var i = 0; i < this._impostors.length; ++i) {
  30679. if (this._impostors[i].object === object) {
  30680. return this._impostors[i];
  30681. }
  30682. }
  30683. };
  30684. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  30685. for (var i = 0; i < this._impostors.length; ++i) {
  30686. if (this._impostors[i].physicsBody === body) {
  30687. return this._impostors[i];
  30688. }
  30689. }
  30690. };
  30691. // Statics, Legacy support.
  30692. /**
  30693. * @Deprecated
  30694. *
  30695. */
  30696. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  30697. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  30698. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  30699. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  30700. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  30701. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  30702. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  30703. PhysicsEngine.CapsuleImpostor = -1;
  30704. PhysicsEngine.ConeImpostor = -1;
  30705. PhysicsEngine.ConvexHullImpostor = -1;
  30706. PhysicsEngine.Epsilon = 0.001;
  30707. return PhysicsEngine;
  30708. }());
  30709. BABYLON.PhysicsEngine = PhysicsEngine;
  30710. })(BABYLON || (BABYLON = {}));
  30711. var BABYLON;
  30712. (function (BABYLON) {
  30713. var VertexData = (function () {
  30714. function VertexData() {
  30715. }
  30716. VertexData.prototype.set = function (data, kind) {
  30717. switch (kind) {
  30718. case BABYLON.VertexBuffer.PositionKind:
  30719. this.positions = data;
  30720. break;
  30721. case BABYLON.VertexBuffer.NormalKind:
  30722. this.normals = data;
  30723. break;
  30724. case BABYLON.VertexBuffer.UVKind:
  30725. this.uvs = data;
  30726. break;
  30727. case BABYLON.VertexBuffer.UV2Kind:
  30728. this.uvs2 = data;
  30729. break;
  30730. case BABYLON.VertexBuffer.UV3Kind:
  30731. this.uvs3 = data;
  30732. break;
  30733. case BABYLON.VertexBuffer.UV4Kind:
  30734. this.uvs4 = data;
  30735. break;
  30736. case BABYLON.VertexBuffer.UV5Kind:
  30737. this.uvs5 = data;
  30738. break;
  30739. case BABYLON.VertexBuffer.UV6Kind:
  30740. this.uvs6 = data;
  30741. break;
  30742. case BABYLON.VertexBuffer.ColorKind:
  30743. this.colors = data;
  30744. break;
  30745. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30746. this.matricesIndices = data;
  30747. break;
  30748. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30749. this.matricesWeights = data;
  30750. break;
  30751. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30752. this.matricesIndicesExtra = data;
  30753. break;
  30754. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30755. this.matricesWeightsExtra = data;
  30756. break;
  30757. }
  30758. };
  30759. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30760. this._applyTo(mesh, updatable);
  30761. };
  30762. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30763. this._applyTo(geometry, updatable);
  30764. };
  30765. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30766. this._update(mesh);
  30767. };
  30768. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30769. this._update(geometry);
  30770. };
  30771. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30772. if (this.positions) {
  30773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30774. }
  30775. if (this.normals) {
  30776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30777. }
  30778. if (this.uvs) {
  30779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30780. }
  30781. if (this.uvs2) {
  30782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30783. }
  30784. if (this.uvs3) {
  30785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30786. }
  30787. if (this.uvs4) {
  30788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30789. }
  30790. if (this.uvs5) {
  30791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30792. }
  30793. if (this.uvs6) {
  30794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30795. }
  30796. if (this.colors) {
  30797. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30798. }
  30799. if (this.matricesIndices) {
  30800. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30801. }
  30802. if (this.matricesWeights) {
  30803. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30804. }
  30805. if (this.matricesIndicesExtra) {
  30806. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30807. }
  30808. if (this.matricesWeightsExtra) {
  30809. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30810. }
  30811. if (this.indices) {
  30812. meshOrGeometry.setIndices(this.indices);
  30813. }
  30814. };
  30815. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30816. if (this.positions) {
  30817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30818. }
  30819. if (this.normals) {
  30820. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30821. }
  30822. if (this.uvs) {
  30823. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30824. }
  30825. if (this.uvs2) {
  30826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30827. }
  30828. if (this.uvs3) {
  30829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30830. }
  30831. if (this.uvs4) {
  30832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30833. }
  30834. if (this.uvs5) {
  30835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30836. }
  30837. if (this.uvs6) {
  30838. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30839. }
  30840. if (this.colors) {
  30841. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30842. }
  30843. if (this.matricesIndices) {
  30844. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30845. }
  30846. if (this.matricesWeights) {
  30847. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30848. }
  30849. if (this.matricesIndicesExtra) {
  30850. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30851. }
  30852. if (this.matricesWeightsExtra) {
  30853. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30854. }
  30855. if (this.indices) {
  30856. meshOrGeometry.setIndices(this.indices);
  30857. }
  30858. };
  30859. VertexData.prototype.transform = function (matrix) {
  30860. var transformed = BABYLON.Vector3.Zero();
  30861. var index;
  30862. if (this.positions) {
  30863. var position = BABYLON.Vector3.Zero();
  30864. for (index = 0; index < this.positions.length; index += 3) {
  30865. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30866. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30867. this.positions[index] = transformed.x;
  30868. this.positions[index + 1] = transformed.y;
  30869. this.positions[index + 2] = transformed.z;
  30870. }
  30871. }
  30872. if (this.normals) {
  30873. var normal = BABYLON.Vector3.Zero();
  30874. for (index = 0; index < this.normals.length; index += 3) {
  30875. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30876. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30877. this.normals[index] = transformed.x;
  30878. this.normals[index + 1] = transformed.y;
  30879. this.normals[index + 2] = transformed.z;
  30880. }
  30881. }
  30882. };
  30883. VertexData.prototype.merge = function (other) {
  30884. if (other.indices) {
  30885. if (!this.indices) {
  30886. this.indices = [];
  30887. }
  30888. var offset = this.positions ? this.positions.length / 3 : 0;
  30889. for (var index = 0; index < other.indices.length; index++) {
  30890. //TODO check type - if Int32Array!
  30891. this.indices.push(other.indices[index] + offset);
  30892. }
  30893. }
  30894. this.positions = this._mergeElement(this.positions, other.positions);
  30895. this.normals = this._mergeElement(this.normals, other.normals);
  30896. this.uvs = this._mergeElement(this.uvs, other.uvs);
  30897. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  30898. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  30899. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  30900. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  30901. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  30902. this.colors = this._mergeElement(this.colors, other.colors);
  30903. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  30904. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  30905. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  30906. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  30907. };
  30908. VertexData.prototype._mergeElement = function (source, other) {
  30909. if (!other)
  30910. return source;
  30911. if (!source)
  30912. return other;
  30913. var len = other.length + source.length;
  30914. var isSrcTypedArray = source instanceof Float32Array;
  30915. var isOthTypedArray = other instanceof Float32Array;
  30916. // use non-loop method when the source is Float32Array
  30917. if (isSrcTypedArray) {
  30918. var ret32 = new Float32Array(len);
  30919. ret32.set(source);
  30920. ret32.set(other, source.length);
  30921. return ret32;
  30922. }
  30923. else if (!isOthTypedArray) {
  30924. return source.concat(other);
  30925. }
  30926. else {
  30927. var ret = source.slice(0); // copy source to a separate array
  30928. for (var i = 0, len = other.length; i < len; i++) {
  30929. ret.push(other[i]);
  30930. }
  30931. return ret;
  30932. }
  30933. };
  30934. VertexData.prototype.serialize = function () {
  30935. var serializationObject = this.serialize();
  30936. if (this.positions) {
  30937. serializationObject.positions = this.positions;
  30938. }
  30939. if (this.normals) {
  30940. serializationObject.normals = this.normals;
  30941. }
  30942. if (this.uvs) {
  30943. serializationObject.uvs = this.uvs;
  30944. }
  30945. if (this.uvs2) {
  30946. serializationObject.uvs2 = this.uvs2;
  30947. }
  30948. if (this.uvs3) {
  30949. serializationObject.uvs3 = this.uvs3;
  30950. }
  30951. if (this.uvs4) {
  30952. serializationObject.uvs4 = this.uvs4;
  30953. }
  30954. if (this.uvs5) {
  30955. serializationObject.uvs5 = this.uvs5;
  30956. }
  30957. if (this.uvs6) {
  30958. serializationObject.uvs6 = this.uvs6;
  30959. }
  30960. if (this.colors) {
  30961. serializationObject.colors = this.colors;
  30962. }
  30963. if (this.matricesIndices) {
  30964. serializationObject.matricesIndices = this.matricesIndices;
  30965. serializationObject.matricesIndices._isExpanded = true;
  30966. }
  30967. if (this.matricesWeights) {
  30968. serializationObject.matricesWeights = this.matricesWeights;
  30969. }
  30970. if (this.matricesIndicesExtra) {
  30971. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30972. serializationObject.matricesIndicesExtra._isExpanded = true;
  30973. }
  30974. if (this.matricesWeightsExtra) {
  30975. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30976. }
  30977. serializationObject.indices = this.indices;
  30978. return serializationObject;
  30979. };
  30980. // Statics
  30981. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  30982. return VertexData._ExtractFrom(mesh, copyWhenShared);
  30983. };
  30984. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  30985. return VertexData._ExtractFrom(geometry, copyWhenShared);
  30986. };
  30987. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  30988. var result = new VertexData();
  30989. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30990. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  30991. }
  30992. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30993. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  30994. }
  30995. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30996. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  30997. }
  30998. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30999. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  31000. }
  31001. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31002. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  31003. }
  31004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31005. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  31006. }
  31007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31008. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  31009. }
  31010. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31011. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  31012. }
  31013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31014. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  31015. }
  31016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31017. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  31018. }
  31019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31020. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  31021. }
  31022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  31023. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  31024. }
  31025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  31026. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  31027. }
  31028. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  31029. return result;
  31030. };
  31031. VertexData.CreateRibbon = function (options) {
  31032. var pathArray = options.pathArray;
  31033. var closeArray = options.closeArray || false;
  31034. var closePath = options.closePath || false;
  31035. var invertUV = options.invertUV || false;
  31036. var defaultOffset = Math.floor(pathArray[0].length / 2);
  31037. var offset = options.offset || defaultOffset;
  31038. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  31039. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31040. var positions = [];
  31041. var indices = [];
  31042. var normals = [];
  31043. var uvs = [];
  31044. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  31045. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  31046. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  31047. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  31048. var minlg; // minimal length among all paths from pathArray
  31049. var lg = []; // array of path lengths : nb of vertex per path
  31050. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  31051. var p; // path iterator
  31052. var i; // point iterator
  31053. var j; // point iterator
  31054. // if single path in pathArray
  31055. if (pathArray.length < 2) {
  31056. var ar1 = [];
  31057. var ar2 = [];
  31058. for (i = 0; i < pathArray[0].length - offset; i++) {
  31059. ar1.push(pathArray[0][i]);
  31060. ar2.push(pathArray[0][i + offset]);
  31061. }
  31062. pathArray = [ar1, ar2];
  31063. }
  31064. // positions and horizontal distances (u)
  31065. var idc = 0;
  31066. var closePathCorr = (closePath) ? 1 : 0;
  31067. var path;
  31068. var l;
  31069. minlg = pathArray[0].length;
  31070. var vectlg;
  31071. var dist;
  31072. for (p = 0; p < pathArray.length; p++) {
  31073. uTotalDistance[p] = 0;
  31074. us[p] = [0];
  31075. path = pathArray[p];
  31076. l = path.length;
  31077. minlg = (minlg < l) ? minlg : l;
  31078. j = 0;
  31079. while (j < l) {
  31080. positions.push(path[j].x, path[j].y, path[j].z);
  31081. if (j > 0) {
  31082. vectlg = path[j].subtract(path[j - 1]).length();
  31083. dist = vectlg + uTotalDistance[p];
  31084. us[p].push(dist);
  31085. uTotalDistance[p] = dist;
  31086. }
  31087. j++;
  31088. }
  31089. if (closePath) {
  31090. j--;
  31091. positions.push(path[0].x, path[0].y, path[0].z);
  31092. vectlg = path[j].subtract(path[0]).length();
  31093. dist = vectlg + uTotalDistance[p];
  31094. us[p].push(dist);
  31095. uTotalDistance[p] = dist;
  31096. }
  31097. lg[p] = l + closePathCorr;
  31098. idx[p] = idc;
  31099. idc += (l + closePathCorr);
  31100. }
  31101. // vertical distances (v)
  31102. var path1;
  31103. var path2;
  31104. var vertex1;
  31105. var vertex2;
  31106. for (i = 0; i < minlg + closePathCorr; i++) {
  31107. vTotalDistance[i] = 0;
  31108. vs[i] = [0];
  31109. for (p = 0; p < pathArray.length - 1; p++) {
  31110. path1 = pathArray[p];
  31111. path2 = pathArray[p + 1];
  31112. if (i === minlg) {
  31113. vertex1 = path1[0];
  31114. vertex2 = path2[0];
  31115. }
  31116. else {
  31117. vertex1 = path1[i];
  31118. vertex2 = path2[i];
  31119. }
  31120. vectlg = vertex2.subtract(vertex1).length();
  31121. dist = vectlg + vTotalDistance[i];
  31122. vs[i].push(dist);
  31123. vTotalDistance[i] = dist;
  31124. }
  31125. if (closeArray) {
  31126. path1 = pathArray[p];
  31127. path2 = pathArray[0];
  31128. if (i === minlg) {
  31129. vertex2 = path2[0];
  31130. }
  31131. vectlg = vertex2.subtract(vertex1).length();
  31132. dist = vectlg + vTotalDistance[i];
  31133. vTotalDistance[i] = dist;
  31134. }
  31135. }
  31136. // uvs
  31137. var u;
  31138. var v;
  31139. for (p = 0; p < pathArray.length; p++) {
  31140. for (i = 0; i < minlg + closePathCorr; i++) {
  31141. u = us[p][i] / uTotalDistance[p];
  31142. v = vs[i][p] / vTotalDistance[i];
  31143. if (invertUV) {
  31144. uvs.push(v, u);
  31145. }
  31146. else {
  31147. uvs.push(u, v);
  31148. }
  31149. }
  31150. }
  31151. // indices
  31152. p = 0; // path index
  31153. var pi = 0; // positions array index
  31154. var l1 = lg[p] - 1; // path1 length
  31155. var l2 = lg[p + 1] - 1; // path2 length
  31156. var min = (l1 < l2) ? l1 : l2; // current path stop index
  31157. var shft = idx[1] - idx[0]; // shift
  31158. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  31159. while (pi <= min && p < path1nb) {
  31160. // 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
  31161. indices.push(pi, pi + shft, pi + 1);
  31162. indices.push(pi + shft + 1, pi + 1, pi + shft);
  31163. pi += 1;
  31164. if (pi === min) {
  31165. p++;
  31166. if (p === lg.length - 1) {
  31167. shft = idx[0] - idx[p];
  31168. l1 = lg[p] - 1;
  31169. l2 = lg[0] - 1;
  31170. }
  31171. else {
  31172. shft = idx[p + 1] - idx[p];
  31173. l1 = lg[p] - 1;
  31174. l2 = lg[p + 1] - 1;
  31175. }
  31176. pi = idx[p];
  31177. min = (l1 < l2) ? l1 + pi : l2 + pi;
  31178. }
  31179. }
  31180. // normals
  31181. VertexData.ComputeNormals(positions, indices, normals);
  31182. if (closePath) {
  31183. var indexFirst = 0;
  31184. var indexLast = 0;
  31185. for (p = 0; p < pathArray.length; p++) {
  31186. indexFirst = idx[p] * 3;
  31187. if (p + 1 < pathArray.length) {
  31188. indexLast = (idx[p + 1] - 1) * 3;
  31189. }
  31190. else {
  31191. indexLast = normals.length - 3;
  31192. }
  31193. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  31194. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  31195. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  31196. normals[indexLast] = normals[indexFirst];
  31197. normals[indexLast + 1] = normals[indexFirst + 1];
  31198. normals[indexLast + 2] = normals[indexFirst + 2];
  31199. }
  31200. }
  31201. // sides
  31202. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31203. // Result
  31204. var vertexData = new VertexData();
  31205. vertexData.indices = indices;
  31206. vertexData.positions = positions;
  31207. vertexData.normals = normals;
  31208. vertexData.uvs = uvs;
  31209. if (closePath) {
  31210. vertexData._idx = idx;
  31211. }
  31212. return vertexData;
  31213. };
  31214. VertexData.CreateBox = function (options) {
  31215. var normalsSource = [
  31216. new BABYLON.Vector3(0, 0, 1),
  31217. new BABYLON.Vector3(0, 0, -1),
  31218. new BABYLON.Vector3(1, 0, 0),
  31219. new BABYLON.Vector3(-1, 0, 0),
  31220. new BABYLON.Vector3(0, 1, 0),
  31221. new BABYLON.Vector3(0, -1, 0)
  31222. ];
  31223. var indices = [];
  31224. var positions = [];
  31225. var normals = [];
  31226. var uvs = [];
  31227. var width = options.width || options.size || 1;
  31228. var height = options.height || options.size || 1;
  31229. var depth = options.depth || options.size || 1;
  31230. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31231. var faceUV = options.faceUV || new Array(6);
  31232. var faceColors = options.faceColors;
  31233. var colors = [];
  31234. // default face colors and UV if undefined
  31235. for (var f = 0; f < 6; f++) {
  31236. if (faceUV[f] === undefined) {
  31237. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31238. }
  31239. if (faceColors && faceColors[f] === undefined) {
  31240. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31241. }
  31242. }
  31243. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31244. // Create each face in turn.
  31245. for (var index = 0; index < normalsSource.length; index++) {
  31246. var normal = normalsSource[index];
  31247. // Get two vectors perpendicular to the face normal and to each other.
  31248. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31249. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31250. // Six indices (two triangles) per face.
  31251. var verticesLength = positions.length / 3;
  31252. indices.push(verticesLength);
  31253. indices.push(verticesLength + 1);
  31254. indices.push(verticesLength + 2);
  31255. indices.push(verticesLength);
  31256. indices.push(verticesLength + 2);
  31257. indices.push(verticesLength + 3);
  31258. // Four vertices per face.
  31259. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31260. positions.push(vertex.x, vertex.y, vertex.z);
  31261. normals.push(normal.x, normal.y, normal.z);
  31262. uvs.push(faceUV[index].z, faceUV[index].w);
  31263. if (faceColors) {
  31264. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31265. }
  31266. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31267. positions.push(vertex.x, vertex.y, vertex.z);
  31268. normals.push(normal.x, normal.y, normal.z);
  31269. uvs.push(faceUV[index].x, faceUV[index].w);
  31270. if (faceColors) {
  31271. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31272. }
  31273. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31274. positions.push(vertex.x, vertex.y, vertex.z);
  31275. normals.push(normal.x, normal.y, normal.z);
  31276. uvs.push(faceUV[index].x, faceUV[index].y);
  31277. if (faceColors) {
  31278. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31279. }
  31280. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31281. positions.push(vertex.x, vertex.y, vertex.z);
  31282. normals.push(normal.x, normal.y, normal.z);
  31283. uvs.push(faceUV[index].z, faceUV[index].y);
  31284. if (faceColors) {
  31285. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31286. }
  31287. }
  31288. // sides
  31289. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31290. // Result
  31291. var vertexData = new VertexData();
  31292. vertexData.indices = indices;
  31293. vertexData.positions = positions;
  31294. vertexData.normals = normals;
  31295. vertexData.uvs = uvs;
  31296. if (faceColors) {
  31297. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31298. vertexData.colors = totalColors;
  31299. }
  31300. return vertexData;
  31301. };
  31302. VertexData.CreateSphere = function (options) {
  31303. var segments = options.segments || 32;
  31304. var diameterX = options.diameterX || options.diameter || 1;
  31305. var diameterY = options.diameterY || options.diameter || 1;
  31306. var diameterZ = options.diameterZ || options.diameter || 1;
  31307. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31308. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31309. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31310. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31311. var totalZRotationSteps = 2 + segments;
  31312. var totalYRotationSteps = 2 * totalZRotationSteps;
  31313. var indices = [];
  31314. var positions = [];
  31315. var normals = [];
  31316. var uvs = [];
  31317. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31318. var normalizedZ = zRotationStep / totalZRotationSteps;
  31319. var angleZ = normalizedZ * Math.PI * slice;
  31320. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31321. var normalizedY = yRotationStep / totalYRotationSteps;
  31322. var angleY = normalizedY * Math.PI * 2 * arc;
  31323. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31324. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31325. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31326. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31327. var vertex = complete.multiply(radius);
  31328. var normal = complete.divide(radius).normalize();
  31329. positions.push(vertex.x, vertex.y, vertex.z);
  31330. normals.push(normal.x, normal.y, normal.z);
  31331. uvs.push(normalizedY, normalizedZ);
  31332. }
  31333. if (zRotationStep > 0) {
  31334. var verticesCount = positions.length / 3;
  31335. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31336. indices.push((firstIndex));
  31337. indices.push((firstIndex + 1));
  31338. indices.push(firstIndex + totalYRotationSteps + 1);
  31339. indices.push((firstIndex + totalYRotationSteps + 1));
  31340. indices.push((firstIndex + 1));
  31341. indices.push((firstIndex + totalYRotationSteps + 2));
  31342. }
  31343. }
  31344. }
  31345. // Sides
  31346. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31347. // Result
  31348. var vertexData = new VertexData();
  31349. vertexData.indices = indices;
  31350. vertexData.positions = positions;
  31351. vertexData.normals = normals;
  31352. vertexData.uvs = uvs;
  31353. return vertexData;
  31354. };
  31355. // Cylinder and cone
  31356. VertexData.CreateCylinder = function (options) {
  31357. var height = options.height || 2;
  31358. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31359. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31360. var tessellation = options.tessellation || 24;
  31361. var subdivisions = options.subdivisions || 1;
  31362. var hasRings = options.hasRings;
  31363. var enclose = options.enclose;
  31364. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31365. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31366. var faceUV = options.faceUV || new Array(3);
  31367. var faceColors = options.faceColors;
  31368. // default face colors and UV if undefined
  31369. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31370. var ringNb = (hasRings) ? subdivisions : 1;
  31371. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31372. var f;
  31373. for (f = 0; f < surfaceNb; f++) {
  31374. if (faceColors && faceColors[f] === undefined) {
  31375. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31376. }
  31377. }
  31378. for (f = 0; f < surfaceNb; f++) {
  31379. if (faceUV && faceUV[f] === undefined) {
  31380. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31381. }
  31382. }
  31383. var indices = [];
  31384. var positions = [];
  31385. var normals = [];
  31386. var uvs = [];
  31387. var colors = [];
  31388. var angle_step = Math.PI * 2 * arc / tessellation;
  31389. var angle;
  31390. var h;
  31391. var radius;
  31392. var tan = (diameterBottom - diameterTop) / 2 / height;
  31393. var ringVertex = BABYLON.Vector3.Zero();
  31394. var ringNormal = BABYLON.Vector3.Zero();
  31395. var ringFirstVertex = BABYLON.Vector3.Zero();
  31396. var ringFirstNormal = BABYLON.Vector3.Zero();
  31397. var quadNormal = BABYLON.Vector3.Zero();
  31398. var Y = BABYLON.Axis.Y;
  31399. // positions, normals, uvs
  31400. var i;
  31401. var j;
  31402. var r;
  31403. var ringIdx = 1;
  31404. var s = 1; // surface index
  31405. var cs = 0;
  31406. var v = 0;
  31407. for (i = 0; i <= subdivisions; i++) {
  31408. h = i / subdivisions;
  31409. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31410. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31411. for (r = 0; r < ringIdx; r++) {
  31412. if (hasRings) {
  31413. s += r;
  31414. }
  31415. if (enclose) {
  31416. s += 2 * r;
  31417. }
  31418. for (j = 0; j <= tessellation; j++) {
  31419. angle = j * angle_step;
  31420. // position
  31421. ringVertex.x = Math.cos(-angle) * radius;
  31422. ringVertex.y = -height / 2 + h * height;
  31423. ringVertex.z = Math.sin(-angle) * radius;
  31424. // normal
  31425. if (diameterTop === 0 && i === subdivisions) {
  31426. // if no top cap, reuse former normals
  31427. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31428. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31429. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31430. }
  31431. else {
  31432. ringNormal.x = ringVertex.x;
  31433. ringNormal.z = ringVertex.z;
  31434. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31435. ringNormal.normalize();
  31436. }
  31437. // keep first ring vertex values for enclose
  31438. if (j === 0) {
  31439. ringFirstVertex.copyFrom(ringVertex);
  31440. ringFirstNormal.copyFrom(ringNormal);
  31441. }
  31442. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31443. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31444. if (hasRings) {
  31445. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31446. }
  31447. else {
  31448. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31449. }
  31450. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31451. if (faceColors) {
  31452. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31453. }
  31454. }
  31455. // if enclose, add four vertices and their dedicated normals
  31456. if (arc !== 1 && enclose) {
  31457. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31458. positions.push(0, ringVertex.y, 0);
  31459. positions.push(0, ringVertex.y, 0);
  31460. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31461. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31462. quadNormal.normalize();
  31463. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31464. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31465. quadNormal.normalize();
  31466. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31467. if (hasRings) {
  31468. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31469. }
  31470. else {
  31471. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31472. }
  31473. uvs.push(faceUV[s + 1].x, v);
  31474. uvs.push(faceUV[s + 1].z, v);
  31475. if (hasRings) {
  31476. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31477. }
  31478. else {
  31479. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31480. }
  31481. uvs.push(faceUV[s + 2].x, v);
  31482. uvs.push(faceUV[s + 2].z, v);
  31483. if (faceColors) {
  31484. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31485. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31486. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31487. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31488. }
  31489. }
  31490. if (cs !== s) {
  31491. cs = s;
  31492. }
  31493. }
  31494. }
  31495. // indices
  31496. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31497. var s;
  31498. i = 0;
  31499. for (s = 0; s < subdivisions; s++) {
  31500. for (j = 0; j < tessellation; j++) {
  31501. var i0 = i * (e + 1) + j;
  31502. var i1 = (i + 1) * (e + 1) + j;
  31503. var i2 = i * (e + 1) + (j + 1);
  31504. var i3 = (i + 1) * (e + 1) + (j + 1);
  31505. indices.push(i0, i1, i2);
  31506. indices.push(i3, i2, i1);
  31507. }
  31508. if (arc !== 1 && enclose) {
  31509. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31510. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31511. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31512. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31513. }
  31514. i = (hasRings) ? (i + 2) : (i + 1);
  31515. }
  31516. // Caps
  31517. var createCylinderCap = function (isTop) {
  31518. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31519. if (radius === 0) {
  31520. return;
  31521. }
  31522. // Cap positions, normals & uvs
  31523. var angle;
  31524. var circleVector;
  31525. var i;
  31526. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31527. var c;
  31528. if (faceColors) {
  31529. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31530. }
  31531. // cap center
  31532. var vbase = positions.length / 3;
  31533. var offset = isTop ? height / 2 : -height / 2;
  31534. var center = new BABYLON.Vector3(0, offset, 0);
  31535. positions.push(center.x, center.y, center.z);
  31536. normals.push(0, isTop ? 1 : -1, 0);
  31537. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31538. if (faceColors) {
  31539. colors.push(c.r, c.g, c.b, c.a);
  31540. }
  31541. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31542. for (i = 0; i <= tessellation; i++) {
  31543. angle = Math.PI * 2 * i * arc / tessellation;
  31544. var cos = Math.cos(-angle);
  31545. var sin = Math.sin(-angle);
  31546. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31547. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31548. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31549. normals.push(0, isTop ? 1 : -1, 0);
  31550. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31551. if (faceColors) {
  31552. colors.push(c.r, c.g, c.b, c.a);
  31553. }
  31554. }
  31555. // Cap indices
  31556. for (i = 0; i < tessellation; i++) {
  31557. if (!isTop) {
  31558. indices.push(vbase);
  31559. indices.push(vbase + (i + 1));
  31560. indices.push(vbase + (i + 2));
  31561. }
  31562. else {
  31563. indices.push(vbase);
  31564. indices.push(vbase + (i + 2));
  31565. indices.push(vbase + (i + 1));
  31566. }
  31567. }
  31568. };
  31569. // add caps to geometry
  31570. createCylinderCap(false);
  31571. createCylinderCap(true);
  31572. // Sides
  31573. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31574. var vertexData = new VertexData();
  31575. vertexData.indices = indices;
  31576. vertexData.positions = positions;
  31577. vertexData.normals = normals;
  31578. vertexData.uvs = uvs;
  31579. if (faceColors) {
  31580. vertexData.colors = colors;
  31581. }
  31582. return vertexData;
  31583. };
  31584. VertexData.CreateTorus = function (options) {
  31585. var indices = [];
  31586. var positions = [];
  31587. var normals = [];
  31588. var uvs = [];
  31589. var diameter = options.diameter || 1;
  31590. var thickness = options.thickness || 0.5;
  31591. var tessellation = options.tessellation || 16;
  31592. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31593. var stride = tessellation + 1;
  31594. for (var i = 0; i <= tessellation; i++) {
  31595. var u = i / tessellation;
  31596. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31597. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31598. for (var j = 0; j <= tessellation; j++) {
  31599. var v = 1 - j / tessellation;
  31600. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31601. var dx = Math.cos(innerAngle);
  31602. var dy = Math.sin(innerAngle);
  31603. // Create a vertex.
  31604. var normal = new BABYLON.Vector3(dx, dy, 0);
  31605. var position = normal.scale(thickness / 2);
  31606. var textureCoordinate = new BABYLON.Vector2(u, v);
  31607. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31608. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31609. positions.push(position.x, position.y, position.z);
  31610. normals.push(normal.x, normal.y, normal.z);
  31611. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31612. // And create indices for two triangles.
  31613. var nextI = (i + 1) % stride;
  31614. var nextJ = (j + 1) % stride;
  31615. indices.push(i * stride + j);
  31616. indices.push(i * stride + nextJ);
  31617. indices.push(nextI * stride + j);
  31618. indices.push(i * stride + nextJ);
  31619. indices.push(nextI * stride + nextJ);
  31620. indices.push(nextI * stride + j);
  31621. }
  31622. }
  31623. // Sides
  31624. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31625. // Result
  31626. var vertexData = new VertexData();
  31627. vertexData.indices = indices;
  31628. vertexData.positions = positions;
  31629. vertexData.normals = normals;
  31630. vertexData.uvs = uvs;
  31631. return vertexData;
  31632. };
  31633. VertexData.CreateLineSystem = function (options) {
  31634. var indices = [];
  31635. var positions = [];
  31636. var lines = options.lines;
  31637. var idx = 0;
  31638. for (var l = 0; l < lines.length; l++) {
  31639. var points = lines[l];
  31640. for (var index = 0; index < points.length; index++) {
  31641. positions.push(points[index].x, points[index].y, points[index].z);
  31642. if (index > 0) {
  31643. indices.push(idx - 1);
  31644. indices.push(idx);
  31645. }
  31646. idx++;
  31647. }
  31648. }
  31649. var vertexData = new VertexData();
  31650. vertexData.indices = indices;
  31651. vertexData.positions = positions;
  31652. return vertexData;
  31653. };
  31654. VertexData.CreateDashedLines = function (options) {
  31655. var dashSize = options.dashSize || 3;
  31656. var gapSize = options.gapSize || 1;
  31657. var dashNb = options.dashNb || 200;
  31658. var points = options.points;
  31659. var positions = new Array();
  31660. var indices = new Array();
  31661. var curvect = BABYLON.Vector3.Zero();
  31662. var lg = 0;
  31663. var nb = 0;
  31664. var shft = 0;
  31665. var dashshft = 0;
  31666. var curshft = 0;
  31667. var idx = 0;
  31668. var i = 0;
  31669. for (i = 0; i < points.length - 1; i++) {
  31670. points[i + 1].subtractToRef(points[i], curvect);
  31671. lg += curvect.length();
  31672. }
  31673. shft = lg / dashNb;
  31674. dashshft = dashSize * shft / (dashSize + gapSize);
  31675. for (i = 0; i < points.length - 1; i++) {
  31676. points[i + 1].subtractToRef(points[i], curvect);
  31677. nb = Math.floor(curvect.length() / shft);
  31678. curvect.normalize();
  31679. for (var j = 0; j < nb; j++) {
  31680. curshft = shft * j;
  31681. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31682. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31683. indices.push(idx, idx + 1);
  31684. idx += 2;
  31685. }
  31686. }
  31687. // Result
  31688. var vertexData = new VertexData();
  31689. vertexData.positions = positions;
  31690. vertexData.indices = indices;
  31691. return vertexData;
  31692. };
  31693. VertexData.CreateGround = function (options) {
  31694. var indices = [];
  31695. var positions = [];
  31696. var normals = [];
  31697. var uvs = [];
  31698. var row, col;
  31699. var width = options.width || 1;
  31700. var height = options.height || 1;
  31701. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31702. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31703. for (row = 0; row <= subdivisionsY; row++) {
  31704. for (col = 0; col <= subdivisionsX; col++) {
  31705. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31706. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31707. positions.push(position.x, position.y, position.z);
  31708. normals.push(normal.x, normal.y, normal.z);
  31709. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  31710. }
  31711. }
  31712. for (row = 0; row < subdivisionsY; row++) {
  31713. for (col = 0; col < subdivisionsX; col++) {
  31714. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31715. indices.push(col + 1 + row * (subdivisionsX + 1));
  31716. indices.push(col + row * (subdivisionsX + 1));
  31717. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31718. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31719. indices.push(col + row * (subdivisionsX + 1));
  31720. }
  31721. }
  31722. // Result
  31723. var vertexData = new VertexData();
  31724. vertexData.indices = indices;
  31725. vertexData.positions = positions;
  31726. vertexData.normals = normals;
  31727. vertexData.uvs = uvs;
  31728. return vertexData;
  31729. };
  31730. VertexData.CreateTiledGround = function (options) {
  31731. var xmin = options.xmin || -1.0;
  31732. var zmin = options.zmin || -1.0;
  31733. var xmax = options.xmax || 1.0;
  31734. var zmax = options.zmax || 1.0;
  31735. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31736. var precision = options.precision || { w: 1, h: 1 };
  31737. var indices = [];
  31738. var positions = [];
  31739. var normals = [];
  31740. var uvs = [];
  31741. var row, col, tileRow, tileCol;
  31742. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31743. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31744. precision.w = (precision.w < 1) ? 1 : precision.w;
  31745. precision.h = (precision.h < 1) ? 1 : precision.h;
  31746. var tileSize = {
  31747. 'w': (xmax - xmin) / subdivisions.w,
  31748. 'h': (zmax - zmin) / subdivisions.h
  31749. };
  31750. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31751. // Indices
  31752. var base = positions.length / 3;
  31753. var rowLength = precision.w + 1;
  31754. for (row = 0; row < precision.h; row++) {
  31755. for (col = 0; col < precision.w; col++) {
  31756. var square = [
  31757. base + col + row * rowLength,
  31758. base + (col + 1) + row * rowLength,
  31759. base + (col + 1) + (row + 1) * rowLength,
  31760. base + col + (row + 1) * rowLength
  31761. ];
  31762. indices.push(square[1]);
  31763. indices.push(square[2]);
  31764. indices.push(square[3]);
  31765. indices.push(square[0]);
  31766. indices.push(square[1]);
  31767. indices.push(square[3]);
  31768. }
  31769. }
  31770. // Position, normals and uvs
  31771. var position = BABYLON.Vector3.Zero();
  31772. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31773. for (row = 0; row <= precision.h; row++) {
  31774. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31775. for (col = 0; col <= precision.w; col++) {
  31776. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31777. position.y = 0;
  31778. positions.push(position.x, position.y, position.z);
  31779. normals.push(normal.x, normal.y, normal.z);
  31780. uvs.push(col / precision.w, row / precision.h);
  31781. }
  31782. }
  31783. }
  31784. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31785. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31786. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31787. }
  31788. }
  31789. // Result
  31790. var vertexData = new VertexData();
  31791. vertexData.indices = indices;
  31792. vertexData.positions = positions;
  31793. vertexData.normals = normals;
  31794. vertexData.uvs = uvs;
  31795. return vertexData;
  31796. };
  31797. VertexData.CreateGroundFromHeightMap = function (options) {
  31798. var indices = [];
  31799. var positions = [];
  31800. var normals = [];
  31801. var uvs = [];
  31802. var row, col;
  31803. // Vertices
  31804. for (row = 0; row <= options.subdivisions; row++) {
  31805. for (col = 0; col <= options.subdivisions; col++) {
  31806. 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));
  31807. // Compute height
  31808. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31809. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31810. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31811. var r = options.buffer[pos] / 255.0;
  31812. var g = options.buffer[pos + 1] / 255.0;
  31813. var b = options.buffer[pos + 2] / 255.0;
  31814. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31815. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31816. // Add vertex
  31817. positions.push(position.x, position.y, position.z);
  31818. normals.push(0, 0, 0);
  31819. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31820. }
  31821. }
  31822. // Indices
  31823. for (row = 0; row < options.subdivisions; row++) {
  31824. for (col = 0; col < options.subdivisions; col++) {
  31825. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31826. indices.push(col + 1 + row * (options.subdivisions + 1));
  31827. indices.push(col + row * (options.subdivisions + 1));
  31828. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31829. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31830. indices.push(col + row * (options.subdivisions + 1));
  31831. }
  31832. }
  31833. // Normals
  31834. VertexData.ComputeNormals(positions, indices, normals);
  31835. // Result
  31836. var vertexData = new VertexData();
  31837. vertexData.indices = indices;
  31838. vertexData.positions = positions;
  31839. vertexData.normals = normals;
  31840. vertexData.uvs = uvs;
  31841. return vertexData;
  31842. };
  31843. VertexData.CreatePlane = function (options) {
  31844. var indices = [];
  31845. var positions = [];
  31846. var normals = [];
  31847. var uvs = [];
  31848. var width = options.width || options.size || 1;
  31849. var height = options.height || options.size || 1;
  31850. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31851. // Vertices
  31852. var halfWidth = width / 2.0;
  31853. var halfHeight = height / 2.0;
  31854. positions.push(-halfWidth, -halfHeight, 0);
  31855. normals.push(0, 0, -1.0);
  31856. uvs.push(0.0, 0.0);
  31857. positions.push(halfWidth, -halfHeight, 0);
  31858. normals.push(0, 0, -1.0);
  31859. uvs.push(1.0, 0.0);
  31860. positions.push(halfWidth, halfHeight, 0);
  31861. normals.push(0, 0, -1.0);
  31862. uvs.push(1.0, 1.0);
  31863. positions.push(-halfWidth, halfHeight, 0);
  31864. normals.push(0, 0, -1.0);
  31865. uvs.push(0.0, 1.0);
  31866. // Indices
  31867. indices.push(0);
  31868. indices.push(1);
  31869. indices.push(2);
  31870. indices.push(0);
  31871. indices.push(2);
  31872. indices.push(3);
  31873. // Sides
  31874. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31875. // Result
  31876. var vertexData = new VertexData();
  31877. vertexData.indices = indices;
  31878. vertexData.positions = positions;
  31879. vertexData.normals = normals;
  31880. vertexData.uvs = uvs;
  31881. return vertexData;
  31882. };
  31883. VertexData.CreateDisc = function (options) {
  31884. var positions = [];
  31885. var indices = [];
  31886. var normals = [];
  31887. var uvs = [];
  31888. var radius = options.radius || 0.5;
  31889. var tessellation = options.tessellation || 64;
  31890. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31891. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31892. // positions and uvs
  31893. positions.push(0, 0, 0); // disc center first
  31894. uvs.push(0.5, 0.5);
  31895. var theta = Math.PI * 2 * arc;
  31896. var step = theta / tessellation;
  31897. for (var a = 0; a < theta; a += step) {
  31898. var x = Math.cos(a);
  31899. var y = Math.sin(a);
  31900. var u = (x + 1) / 2;
  31901. var v = (1 - y) / 2;
  31902. positions.push(radius * x, radius * y, 0);
  31903. uvs.push(u, v);
  31904. }
  31905. if (arc === 1) {
  31906. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31907. uvs.push(uvs[2], uvs[3]);
  31908. }
  31909. //indices
  31910. var vertexNb = positions.length / 3;
  31911. for (var i = 1; i < vertexNb - 1; i++) {
  31912. indices.push(i + 1, 0, i);
  31913. }
  31914. // result
  31915. VertexData.ComputeNormals(positions, indices, normals);
  31916. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31917. var vertexData = new VertexData();
  31918. vertexData.indices = indices;
  31919. vertexData.positions = positions;
  31920. vertexData.normals = normals;
  31921. vertexData.uvs = uvs;
  31922. return vertexData;
  31923. };
  31924. VertexData.CreateIcoSphere = function (options) {
  31925. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31926. var radius = options.radius || 1;
  31927. var flat = (options.flat === undefined) ? true : options.flat;
  31928. var subdivisions = options.subdivisions || 4;
  31929. var radiusX = options.radiusX || radius;
  31930. var radiusY = options.radiusY || radius;
  31931. var radiusZ = options.radiusZ || radius;
  31932. var t = (1 + Math.sqrt(5)) / 2;
  31933. // 12 vertex x,y,z
  31934. var ico_vertices = [
  31935. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31936. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31937. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31938. ];
  31939. // index of 3 vertex makes a face of icopshere
  31940. var ico_indices = [
  31941. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31942. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31943. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31944. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31945. ];
  31946. // vertex for uv have aliased position, not for UV
  31947. var vertices_unalias_id = [
  31948. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31949. // vertex alias
  31950. 0,
  31951. 2,
  31952. 3,
  31953. 3,
  31954. 3,
  31955. 4,
  31956. 7,
  31957. 8,
  31958. 9,
  31959. 9,
  31960. 10,
  31961. 11 // 23: B + 12
  31962. ];
  31963. // uv as integer step (not pixels !)
  31964. var ico_vertexuv = [
  31965. 5, 1, 3, 1, 6, 4, 0, 0,
  31966. 5, 3, 4, 2, 2, 2, 4, 0,
  31967. 2, 0, 1, 1, 6, 0, 6, 2,
  31968. // vertex alias (for same vertex on different faces)
  31969. 0, 4,
  31970. 3, 3,
  31971. 4, 4,
  31972. 3, 1,
  31973. 4, 2,
  31974. 4, 4,
  31975. 0, 2,
  31976. 1, 1,
  31977. 2, 2,
  31978. 3, 3,
  31979. 1, 3,
  31980. 2, 4 // 23: B + 12
  31981. ];
  31982. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31983. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31984. // First island of uv mapping
  31985. // v = 4h 3+ 2
  31986. // v = 3h 9+ 4
  31987. // v = 2h 9+ 5 B
  31988. // v = 1h 9 1 0
  31989. // v = 0h 3 8 7 A
  31990. // u = 0 1 2 3 4 5 6 *a
  31991. // Second island of uv mapping
  31992. // v = 4h 0+ B+ 4+
  31993. // v = 3h A+ 2+
  31994. // v = 2h 7+ 6 3+
  31995. // v = 1h 8+ 3+
  31996. // v = 0h
  31997. // u = 0 1 2 3 4 5 6 *a
  31998. // Face layout on texture UV mapping
  31999. // ============
  32000. // \ 4 /\ 16 / ======
  32001. // \ / \ / /\ 11 /
  32002. // \/ 7 \/ / \ /
  32003. // ======= / 10 \/
  32004. // /\ 17 /\ =======
  32005. // / \ / \ \ 15 /\
  32006. // / 8 \/ 12 \ \ / \
  32007. // ============ \/ 6 \
  32008. // \ 18 /\ ============
  32009. // \ / \ \ 5 /\ 0 /
  32010. // \/ 13 \ \ / \ /
  32011. // ======= \/ 1 \/
  32012. // =============
  32013. // /\ 19 /\ 2 /\
  32014. // / \ / \ / \
  32015. // / 14 \/ 9 \/ 3 \
  32016. // ===================
  32017. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  32018. var ustep = 138 / 1024;
  32019. var vstep = 239 / 1024;
  32020. var uoffset = 60 / 1024;
  32021. var voffset = 26 / 1024;
  32022. // Second island should have margin, not to touch the first island
  32023. // avoid any borderline artefact in pixel rounding
  32024. var island_u_offset = -40 / 1024;
  32025. var island_v_offset = +20 / 1024;
  32026. // face is either island 0 or 1 :
  32027. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  32028. var island = [
  32029. 0, 0, 0, 0, 1,
  32030. 0, 0, 1, 1, 0,
  32031. 0, 0, 1, 1, 0,
  32032. 0, 1, 1, 1, 0 // 15 - 19
  32033. ];
  32034. var indices = [];
  32035. var positions = [];
  32036. var normals = [];
  32037. var uvs = [];
  32038. var current_indice = 0;
  32039. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  32040. var face_vertex_pos = new Array(3);
  32041. var face_vertex_uv = new Array(3);
  32042. var v012;
  32043. for (v012 = 0; v012 < 3; v012++) {
  32044. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  32045. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  32046. }
  32047. // create all with normals
  32048. for (var face = 0; face < 20; face++) {
  32049. // 3 vertex per face
  32050. for (v012 = 0; v012 < 3; v012++) {
  32051. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  32052. var v_id = ico_indices[3 * face + v012];
  32053. // vertex have 3D position (x,y,z)
  32054. 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]);
  32055. // Normalize to get normal, then scale to radius
  32056. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  32057. // uv Coordinates from vertex ID
  32058. 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);
  32059. }
  32060. // Subdivide the face (interpolate pos, norm, uv)
  32061. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  32062. // - norm is linear interpolation of vertex corner normal
  32063. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  32064. // - uv is linear interpolation
  32065. //
  32066. // Topology is as below for sub-divide by 2
  32067. // vertex shown as v0,v1,v2
  32068. // interp index is i1 to progress in range [v0,v1[
  32069. // interp index is i2 to progress in range [v0,v2[
  32070. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  32071. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32072. //
  32073. //
  32074. // i2 v2
  32075. // ^ ^
  32076. // / / \
  32077. // / / \
  32078. // / / \
  32079. // / / (0,1) \
  32080. // / #---------\
  32081. // / / \ (0,0)'/ \
  32082. // / / \ / \
  32083. // / / \ / \
  32084. // / / (0,0) \ / (1,0) \
  32085. // / #---------#---------\
  32086. // v0 v1
  32087. //
  32088. // --------------------> i1
  32089. //
  32090. // interp of (i1,i2):
  32091. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32092. // along i1 : lerp(x0,x1, i1/(S-i2))
  32093. //
  32094. // centroid of triangle is needed to get help normal computation
  32095. // (c1,c2) are used for centroid location
  32096. var interp_vertex = function (i1, i2, c1, c2) {
  32097. // vertex is interpolated from
  32098. // - face_vertex_pos[0..2]
  32099. // - face_vertex_uv[0..2]
  32100. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32101. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32102. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32103. pos_interp.normalize();
  32104. var vertex_normal;
  32105. if (flat) {
  32106. // in flat mode, recalculate normal as face centroid normal
  32107. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32108. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32109. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32110. }
  32111. else {
  32112. // in smooth mode, recalculate normal from each single vertex position
  32113. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32114. }
  32115. // Vertex normal need correction due to X,Y,Z radius scaling
  32116. vertex_normal.x /= radiusX;
  32117. vertex_normal.y /= radiusY;
  32118. vertex_normal.z /= radiusZ;
  32119. vertex_normal.normalize();
  32120. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32121. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32122. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32123. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32124. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32125. uvs.push(uv_interp.x, uv_interp.y);
  32126. // push each vertex has member of a face
  32127. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32128. indices.push(current_indice);
  32129. current_indice++;
  32130. };
  32131. for (var i2 = 0; i2 < subdivisions; i2++) {
  32132. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32133. // face : (i1,i2) for /\ :
  32134. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32135. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32136. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32137. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32138. if (i1 + i2 + 1 < subdivisions) {
  32139. // face : (i1,i2)' for \/ :
  32140. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32141. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32142. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32143. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32144. }
  32145. }
  32146. }
  32147. }
  32148. // Sides
  32149. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32150. // Result
  32151. var vertexData = new VertexData();
  32152. vertexData.indices = indices;
  32153. vertexData.positions = positions;
  32154. vertexData.normals = normals;
  32155. vertexData.uvs = uvs;
  32156. return vertexData;
  32157. };
  32158. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32159. VertexData.CreatePolyhedron = function (options) {
  32160. // provided polyhedron types :
  32161. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32162. // 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)
  32163. var polyhedra = [];
  32164. 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]] };
  32165. 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]] };
  32166. polyhedra[2] = {
  32167. 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]],
  32168. 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]]
  32169. };
  32170. polyhedra[3] = {
  32171. 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]],
  32172. 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]]
  32173. };
  32174. polyhedra[4] = {
  32175. 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]],
  32176. 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]]
  32177. };
  32178. 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]] };
  32179. 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]] };
  32180. 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]] };
  32181. 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]] };
  32182. 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]] };
  32183. 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]] };
  32184. 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]] };
  32185. 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]] };
  32186. 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]] };
  32187. polyhedra[14] = {
  32188. 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]],
  32189. 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]]
  32190. };
  32191. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32192. var size = options.size;
  32193. var sizeX = options.sizeX || size || 1;
  32194. var sizeY = options.sizeY || size || 1;
  32195. var sizeZ = options.sizeZ || size || 1;
  32196. var data = options.custom || polyhedra[type];
  32197. var nbfaces = data.face.length;
  32198. var faceUV = options.faceUV || new Array(nbfaces);
  32199. var faceColors = options.faceColors;
  32200. var flat = (options.flat === undefined) ? true : options.flat;
  32201. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32202. var positions = [];
  32203. var indices = [];
  32204. var normals = [];
  32205. var uvs = [];
  32206. var colors = [];
  32207. var index = 0;
  32208. var faceIdx = 0; // face cursor in the array "indexes"
  32209. var indexes = [];
  32210. var i = 0;
  32211. var f = 0;
  32212. var u, v, ang, x, y, tmp;
  32213. // default face colors and UV if undefined
  32214. if (flat) {
  32215. for (f = 0; f < nbfaces; f++) {
  32216. if (faceColors && faceColors[f] === undefined) {
  32217. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32218. }
  32219. if (faceUV && faceUV[f] === undefined) {
  32220. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32221. }
  32222. }
  32223. }
  32224. if (!flat) {
  32225. for (i = 0; i < data.vertex.length; i++) {
  32226. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32227. uvs.push(0, 0);
  32228. }
  32229. for (f = 0; f < nbfaces; f++) {
  32230. for (i = 0; i < data.face[f].length - 2; i++) {
  32231. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32232. }
  32233. }
  32234. }
  32235. else {
  32236. for (f = 0; f < nbfaces; f++) {
  32237. var fl = data.face[f].length; // number of vertices of the current face
  32238. ang = 2 * Math.PI / fl;
  32239. x = 0.5 * Math.tan(ang / 2);
  32240. y = 0.5;
  32241. // positions, uvs, colors
  32242. for (i = 0; i < fl; i++) {
  32243. // positions
  32244. 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);
  32245. indexes.push(index);
  32246. index++;
  32247. // uvs
  32248. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32249. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32250. uvs.push(u, v);
  32251. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32252. y = x * Math.sin(ang) + y * Math.cos(ang);
  32253. x = tmp;
  32254. // colors
  32255. if (faceColors) {
  32256. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32257. }
  32258. }
  32259. // indices from indexes
  32260. for (i = 0; i < fl - 2; i++) {
  32261. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32262. }
  32263. faceIdx += fl;
  32264. }
  32265. }
  32266. VertexData.ComputeNormals(positions, indices, normals);
  32267. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32268. var vertexData = new VertexData();
  32269. vertexData.positions = positions;
  32270. vertexData.indices = indices;
  32271. vertexData.normals = normals;
  32272. vertexData.uvs = uvs;
  32273. if (faceColors && flat) {
  32274. vertexData.colors = colors;
  32275. }
  32276. return vertexData;
  32277. };
  32278. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32279. VertexData.CreateTorusKnot = function (options) {
  32280. var indices = [];
  32281. var positions = [];
  32282. var normals = [];
  32283. var uvs = [];
  32284. var radius = options.radius || 2;
  32285. var tube = options.tube || 0.5;
  32286. var radialSegments = options.radialSegments || 32;
  32287. var tubularSegments = options.tubularSegments || 32;
  32288. var p = options.p || 2;
  32289. var q = options.q || 3;
  32290. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32291. // Helper
  32292. var getPos = function (angle) {
  32293. var cu = Math.cos(angle);
  32294. var su = Math.sin(angle);
  32295. var quOverP = q / p * angle;
  32296. var cs = Math.cos(quOverP);
  32297. var tx = radius * (2 + cs) * 0.5 * cu;
  32298. var ty = radius * (2 + cs) * su * 0.5;
  32299. var tz = radius * Math.sin(quOverP) * 0.5;
  32300. return new BABYLON.Vector3(tx, ty, tz);
  32301. };
  32302. // Vertices
  32303. var i;
  32304. var j;
  32305. for (i = 0; i <= radialSegments; i++) {
  32306. var modI = i % radialSegments;
  32307. var u = modI / radialSegments * 2 * p * Math.PI;
  32308. var p1 = getPos(u);
  32309. var p2 = getPos(u + 0.01);
  32310. var tang = p2.subtract(p1);
  32311. var n = p2.add(p1);
  32312. var bitan = BABYLON.Vector3.Cross(tang, n);
  32313. n = BABYLON.Vector3.Cross(bitan, tang);
  32314. bitan.normalize();
  32315. n.normalize();
  32316. for (j = 0; j < tubularSegments; j++) {
  32317. var modJ = j % tubularSegments;
  32318. var v = modJ / tubularSegments * 2 * Math.PI;
  32319. var cx = -tube * Math.cos(v);
  32320. var cy = tube * Math.sin(v);
  32321. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32322. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32323. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32324. uvs.push(i / radialSegments);
  32325. uvs.push(j / tubularSegments);
  32326. }
  32327. }
  32328. for (i = 0; i < radialSegments; i++) {
  32329. for (j = 0; j < tubularSegments; j++) {
  32330. var jNext = (j + 1) % tubularSegments;
  32331. var a = i * tubularSegments + j;
  32332. var b = (i + 1) * tubularSegments + j;
  32333. var c = (i + 1) * tubularSegments + jNext;
  32334. var d = i * tubularSegments + jNext;
  32335. indices.push(d);
  32336. indices.push(b);
  32337. indices.push(a);
  32338. indices.push(d);
  32339. indices.push(c);
  32340. indices.push(b);
  32341. }
  32342. }
  32343. // Normals
  32344. VertexData.ComputeNormals(positions, indices, normals);
  32345. // Sides
  32346. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32347. // Result
  32348. var vertexData = new VertexData();
  32349. vertexData.indices = indices;
  32350. vertexData.positions = positions;
  32351. vertexData.normals = normals;
  32352. vertexData.uvs = uvs;
  32353. return vertexData;
  32354. };
  32355. // Tools
  32356. /**
  32357. * @param {any} - positions (number[] or Float32Array)
  32358. * @param {any} - indices (number[] or Uint16Array)
  32359. * @param {any} - normals (number[] or Float32Array)
  32360. */
  32361. VertexData.ComputeNormals = function (positions, indices, normals) {
  32362. var index = 0;
  32363. var p1p2x = 0.0;
  32364. var p1p2y = 0.0;
  32365. var p1p2z = 0.0;
  32366. var p3p2x = 0.0;
  32367. var p3p2y = 0.0;
  32368. var p3p2z = 0.0;
  32369. var faceNormalx = 0.0;
  32370. var faceNormaly = 0.0;
  32371. var faceNormalz = 0.0;
  32372. var length = 0.0;
  32373. var i1 = 0;
  32374. var i2 = 0;
  32375. var i3 = 0;
  32376. for (index = 0; index < positions.length; index++) {
  32377. normals[index] = 0.0;
  32378. }
  32379. // indice triplet = 1 face
  32380. var nbFaces = indices.length / 3;
  32381. for (index = 0; index < nbFaces; index++) {
  32382. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  32383. i2 = indices[index * 3 + 1];
  32384. i3 = indices[index * 3 + 2];
  32385. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  32386. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  32387. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  32388. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  32389. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  32390. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  32391. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  32392. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  32393. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  32394. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32395. length = (length === 0) ? 1.0 : length;
  32396. faceNormalx /= length; // normalize this normal
  32397. faceNormaly /= length;
  32398. faceNormalz /= length;
  32399. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  32400. normals[i1 * 3 + 1] += faceNormaly;
  32401. normals[i1 * 3 + 2] += faceNormalz;
  32402. normals[i2 * 3] += faceNormalx;
  32403. normals[i2 * 3 + 1] += faceNormaly;
  32404. normals[i2 * 3 + 2] += faceNormalz;
  32405. normals[i3 * 3] += faceNormalx;
  32406. normals[i3 * 3 + 1] += faceNormaly;
  32407. normals[i3 * 3 + 2] += faceNormalz;
  32408. }
  32409. // last normalization of each normal
  32410. for (index = 0; index < normals.length / 3; index++) {
  32411. faceNormalx = normals[index * 3];
  32412. faceNormaly = normals[index * 3 + 1];
  32413. faceNormalz = normals[index * 3 + 2];
  32414. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32415. length = (length === 0) ? 1.0 : length;
  32416. faceNormalx /= length;
  32417. faceNormaly /= length;
  32418. faceNormalz /= length;
  32419. normals[index * 3] = faceNormalx;
  32420. normals[index * 3 + 1] = faceNormaly;
  32421. normals[index * 3 + 2] = faceNormalz;
  32422. }
  32423. };
  32424. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  32425. var li = indices.length;
  32426. var ln = normals.length;
  32427. var i;
  32428. var n;
  32429. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32430. switch (sideOrientation) {
  32431. case BABYLON.Mesh.FRONTSIDE:
  32432. // nothing changed
  32433. break;
  32434. case BABYLON.Mesh.BACKSIDE:
  32435. var tmp;
  32436. // indices
  32437. for (i = 0; i < li; i += 3) {
  32438. tmp = indices[i];
  32439. indices[i] = indices[i + 2];
  32440. indices[i + 2] = tmp;
  32441. }
  32442. // normals
  32443. for (n = 0; n < ln; n++) {
  32444. normals[n] = -normals[n];
  32445. }
  32446. break;
  32447. case BABYLON.Mesh.DOUBLESIDE:
  32448. // positions
  32449. var lp = positions.length;
  32450. var l = lp / 3;
  32451. for (var p = 0; p < lp; p++) {
  32452. positions[lp + p] = positions[p];
  32453. }
  32454. // indices
  32455. for (i = 0; i < li; i += 3) {
  32456. indices[i + li] = indices[i + 2] + l;
  32457. indices[i + 1 + li] = indices[i + 1] + l;
  32458. indices[i + 2 + li] = indices[i] + l;
  32459. }
  32460. // normals
  32461. for (n = 0; n < ln; n++) {
  32462. normals[ln + n] = -normals[n];
  32463. }
  32464. // uvs
  32465. var lu = uvs.length;
  32466. for (var u = 0; u < lu; u++) {
  32467. uvs[u + lu] = uvs[u];
  32468. }
  32469. break;
  32470. }
  32471. };
  32472. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32473. var vertexData = new VertexData();
  32474. // positions
  32475. var positions = parsedVertexData.positions;
  32476. if (positions) {
  32477. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32478. }
  32479. // normals
  32480. var normals = parsedVertexData.normals;
  32481. if (normals) {
  32482. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32483. }
  32484. // uvs
  32485. var uvs = parsedVertexData.uvs;
  32486. if (uvs) {
  32487. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32488. }
  32489. // uv2s
  32490. var uv2s = parsedVertexData.uv2s;
  32491. if (uv2s) {
  32492. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32493. }
  32494. // uv3s
  32495. var uv3s = parsedVertexData.uv3s;
  32496. if (uv3s) {
  32497. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32498. }
  32499. // uv4s
  32500. var uv4s = parsedVertexData.uv4s;
  32501. if (uv4s) {
  32502. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32503. }
  32504. // uv5s
  32505. var uv5s = parsedVertexData.uv5s;
  32506. if (uv5s) {
  32507. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32508. }
  32509. // uv6s
  32510. var uv6s = parsedVertexData.uv6s;
  32511. if (uv6s) {
  32512. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32513. }
  32514. // colors
  32515. var colors = parsedVertexData.colors;
  32516. if (colors) {
  32517. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32518. }
  32519. // matricesIndices
  32520. var matricesIndices = parsedVertexData.matricesIndices;
  32521. if (matricesIndices) {
  32522. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32523. }
  32524. // matricesWeights
  32525. var matricesWeights = parsedVertexData.matricesWeights;
  32526. if (matricesWeights) {
  32527. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32528. }
  32529. // indices
  32530. var indices = parsedVertexData.indices;
  32531. if (indices) {
  32532. vertexData.indices = indices;
  32533. }
  32534. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32535. };
  32536. return VertexData;
  32537. }());
  32538. BABYLON.VertexData = VertexData;
  32539. })(BABYLON || (BABYLON = {}));
  32540. var BABYLON;
  32541. (function (BABYLON) {
  32542. var Tags = (function () {
  32543. function Tags() {
  32544. }
  32545. Tags.EnableFor = function (obj) {
  32546. obj._tags = obj._tags || {};
  32547. obj.hasTags = function () {
  32548. return Tags.HasTags(obj);
  32549. };
  32550. obj.addTags = function (tagsString) {
  32551. return Tags.AddTagsTo(obj, tagsString);
  32552. };
  32553. obj.removeTags = function (tagsString) {
  32554. return Tags.RemoveTagsFrom(obj, tagsString);
  32555. };
  32556. obj.matchesTagsQuery = function (tagsQuery) {
  32557. return Tags.MatchesQuery(obj, tagsQuery);
  32558. };
  32559. };
  32560. Tags.DisableFor = function (obj) {
  32561. delete obj._tags;
  32562. delete obj.hasTags;
  32563. delete obj.addTags;
  32564. delete obj.removeTags;
  32565. delete obj.matchesTagsQuery;
  32566. };
  32567. Tags.HasTags = function (obj) {
  32568. if (!obj._tags) {
  32569. return false;
  32570. }
  32571. return !BABYLON.Tools.IsEmpty(obj._tags);
  32572. };
  32573. Tags.GetTags = function (obj, asString) {
  32574. if (asString === void 0) { asString = true; }
  32575. if (!obj._tags) {
  32576. return null;
  32577. }
  32578. if (asString) {
  32579. var tagsArray = [];
  32580. for (var tag in obj._tags) {
  32581. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  32582. tagsArray.push(tag);
  32583. }
  32584. }
  32585. return tagsArray.join(" ");
  32586. }
  32587. else {
  32588. return obj._tags;
  32589. }
  32590. };
  32591. // the tags 'true' and 'false' are reserved and cannot be used as tags
  32592. // a tag cannot start with '||', '&&', and '!'
  32593. // it cannot contain whitespaces
  32594. Tags.AddTagsTo = function (obj, tagsString) {
  32595. if (!tagsString) {
  32596. return;
  32597. }
  32598. if (typeof tagsString !== "string") {
  32599. return;
  32600. }
  32601. var tags = tagsString.split(" ");
  32602. tags.forEach(function (tag, index, array) {
  32603. Tags._AddTagTo(obj, tag);
  32604. });
  32605. };
  32606. Tags._AddTagTo = function (obj, tag) {
  32607. tag = tag.trim();
  32608. if (tag === "" || tag === "true" || tag === "false") {
  32609. return;
  32610. }
  32611. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  32612. return;
  32613. }
  32614. Tags.EnableFor(obj);
  32615. obj._tags[tag] = true;
  32616. };
  32617. Tags.RemoveTagsFrom = function (obj, tagsString) {
  32618. if (!Tags.HasTags(obj)) {
  32619. return;
  32620. }
  32621. var tags = tagsString.split(" ");
  32622. for (var t in tags) {
  32623. Tags._RemoveTagFrom(obj, tags[t]);
  32624. }
  32625. };
  32626. Tags._RemoveTagFrom = function (obj, tag) {
  32627. delete obj._tags[tag];
  32628. };
  32629. Tags.MatchesQuery = function (obj, tagsQuery) {
  32630. if (tagsQuery === undefined) {
  32631. return true;
  32632. }
  32633. if (tagsQuery === "") {
  32634. return Tags.HasTags(obj);
  32635. }
  32636. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  32637. };
  32638. return Tags;
  32639. }());
  32640. BABYLON.Tags = Tags;
  32641. })(BABYLON || (BABYLON = {}));
  32642. var BABYLON;
  32643. (function (BABYLON) {
  32644. var Internals;
  32645. (function (Internals) {
  32646. var AndOrNotEvaluator = (function () {
  32647. function AndOrNotEvaluator() {
  32648. }
  32649. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  32650. if (!query.match(/\([^\(\)]*\)/g)) {
  32651. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  32652. }
  32653. else {
  32654. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  32655. // remove parenthesis
  32656. r = r.slice(1, r.length - 1);
  32657. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  32658. });
  32659. }
  32660. if (query === "true") {
  32661. return true;
  32662. }
  32663. if (query === "false") {
  32664. return false;
  32665. }
  32666. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  32667. };
  32668. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  32669. evaluateCallback = evaluateCallback || (function (r) {
  32670. return r === "true" ? true : false;
  32671. });
  32672. var result;
  32673. var or = parenthesisContent.split("||");
  32674. for (var i in or) {
  32675. if (or.hasOwnProperty(i)) {
  32676. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  32677. var and = ori.split("&&");
  32678. if (and.length > 1) {
  32679. for (var j = 0; j < and.length; ++j) {
  32680. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  32681. if (andj !== "true" && andj !== "false") {
  32682. if (andj[0] === "!") {
  32683. result = !evaluateCallback(andj.substring(1));
  32684. }
  32685. else {
  32686. result = evaluateCallback(andj);
  32687. }
  32688. }
  32689. else {
  32690. result = andj === "true" ? true : false;
  32691. }
  32692. if (!result) {
  32693. ori = "false";
  32694. break;
  32695. }
  32696. }
  32697. }
  32698. if (result || ori === "true") {
  32699. result = true;
  32700. break;
  32701. }
  32702. // result equals false (or undefined)
  32703. if (ori !== "true" && ori !== "false") {
  32704. if (ori[0] === "!") {
  32705. result = !evaluateCallback(ori.substring(1));
  32706. }
  32707. else {
  32708. result = evaluateCallback(ori);
  32709. }
  32710. }
  32711. else {
  32712. result = ori === "true" ? true : false;
  32713. }
  32714. }
  32715. }
  32716. // the whole parenthesis scope is replaced by 'true' or 'false'
  32717. return result ? "true" : "false";
  32718. };
  32719. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  32720. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  32721. // remove whitespaces
  32722. r = r.replace(/[\s]/g, function () { return ""; });
  32723. return r.length % 2 ? "!" : "";
  32724. });
  32725. booleanString = booleanString.trim();
  32726. if (booleanString === "!true") {
  32727. booleanString = "false";
  32728. }
  32729. else if (booleanString === "!false") {
  32730. booleanString = "true";
  32731. }
  32732. return booleanString;
  32733. };
  32734. return AndOrNotEvaluator;
  32735. }());
  32736. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  32737. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32738. })(BABYLON || (BABYLON = {}));
  32739. var BABYLON;
  32740. (function (BABYLON) {
  32741. var PostProcessRenderPass = (function () {
  32742. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  32743. this._enabled = true;
  32744. this._refCount = 0;
  32745. this._name = name;
  32746. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  32747. this.setRenderList(renderList);
  32748. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  32749. this._renderTexture.onAfterRenderObservable.add(afterRender);
  32750. this._scene = scene;
  32751. this._renderList = renderList;
  32752. }
  32753. // private
  32754. PostProcessRenderPass.prototype._incRefCount = function () {
  32755. if (this._refCount === 0) {
  32756. this._scene.customRenderTargets.push(this._renderTexture);
  32757. }
  32758. return ++this._refCount;
  32759. };
  32760. PostProcessRenderPass.prototype._decRefCount = function () {
  32761. this._refCount--;
  32762. if (this._refCount <= 0) {
  32763. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  32764. }
  32765. return this._refCount;
  32766. };
  32767. PostProcessRenderPass.prototype._update = function () {
  32768. this.setRenderList(this._renderList);
  32769. };
  32770. // public
  32771. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  32772. this._renderTexture.renderList = renderList;
  32773. };
  32774. PostProcessRenderPass.prototype.getRenderTexture = function () {
  32775. return this._renderTexture;
  32776. };
  32777. return PostProcessRenderPass;
  32778. }());
  32779. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  32780. })(BABYLON || (BABYLON = {}));
  32781. var BABYLON;
  32782. (function (BABYLON) {
  32783. var PostProcessRenderEffect = (function () {
  32784. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  32785. this._engine = engine;
  32786. this._name = name;
  32787. this._singleInstance = singleInstance || true;
  32788. this._getPostProcess = getPostProcess;
  32789. this._cameras = [];
  32790. this._indicesForCamera = [];
  32791. this._postProcesses = {};
  32792. this._renderPasses = {};
  32793. this._renderEffectAsPasses = {};
  32794. }
  32795. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  32796. get: function () {
  32797. for (var index in this._postProcesses) {
  32798. if (!this._postProcesses[index].isSupported) {
  32799. return false;
  32800. }
  32801. }
  32802. return true;
  32803. },
  32804. enumerable: true,
  32805. configurable: true
  32806. });
  32807. PostProcessRenderEffect.prototype._update = function () {
  32808. for (var renderPassName in this._renderPasses) {
  32809. this._renderPasses[renderPassName]._update();
  32810. }
  32811. };
  32812. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  32813. this._renderPasses[renderPass._name] = renderPass;
  32814. this._linkParameters();
  32815. };
  32816. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  32817. delete this._renderPasses[renderPass._name];
  32818. this._linkParameters();
  32819. };
  32820. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  32821. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  32822. this._linkParameters();
  32823. };
  32824. PostProcessRenderEffect.prototype.getPass = function (passName) {
  32825. for (var renderPassName in this._renderPasses) {
  32826. if (renderPassName === passName) {
  32827. return this._renderPasses[passName];
  32828. }
  32829. }
  32830. };
  32831. PostProcessRenderEffect.prototype.emptyPasses = function () {
  32832. this._renderPasses = {};
  32833. this._linkParameters();
  32834. };
  32835. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  32836. var cameraKey;
  32837. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32838. for (var i = 0; i < _cam.length; i++) {
  32839. var camera = _cam[i];
  32840. var cameraName = camera.name;
  32841. if (this._singleInstance) {
  32842. cameraKey = 0;
  32843. }
  32844. else {
  32845. cameraKey = cameraName;
  32846. }
  32847. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  32848. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  32849. if (!this._indicesForCamera[cameraName]) {
  32850. this._indicesForCamera[cameraName] = [];
  32851. }
  32852. this._indicesForCamera[cameraName].push(index);
  32853. if (this._cameras.indexOf(camera) === -1) {
  32854. this._cameras[cameraName] = camera;
  32855. }
  32856. for (var passName in this._renderPasses) {
  32857. this._renderPasses[passName]._incRefCount();
  32858. }
  32859. }
  32860. this._linkParameters();
  32861. };
  32862. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  32863. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32864. for (var i = 0; i < _cam.length; i++) {
  32865. var camera = _cam[i];
  32866. var cameraName = camera.name;
  32867. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32868. var index = this._cameras.indexOf(cameraName);
  32869. this._indicesForCamera.splice(index, 1);
  32870. this._cameras.splice(index, 1);
  32871. for (var passName in this._renderPasses) {
  32872. this._renderPasses[passName]._decRefCount();
  32873. }
  32874. }
  32875. };
  32876. PostProcessRenderEffect.prototype._enable = function (cameras) {
  32877. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32878. for (var i = 0; i < _cam.length; i++) {
  32879. var camera = _cam[i];
  32880. var cameraName = camera.name;
  32881. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  32882. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  32883. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  32884. }
  32885. }
  32886. for (var passName in this._renderPasses) {
  32887. this._renderPasses[passName]._incRefCount();
  32888. }
  32889. }
  32890. };
  32891. PostProcessRenderEffect.prototype._disable = 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. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32897. for (var passName in this._renderPasses) {
  32898. this._renderPasses[passName]._decRefCount();
  32899. }
  32900. }
  32901. };
  32902. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  32903. if (this._singleInstance) {
  32904. return this._postProcesses[0];
  32905. }
  32906. else {
  32907. return this._postProcesses[camera.name];
  32908. }
  32909. };
  32910. PostProcessRenderEffect.prototype._linkParameters = function () {
  32911. var _this = this;
  32912. for (var index in this._postProcesses) {
  32913. if (this.applyParameters) {
  32914. this.applyParameters(this._postProcesses[index]);
  32915. }
  32916. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  32917. _this._linkTextures(effect);
  32918. });
  32919. }
  32920. };
  32921. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  32922. for (var renderPassName in this._renderPasses) {
  32923. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  32924. }
  32925. for (var renderEffectName in this._renderEffectAsPasses) {
  32926. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  32927. }
  32928. };
  32929. return PostProcessRenderEffect;
  32930. }());
  32931. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  32932. })(BABYLON || (BABYLON = {}));
  32933. var BABYLON;
  32934. (function (BABYLON) {
  32935. var PostProcessRenderPipeline = (function () {
  32936. function PostProcessRenderPipeline(engine, name) {
  32937. this._engine = engine;
  32938. this._name = name;
  32939. this._renderEffects = {};
  32940. this._renderEffectsForIsolatedPass = {};
  32941. this._cameras = [];
  32942. }
  32943. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  32944. get: function () {
  32945. for (var renderEffectName in this._renderEffects) {
  32946. if (!this._renderEffects[renderEffectName].isSupported) {
  32947. return false;
  32948. }
  32949. }
  32950. return true;
  32951. },
  32952. enumerable: true,
  32953. configurable: true
  32954. });
  32955. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  32956. this._renderEffects[renderEffect._name] = renderEffect;
  32957. };
  32958. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  32959. var renderEffects = this._renderEffects[renderEffectName];
  32960. if (!renderEffects) {
  32961. return;
  32962. }
  32963. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32964. };
  32965. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  32966. var renderEffects = this._renderEffects[renderEffectName];
  32967. if (!renderEffects) {
  32968. return;
  32969. }
  32970. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32971. };
  32972. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  32973. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32974. var indicesToDelete = [];
  32975. var i;
  32976. for (i = 0; i < _cam.length; i++) {
  32977. var camera = _cam[i];
  32978. var cameraName = camera.name;
  32979. if (this._cameras.indexOf(camera) === -1) {
  32980. this._cameras[cameraName] = camera;
  32981. }
  32982. else if (unique) {
  32983. indicesToDelete.push(i);
  32984. }
  32985. }
  32986. for (i = 0; i < indicesToDelete.length; i++) {
  32987. cameras.splice(indicesToDelete[i], 1);
  32988. }
  32989. for (var renderEffectName in this._renderEffects) {
  32990. this._renderEffects[renderEffectName]._attachCameras(_cam);
  32991. }
  32992. };
  32993. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  32994. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32995. for (var renderEffectName in this._renderEffects) {
  32996. this._renderEffects[renderEffectName]._detachCameras(_cam);
  32997. }
  32998. for (var i = 0; i < _cam.length; i++) {
  32999. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  33000. }
  33001. };
  33002. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  33003. var _this = this;
  33004. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33005. var pass = null;
  33006. var renderEffectName;
  33007. for (renderEffectName in this._renderEffects) {
  33008. pass = this._renderEffects[renderEffectName].getPass(passName);
  33009. if (pass != null) {
  33010. break;
  33011. }
  33012. }
  33013. if (pass === null) {
  33014. return;
  33015. }
  33016. for (renderEffectName in this._renderEffects) {
  33017. this._renderEffects[renderEffectName]._disable(_cam);
  33018. }
  33019. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  33020. for (var i = 0; i < _cam.length; i++) {
  33021. var camera = _cam[i];
  33022. var cameraName = camera.name;
  33023. 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); });
  33024. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  33025. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  33026. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  33027. }
  33028. };
  33029. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  33030. var _this = this;
  33031. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33032. for (var i = 0; i < _cam.length; i++) {
  33033. var camera = _cam[i];
  33034. var cameraName = camera.name;
  33035. 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); });
  33036. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  33037. }
  33038. for (var renderEffectName in this._renderEffects) {
  33039. this._renderEffects[renderEffectName]._enable(_cam);
  33040. }
  33041. };
  33042. PostProcessRenderPipeline.prototype._update = function () {
  33043. for (var renderEffectName in this._renderEffects) {
  33044. this._renderEffects[renderEffectName]._update();
  33045. }
  33046. for (var i = 0; i < this._cameras.length; i++) {
  33047. var cameraName = this._cameras[i].name;
  33048. if (this._renderEffectsForIsolatedPass[cameraName]) {
  33049. this._renderEffectsForIsolatedPass[cameraName]._update();
  33050. }
  33051. }
  33052. };
  33053. PostProcessRenderPipeline.prototype.dispose = function () {
  33054. // Must be implemented by children
  33055. };
  33056. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  33057. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  33058. return PostProcessRenderPipeline;
  33059. }());
  33060. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  33061. })(BABYLON || (BABYLON = {}));
  33062. var BABYLON;
  33063. (function (BABYLON) {
  33064. var PostProcessRenderPipelineManager = (function () {
  33065. function PostProcessRenderPipelineManager() {
  33066. this._renderPipelines = {};
  33067. }
  33068. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  33069. this._renderPipelines[renderPipeline._name] = renderPipeline;
  33070. };
  33071. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  33072. var renderPipeline = this._renderPipelines[renderPipelineName];
  33073. if (!renderPipeline) {
  33074. return;
  33075. }
  33076. renderPipeline._attachCameras(cameras, unique);
  33077. };
  33078. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  33079. var renderPipeline = this._renderPipelines[renderPipelineName];
  33080. if (!renderPipeline) {
  33081. return;
  33082. }
  33083. renderPipeline._detachCameras(cameras);
  33084. };
  33085. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33086. var renderPipeline = this._renderPipelines[renderPipelineName];
  33087. if (!renderPipeline) {
  33088. return;
  33089. }
  33090. renderPipeline._enableEffect(renderEffectName, cameras);
  33091. };
  33092. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33093. var renderPipeline = this._renderPipelines[renderPipelineName];
  33094. if (!renderPipeline) {
  33095. return;
  33096. }
  33097. renderPipeline._disableEffect(renderEffectName, cameras);
  33098. };
  33099. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  33100. var renderPipeline = this._renderPipelines[renderPipelineName];
  33101. if (!renderPipeline) {
  33102. return;
  33103. }
  33104. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  33105. };
  33106. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  33107. var renderPipeline = this._renderPipelines[renderPipelineName];
  33108. if (!renderPipeline) {
  33109. return;
  33110. }
  33111. renderPipeline._disableDisplayOnlyPass(cameras);
  33112. };
  33113. PostProcessRenderPipelineManager.prototype.update = function () {
  33114. for (var renderPipelineName in this._renderPipelines) {
  33115. var pipeline = this._renderPipelines[renderPipelineName];
  33116. if (!pipeline.isSupported) {
  33117. pipeline.dispose();
  33118. delete this._renderPipelines[renderPipelineName];
  33119. }
  33120. else {
  33121. pipeline._update();
  33122. }
  33123. }
  33124. };
  33125. return PostProcessRenderPipelineManager;
  33126. }());
  33127. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  33128. })(BABYLON || (BABYLON = {}));
  33129. var BABYLON;
  33130. (function (BABYLON) {
  33131. var BoundingBoxRenderer = (function () {
  33132. function BoundingBoxRenderer(scene) {
  33133. this.frontColor = new BABYLON.Color3(1, 1, 1);
  33134. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  33135. this.showBackLines = true;
  33136. this.renderList = new BABYLON.SmartArray(32);
  33137. this._vertexBuffers = {};
  33138. this._scene = scene;
  33139. }
  33140. BoundingBoxRenderer.prototype._prepareRessources = function () {
  33141. if (this._colorShader) {
  33142. return;
  33143. }
  33144. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  33145. attributes: [BABYLON.VertexBuffer.PositionKind],
  33146. uniforms: ["worldViewProjection", "color"]
  33147. });
  33148. var engine = this._scene.getEngine();
  33149. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  33150. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  33151. 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]);
  33152. };
  33153. BoundingBoxRenderer.prototype.reset = function () {
  33154. this.renderList.reset();
  33155. };
  33156. BoundingBoxRenderer.prototype.render = function () {
  33157. if (this.renderList.length === 0) {
  33158. return;
  33159. }
  33160. this._prepareRessources();
  33161. if (!this._colorShader.isReady()) {
  33162. return;
  33163. }
  33164. var engine = this._scene.getEngine();
  33165. engine.setDepthWrite(false);
  33166. this._colorShader._preBind();
  33167. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  33168. var boundingBox = this.renderList.data[boundingBoxIndex];
  33169. var min = boundingBox.minimum;
  33170. var max = boundingBox.maximum;
  33171. var diff = max.subtract(min);
  33172. var median = min.add(diff.scale(0.5));
  33173. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  33174. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  33175. .multiply(boundingBox.getWorldMatrix());
  33176. // VBOs
  33177. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  33178. if (this.showBackLines) {
  33179. // Back
  33180. engine.setDepthFunctionToGreaterOrEqual();
  33181. this._scene.resetCachedMaterial();
  33182. this._colorShader.setColor4("color", this.backColor.toColor4());
  33183. this._colorShader.bind(worldMatrix);
  33184. // Draw order
  33185. engine.draw(false, 0, 24);
  33186. }
  33187. // Front
  33188. engine.setDepthFunctionToLess();
  33189. this._scene.resetCachedMaterial();
  33190. this._colorShader.setColor4("color", this.frontColor.toColor4());
  33191. this._colorShader.bind(worldMatrix);
  33192. // Draw order
  33193. engine.draw(false, 0, 24);
  33194. }
  33195. this._colorShader.unbind();
  33196. engine.setDepthFunctionToLessOrEqual();
  33197. engine.setDepthWrite(true);
  33198. };
  33199. BoundingBoxRenderer.prototype.dispose = function () {
  33200. if (!this._colorShader) {
  33201. return;
  33202. }
  33203. this._colorShader.dispose();
  33204. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33205. if (buffer) {
  33206. buffer.dispose();
  33207. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33208. }
  33209. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33210. };
  33211. return BoundingBoxRenderer;
  33212. }());
  33213. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  33214. })(BABYLON || (BABYLON = {}));
  33215. var BABYLON;
  33216. (function (BABYLON) {
  33217. var Condition = (function () {
  33218. function Condition(actionManager) {
  33219. this._actionManager = actionManager;
  33220. }
  33221. Condition.prototype.isValid = function () {
  33222. return true;
  33223. };
  33224. Condition.prototype._getProperty = function (propertyPath) {
  33225. return this._actionManager._getProperty(propertyPath);
  33226. };
  33227. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33228. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33229. };
  33230. Condition.prototype.serialize = function () {
  33231. };
  33232. Condition.prototype._serialize = function (serializedCondition) {
  33233. return {
  33234. type: 2,
  33235. children: [],
  33236. name: serializedCondition.name,
  33237. properties: serializedCondition.properties
  33238. };
  33239. };
  33240. return Condition;
  33241. }());
  33242. BABYLON.Condition = Condition;
  33243. var ValueCondition = (function (_super) {
  33244. __extends(ValueCondition, _super);
  33245. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33246. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33247. _super.call(this, actionManager);
  33248. this.propertyPath = propertyPath;
  33249. this.value = value;
  33250. this.operator = operator;
  33251. this._target = target;
  33252. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  33253. this._property = this._getProperty(this.propertyPath);
  33254. }
  33255. Object.defineProperty(ValueCondition, "IsEqual", {
  33256. get: function () {
  33257. return ValueCondition._IsEqual;
  33258. },
  33259. enumerable: true,
  33260. configurable: true
  33261. });
  33262. Object.defineProperty(ValueCondition, "IsDifferent", {
  33263. get: function () {
  33264. return ValueCondition._IsDifferent;
  33265. },
  33266. enumerable: true,
  33267. configurable: true
  33268. });
  33269. Object.defineProperty(ValueCondition, "IsGreater", {
  33270. get: function () {
  33271. return ValueCondition._IsGreater;
  33272. },
  33273. enumerable: true,
  33274. configurable: true
  33275. });
  33276. Object.defineProperty(ValueCondition, "IsLesser", {
  33277. get: function () {
  33278. return ValueCondition._IsLesser;
  33279. },
  33280. enumerable: true,
  33281. configurable: true
  33282. });
  33283. // Methods
  33284. ValueCondition.prototype.isValid = function () {
  33285. switch (this.operator) {
  33286. case ValueCondition.IsGreater:
  33287. return this._effectiveTarget[this._property] > this.value;
  33288. case ValueCondition.IsLesser:
  33289. return this._effectiveTarget[this._property] < this.value;
  33290. case ValueCondition.IsEqual:
  33291. case ValueCondition.IsDifferent:
  33292. var check;
  33293. if (this.value.equals) {
  33294. check = this.value.equals(this._effectiveTarget[this._property]);
  33295. }
  33296. else {
  33297. check = this.value === this._effectiveTarget[this._property];
  33298. }
  33299. return this.operator === ValueCondition.IsEqual ? check : !check;
  33300. }
  33301. return false;
  33302. };
  33303. ValueCondition.prototype.serialize = function () {
  33304. return this._serialize({
  33305. name: "ValueCondition",
  33306. properties: [
  33307. BABYLON.Action._GetTargetProperty(this._target),
  33308. { name: "propertyPath", value: this.propertyPath },
  33309. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33310. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33311. ]
  33312. });
  33313. };
  33314. ValueCondition.GetOperatorName = function (operator) {
  33315. switch (operator) {
  33316. case ValueCondition._IsEqual: return "IsEqual";
  33317. case ValueCondition._IsDifferent: return "IsDifferent";
  33318. case ValueCondition._IsGreater: return "IsGreater";
  33319. case ValueCondition._IsLesser: return "IsLesser";
  33320. default: return "";
  33321. }
  33322. };
  33323. // Statics
  33324. ValueCondition._IsEqual = 0;
  33325. ValueCondition._IsDifferent = 1;
  33326. ValueCondition._IsGreater = 2;
  33327. ValueCondition._IsLesser = 3;
  33328. return ValueCondition;
  33329. }(Condition));
  33330. BABYLON.ValueCondition = ValueCondition;
  33331. var PredicateCondition = (function (_super) {
  33332. __extends(PredicateCondition, _super);
  33333. function PredicateCondition(actionManager, predicate) {
  33334. _super.call(this, actionManager);
  33335. this.predicate = predicate;
  33336. }
  33337. PredicateCondition.prototype.isValid = function () {
  33338. return this.predicate();
  33339. };
  33340. return PredicateCondition;
  33341. }(Condition));
  33342. BABYLON.PredicateCondition = PredicateCondition;
  33343. var StateCondition = (function (_super) {
  33344. __extends(StateCondition, _super);
  33345. function StateCondition(actionManager, target, value) {
  33346. _super.call(this, actionManager);
  33347. this.value = value;
  33348. this._target = target;
  33349. }
  33350. // Methods
  33351. StateCondition.prototype.isValid = function () {
  33352. return this._target.state === this.value;
  33353. };
  33354. StateCondition.prototype.serialize = function () {
  33355. return this._serialize({
  33356. name: "StateCondition",
  33357. properties: [
  33358. BABYLON.Action._GetTargetProperty(this._target),
  33359. { name: "value", value: this.value }
  33360. ]
  33361. });
  33362. };
  33363. return StateCondition;
  33364. }(Condition));
  33365. BABYLON.StateCondition = StateCondition;
  33366. })(BABYLON || (BABYLON = {}));
  33367. var BABYLON;
  33368. (function (BABYLON) {
  33369. var Action = (function () {
  33370. function Action(triggerOptions, condition) {
  33371. this.triggerOptions = triggerOptions;
  33372. if (triggerOptions.parameter) {
  33373. this.trigger = triggerOptions.trigger;
  33374. this._triggerParameter = triggerOptions.parameter;
  33375. }
  33376. else {
  33377. this.trigger = triggerOptions;
  33378. }
  33379. this._nextActiveAction = this;
  33380. this._condition = condition;
  33381. }
  33382. // Methods
  33383. Action.prototype._prepare = function () {
  33384. };
  33385. Action.prototype.getTriggerParameter = function () {
  33386. return this._triggerParameter;
  33387. };
  33388. Action.prototype._executeCurrent = function (evt) {
  33389. if (this._nextActiveAction._condition) {
  33390. var condition = this._nextActiveAction._condition;
  33391. var currentRenderId = this._actionManager.getScene().getRenderId();
  33392. // We cache the current evaluation for the current frame
  33393. if (condition._evaluationId === currentRenderId) {
  33394. if (!condition._currentResult) {
  33395. return;
  33396. }
  33397. }
  33398. else {
  33399. condition._evaluationId = currentRenderId;
  33400. if (!condition.isValid()) {
  33401. condition._currentResult = false;
  33402. return;
  33403. }
  33404. condition._currentResult = true;
  33405. }
  33406. }
  33407. this._nextActiveAction.execute(evt);
  33408. this.skipToNextActiveAction();
  33409. };
  33410. Action.prototype.execute = function (evt) {
  33411. };
  33412. Action.prototype.skipToNextActiveAction = function () {
  33413. if (this._nextActiveAction._child) {
  33414. if (!this._nextActiveAction._child._actionManager) {
  33415. this._nextActiveAction._child._actionManager = this._actionManager;
  33416. }
  33417. this._nextActiveAction = this._nextActiveAction._child;
  33418. }
  33419. else {
  33420. this._nextActiveAction = this;
  33421. }
  33422. };
  33423. Action.prototype.then = function (action) {
  33424. this._child = action;
  33425. action._actionManager = this._actionManager;
  33426. action._prepare();
  33427. return action;
  33428. };
  33429. Action.prototype._getProperty = function (propertyPath) {
  33430. return this._actionManager._getProperty(propertyPath);
  33431. };
  33432. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33433. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33434. };
  33435. Action.prototype.serialize = function (parent) {
  33436. };
  33437. // Called by BABYLON.Action objects in serialize(...). Internal use
  33438. Action.prototype._serialize = function (serializedAction, parent) {
  33439. var serializationObject = {
  33440. type: 1,
  33441. children: [],
  33442. name: serializedAction.name,
  33443. properties: serializedAction.properties || []
  33444. };
  33445. // Serialize child
  33446. if (this._child) {
  33447. this._child.serialize(serializationObject);
  33448. }
  33449. // Check if "this" has a condition
  33450. if (this._condition) {
  33451. var serializedCondition = this._condition.serialize();
  33452. serializedCondition.children.push(serializationObject);
  33453. if (parent) {
  33454. parent.children.push(serializedCondition);
  33455. }
  33456. return serializedCondition;
  33457. }
  33458. if (parent) {
  33459. parent.children.push(serializationObject);
  33460. }
  33461. return serializationObject;
  33462. };
  33463. Action._SerializeValueAsString = function (value) {
  33464. if (typeof value === "number") {
  33465. return value.toString();
  33466. }
  33467. if (typeof value === "boolean") {
  33468. return value ? "true" : "false";
  33469. }
  33470. if (value instanceof BABYLON.Vector2) {
  33471. return value.x + ", " + value.y;
  33472. }
  33473. if (value instanceof BABYLON.Vector3) {
  33474. return value.x + ", " + value.y + ", " + value.z;
  33475. }
  33476. if (value instanceof BABYLON.Color3) {
  33477. return value.r + ", " + value.g + ", " + value.b;
  33478. }
  33479. if (value instanceof BABYLON.Color4) {
  33480. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33481. }
  33482. return value; // string
  33483. };
  33484. Action._GetTargetProperty = function (target) {
  33485. return {
  33486. name: "target",
  33487. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33488. : target instanceof BABYLON.Light ? "LightProperties"
  33489. : target instanceof BABYLON.Camera ? "CameraProperties"
  33490. : "SceneProperties",
  33491. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33492. };
  33493. };
  33494. return Action;
  33495. }());
  33496. BABYLON.Action = Action;
  33497. })(BABYLON || (BABYLON = {}));
  33498. var BABYLON;
  33499. (function (BABYLON) {
  33500. /**
  33501. * ActionEvent is the event beint sent when an action is triggered.
  33502. */
  33503. var ActionEvent = (function () {
  33504. /**
  33505. * @constructor
  33506. * @param source The mesh or sprite that triggered the action.
  33507. * @param pointerX The X mouse cursor position at the time of the event
  33508. * @param pointerY The Y mouse cursor position at the time of the event
  33509. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33510. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33511. */
  33512. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33513. this.source = source;
  33514. this.pointerX = pointerX;
  33515. this.pointerY = pointerY;
  33516. this.meshUnderPointer = meshUnderPointer;
  33517. this.sourceEvent = sourceEvent;
  33518. this.additionalData = additionalData;
  33519. }
  33520. /**
  33521. * Helper function to auto-create an ActionEvent from a source mesh.
  33522. * @param source The source mesh that triggered the event
  33523. * @param evt {Event} The original (browser) event
  33524. */
  33525. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33526. var scene = source.getScene();
  33527. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33528. };
  33529. /**
  33530. * Helper function to auto-create an ActionEvent from a source mesh.
  33531. * @param source The source sprite that triggered the event
  33532. * @param scene Scene associated with the sprite
  33533. * @param evt {Event} The original (browser) event
  33534. */
  33535. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33536. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33537. };
  33538. /**
  33539. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33540. * @param scene the scene where the event occurred
  33541. * @param evt {Event} The original (browser) event
  33542. */
  33543. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33544. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33545. };
  33546. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33547. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33548. };
  33549. return ActionEvent;
  33550. }());
  33551. BABYLON.ActionEvent = ActionEvent;
  33552. /**
  33553. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  33554. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  33555. */
  33556. var ActionManager = (function () {
  33557. function ActionManager(scene) {
  33558. // Members
  33559. this.actions = new Array();
  33560. this._scene = scene;
  33561. scene._actionManagers.push(this);
  33562. }
  33563. Object.defineProperty(ActionManager, "NothingTrigger", {
  33564. get: function () {
  33565. return ActionManager._NothingTrigger;
  33566. },
  33567. enumerable: true,
  33568. configurable: true
  33569. });
  33570. Object.defineProperty(ActionManager, "OnPickTrigger", {
  33571. get: function () {
  33572. return ActionManager._OnPickTrigger;
  33573. },
  33574. enumerable: true,
  33575. configurable: true
  33576. });
  33577. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  33578. get: function () {
  33579. return ActionManager._OnLeftPickTrigger;
  33580. },
  33581. enumerable: true,
  33582. configurable: true
  33583. });
  33584. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  33585. get: function () {
  33586. return ActionManager._OnRightPickTrigger;
  33587. },
  33588. enumerable: true,
  33589. configurable: true
  33590. });
  33591. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  33592. get: function () {
  33593. return ActionManager._OnCenterPickTrigger;
  33594. },
  33595. enumerable: true,
  33596. configurable: true
  33597. });
  33598. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33599. get: function () {
  33600. return ActionManager._OnPickDownTrigger;
  33601. },
  33602. enumerable: true,
  33603. configurable: true
  33604. });
  33605. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33606. get: function () {
  33607. return ActionManager._OnPickUpTrigger;
  33608. },
  33609. enumerable: true,
  33610. configurable: true
  33611. });
  33612. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33613. /// This trigger will only be raised if you also declared a OnPickDown
  33614. get: function () {
  33615. return ActionManager._OnPickOutTrigger;
  33616. },
  33617. enumerable: true,
  33618. configurable: true
  33619. });
  33620. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33621. get: function () {
  33622. return ActionManager._OnLongPressTrigger;
  33623. },
  33624. enumerable: true,
  33625. configurable: true
  33626. });
  33627. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33628. get: function () {
  33629. return ActionManager._OnPointerOverTrigger;
  33630. },
  33631. enumerable: true,
  33632. configurable: true
  33633. });
  33634. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33635. get: function () {
  33636. return ActionManager._OnPointerOutTrigger;
  33637. },
  33638. enumerable: true,
  33639. configurable: true
  33640. });
  33641. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33642. get: function () {
  33643. return ActionManager._OnEveryFrameTrigger;
  33644. },
  33645. enumerable: true,
  33646. configurable: true
  33647. });
  33648. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33649. get: function () {
  33650. return ActionManager._OnIntersectionEnterTrigger;
  33651. },
  33652. enumerable: true,
  33653. configurable: true
  33654. });
  33655. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33656. get: function () {
  33657. return ActionManager._OnIntersectionExitTrigger;
  33658. },
  33659. enumerable: true,
  33660. configurable: true
  33661. });
  33662. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33663. get: function () {
  33664. return ActionManager._OnKeyDownTrigger;
  33665. },
  33666. enumerable: true,
  33667. configurable: true
  33668. });
  33669. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33670. get: function () {
  33671. return ActionManager._OnKeyUpTrigger;
  33672. },
  33673. enumerable: true,
  33674. configurable: true
  33675. });
  33676. // Methods
  33677. ActionManager.prototype.dispose = function () {
  33678. var index = this._scene._actionManagers.indexOf(this);
  33679. if (index > -1) {
  33680. this._scene._actionManagers.splice(index, 1);
  33681. }
  33682. };
  33683. ActionManager.prototype.getScene = function () {
  33684. return this._scene;
  33685. };
  33686. /**
  33687. * Does this action manager handles actions of any of the given triggers
  33688. * @param {number[]} triggers - the triggers to be tested
  33689. * @return {boolean} whether one (or more) of the triggers is handeled
  33690. */
  33691. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  33692. for (var index = 0; index < this.actions.length; index++) {
  33693. var action = this.actions[index];
  33694. if (triggers.indexOf(action.trigger) > -1) {
  33695. return true;
  33696. }
  33697. }
  33698. return false;
  33699. };
  33700. /**
  33701. * Does this action manager handles actions of a given trigger
  33702. * @param {number} trigger - the trigger to be tested
  33703. * @return {boolean} whether the trigger is handeled
  33704. */
  33705. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33706. for (var index = 0; index < this.actions.length; index++) {
  33707. var action = this.actions[index];
  33708. if (action.trigger === trigger) {
  33709. return true;
  33710. }
  33711. }
  33712. return false;
  33713. };
  33714. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33715. /**
  33716. * Does this action manager has pointer triggers
  33717. * @return {boolean} whether or not it has pointer triggers
  33718. */
  33719. get: function () {
  33720. for (var index = 0; index < this.actions.length; index++) {
  33721. var action = this.actions[index];
  33722. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33723. return true;
  33724. }
  33725. }
  33726. return false;
  33727. },
  33728. enumerable: true,
  33729. configurable: true
  33730. });
  33731. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33732. /**
  33733. * Does this action manager has pick triggers
  33734. * @return {boolean} whether or not it has pick triggers
  33735. */
  33736. get: function () {
  33737. for (var index = 0; index < this.actions.length; index++) {
  33738. var action = this.actions[index];
  33739. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33740. return true;
  33741. }
  33742. }
  33743. return false;
  33744. },
  33745. enumerable: true,
  33746. configurable: true
  33747. });
  33748. /**
  33749. * Registers an action to this action manager
  33750. * @param {BABYLON.Action} action - the action to be registered
  33751. * @return {BABYLON.Action} the action amended (prepared) after registration
  33752. */
  33753. ActionManager.prototype.registerAction = function (action) {
  33754. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33755. if (this.getScene().actionManager !== this) {
  33756. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33757. return null;
  33758. }
  33759. }
  33760. this.actions.push(action);
  33761. action._actionManager = this;
  33762. action._prepare();
  33763. return action;
  33764. };
  33765. /**
  33766. * Process a specific trigger
  33767. * @param {number} trigger - the trigger to process
  33768. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33769. */
  33770. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33771. for (var index = 0; index < this.actions.length; index++) {
  33772. var action = this.actions[index];
  33773. if (action.trigger === trigger) {
  33774. if (trigger === ActionManager.OnKeyUpTrigger
  33775. || trigger === ActionManager.OnKeyDownTrigger) {
  33776. var parameter = action.getTriggerParameter();
  33777. if (parameter) {
  33778. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33779. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33780. if (actualkey !== parameter.toLowerCase()) {
  33781. continue;
  33782. }
  33783. }
  33784. }
  33785. action._executeCurrent(evt);
  33786. }
  33787. }
  33788. };
  33789. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33790. var properties = propertyPath.split(".");
  33791. for (var index = 0; index < properties.length - 1; index++) {
  33792. target = target[properties[index]];
  33793. }
  33794. return target;
  33795. };
  33796. ActionManager.prototype._getProperty = function (propertyPath) {
  33797. var properties = propertyPath.split(".");
  33798. return properties[properties.length - 1];
  33799. };
  33800. ActionManager.prototype.serialize = function (name) {
  33801. var root = {
  33802. children: [],
  33803. name: name,
  33804. type: 3,
  33805. properties: [] // Empty for root but required
  33806. };
  33807. for (var i = 0; i < this.actions.length; i++) {
  33808. var triggerObject = {
  33809. type: 0,
  33810. children: [],
  33811. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33812. properties: []
  33813. };
  33814. var triggerOptions = this.actions[i].triggerOptions;
  33815. if (triggerOptions && typeof triggerOptions !== "number") {
  33816. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33817. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33818. }
  33819. else {
  33820. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  33821. }
  33822. }
  33823. // Serialize child action, recursively
  33824. this.actions[i].serialize(triggerObject);
  33825. // Add serialized trigger
  33826. root.children.push(triggerObject);
  33827. }
  33828. return root;
  33829. };
  33830. ActionManager.Parse = function (parsedActions, object, scene) {
  33831. var actionManager = new BABYLON.ActionManager(scene);
  33832. if (object === null)
  33833. scene.actionManager = actionManager;
  33834. else
  33835. object.actionManager = actionManager;
  33836. // instanciate a new object
  33837. var instanciate = function (name, params) {
  33838. var newInstance = Object.create(BABYLON[name].prototype);
  33839. newInstance.constructor.apply(newInstance, params);
  33840. return newInstance;
  33841. };
  33842. var parseParameter = function (name, value, target, propertyPath) {
  33843. if (propertyPath === null) {
  33844. // String, boolean or float
  33845. var floatValue = parseFloat(value);
  33846. if (value === "true" || value === "false")
  33847. return value === "true";
  33848. else
  33849. return isNaN(floatValue) ? value : floatValue;
  33850. }
  33851. var effectiveTarget = propertyPath.split(".");
  33852. var values = value.split(",");
  33853. // Get effective Target
  33854. for (var i = 0; i < effectiveTarget.length; i++) {
  33855. target = target[effectiveTarget[i]];
  33856. }
  33857. // Return appropriate value with its type
  33858. if (typeof (target) === "boolean")
  33859. return values[0] === "true";
  33860. if (typeof (target) === "string")
  33861. return values[0];
  33862. // Parameters with multiple values such as Vector3 etc.
  33863. var split = new Array();
  33864. for (var i = 0; i < values.length; i++)
  33865. split.push(parseFloat(values[i]));
  33866. if (target instanceof BABYLON.Vector3)
  33867. return BABYLON.Vector3.FromArray(split);
  33868. if (target instanceof BABYLON.Vector4)
  33869. return BABYLON.Vector4.FromArray(split);
  33870. if (target instanceof BABYLON.Color3)
  33871. return BABYLON.Color3.FromArray(split);
  33872. if (target instanceof BABYLON.Color4)
  33873. return BABYLON.Color4.FromArray(split);
  33874. return parseFloat(values[0]);
  33875. };
  33876. // traverse graph per trigger
  33877. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33878. if (combineArray === void 0) { combineArray = null; }
  33879. if (parsedAction.detached)
  33880. return;
  33881. var parameters = new Array();
  33882. var target = null;
  33883. var propertyPath = null;
  33884. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33885. // Parameters
  33886. if (parsedAction.type === 2)
  33887. parameters.push(actionManager);
  33888. else
  33889. parameters.push(trigger);
  33890. if (combine) {
  33891. var actions = new Array();
  33892. for (var j = 0; j < parsedAction.combine.length; j++) {
  33893. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33894. }
  33895. parameters.push(actions);
  33896. }
  33897. else {
  33898. for (var i = 0; i < parsedAction.properties.length; i++) {
  33899. var value = parsedAction.properties[i].value;
  33900. var name = parsedAction.properties[i].name;
  33901. var targetType = parsedAction.properties[i].targetType;
  33902. if (name === "target")
  33903. if (targetType !== null && targetType === "SceneProperties")
  33904. value = target = scene;
  33905. else
  33906. value = target = scene.getNodeByName(value);
  33907. else if (name === "parent")
  33908. value = scene.getNodeByName(value);
  33909. else if (name === "sound")
  33910. value = scene.getSoundByName(value);
  33911. else if (name !== "propertyPath") {
  33912. if (parsedAction.type === 2 && name === "operator")
  33913. value = BABYLON.ValueCondition[value];
  33914. else
  33915. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33916. }
  33917. else {
  33918. propertyPath = value;
  33919. }
  33920. parameters.push(value);
  33921. }
  33922. }
  33923. if (combineArray === null) {
  33924. parameters.push(condition);
  33925. }
  33926. else {
  33927. parameters.push(null);
  33928. }
  33929. // If interpolate value action
  33930. if (parsedAction.name === "InterpolateValueAction") {
  33931. var param = parameters[parameters.length - 2];
  33932. parameters[parameters.length - 1] = param;
  33933. parameters[parameters.length - 2] = condition;
  33934. }
  33935. // Action or condition(s) and not CombineAction
  33936. var newAction = instanciate(parsedAction.name, parameters);
  33937. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33938. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33939. if (action)
  33940. action.then(nothing);
  33941. else
  33942. actionManager.registerAction(nothing);
  33943. action = nothing;
  33944. }
  33945. if (combineArray === null) {
  33946. if (newAction instanceof BABYLON.Condition) {
  33947. condition = newAction;
  33948. newAction = action;
  33949. }
  33950. else {
  33951. condition = null;
  33952. if (action)
  33953. action.then(newAction);
  33954. else
  33955. actionManager.registerAction(newAction);
  33956. }
  33957. }
  33958. else {
  33959. combineArray.push(newAction);
  33960. }
  33961. for (var i = 0; i < parsedAction.children.length; i++)
  33962. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33963. };
  33964. // triggers
  33965. for (var i = 0; i < parsedActions.children.length; i++) {
  33966. var triggerParams;
  33967. var trigger = parsedActions.children[i];
  33968. if (trigger.properties.length > 0) {
  33969. var param = trigger.properties[0].value;
  33970. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33971. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33972. }
  33973. else
  33974. triggerParams = BABYLON.ActionManager[trigger.name];
  33975. for (var j = 0; j < trigger.children.length; j++) {
  33976. if (!trigger.detached)
  33977. traverse(trigger.children[j], triggerParams, null, null);
  33978. }
  33979. }
  33980. };
  33981. ActionManager.GetTriggerName = function (trigger) {
  33982. switch (trigger) {
  33983. case 0: return "NothingTrigger";
  33984. case 1: return "OnPickTrigger";
  33985. case 2: return "OnLeftPickTrigger";
  33986. case 3: return "OnRightPickTrigger";
  33987. case 4: return "OnCenterPickTrigger";
  33988. case 5: return "OnPickDownTrigger";
  33989. case 6: return "OnPickUpTrigger";
  33990. case 7: return "OnLongPressTrigger";
  33991. case 8: return "OnPointerOverTrigger";
  33992. case 9: return "OnPointerOutTrigger";
  33993. case 10: return "OnEveryFrameTrigger";
  33994. case 11: return "OnIntersectionEnterTrigger";
  33995. case 12: return "OnIntersectionExitTrigger";
  33996. case 13: return "OnKeyDownTrigger";
  33997. case 14: return "OnKeyUpTrigger";
  33998. case 15: return "OnPickOutTrigger";
  33999. default: return "";
  34000. }
  34001. };
  34002. // Statics
  34003. ActionManager._NothingTrigger = 0;
  34004. ActionManager._OnPickTrigger = 1;
  34005. ActionManager._OnLeftPickTrigger = 2;
  34006. ActionManager._OnRightPickTrigger = 3;
  34007. ActionManager._OnCenterPickTrigger = 4;
  34008. ActionManager._OnPickDownTrigger = 5;
  34009. ActionManager._OnPickUpTrigger = 6;
  34010. ActionManager._OnLongPressTrigger = 7;
  34011. ActionManager._OnPointerOverTrigger = 8;
  34012. ActionManager._OnPointerOutTrigger = 9;
  34013. ActionManager._OnEveryFrameTrigger = 10;
  34014. ActionManager._OnIntersectionEnterTrigger = 11;
  34015. ActionManager._OnIntersectionExitTrigger = 12;
  34016. ActionManager._OnKeyDownTrigger = 13;
  34017. ActionManager._OnKeyUpTrigger = 14;
  34018. ActionManager._OnPickOutTrigger = 15;
  34019. ActionManager.DragMovementThreshold = 10; // in pixels
  34020. ActionManager.LongPressDelay = 500; // in milliseconds
  34021. return ActionManager;
  34022. }());
  34023. BABYLON.ActionManager = ActionManager;
  34024. })(BABYLON || (BABYLON = {}));
  34025. var BABYLON;
  34026. (function (BABYLON) {
  34027. var InterpolateValueAction = (function (_super) {
  34028. __extends(InterpolateValueAction, _super);
  34029. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  34030. if (duration === void 0) { duration = 1000; }
  34031. _super.call(this, triggerOptions, condition);
  34032. this.propertyPath = propertyPath;
  34033. this.value = value;
  34034. this.duration = duration;
  34035. this.stopOtherAnimations = stopOtherAnimations;
  34036. this.onInterpolationDone = onInterpolationDone;
  34037. this._target = this._effectiveTarget = target;
  34038. }
  34039. InterpolateValueAction.prototype._prepare = function () {
  34040. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34041. this._property = this._getProperty(this.propertyPath);
  34042. };
  34043. InterpolateValueAction.prototype.execute = function () {
  34044. var scene = this._actionManager.getScene();
  34045. var keys = [
  34046. {
  34047. frame: 0,
  34048. value: this._effectiveTarget[this._property]
  34049. }, {
  34050. frame: 100,
  34051. value: this.value
  34052. }
  34053. ];
  34054. var dataType;
  34055. if (typeof this.value === "number") {
  34056. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34057. }
  34058. else if (this.value instanceof BABYLON.Color3) {
  34059. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34060. }
  34061. else if (this.value instanceof BABYLON.Vector3) {
  34062. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34063. }
  34064. else if (this.value instanceof BABYLON.Matrix) {
  34065. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34066. }
  34067. else if (this.value instanceof BABYLON.Quaternion) {
  34068. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34069. }
  34070. else {
  34071. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34072. return;
  34073. }
  34074. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34075. animation.setKeys(keys);
  34076. if (this.stopOtherAnimations) {
  34077. scene.stopAnimation(this._effectiveTarget);
  34078. }
  34079. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34080. };
  34081. InterpolateValueAction.prototype.serialize = function (parent) {
  34082. return _super.prototype._serialize.call(this, {
  34083. name: "InterpolateValueAction",
  34084. properties: [
  34085. BABYLON.Action._GetTargetProperty(this._target),
  34086. { name: "propertyPath", value: this.propertyPath },
  34087. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34088. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34089. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34090. ]
  34091. }, parent);
  34092. };
  34093. return InterpolateValueAction;
  34094. }(BABYLON.Action));
  34095. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34096. })(BABYLON || (BABYLON = {}));
  34097. var BABYLON;
  34098. (function (BABYLON) {
  34099. var SwitchBooleanAction = (function (_super) {
  34100. __extends(SwitchBooleanAction, _super);
  34101. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34102. _super.call(this, triggerOptions, condition);
  34103. this.propertyPath = propertyPath;
  34104. this._target = this._effectiveTarget = target;
  34105. }
  34106. SwitchBooleanAction.prototype._prepare = function () {
  34107. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34108. this._property = this._getProperty(this.propertyPath);
  34109. };
  34110. SwitchBooleanAction.prototype.execute = function () {
  34111. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34112. };
  34113. SwitchBooleanAction.prototype.serialize = function (parent) {
  34114. return _super.prototype._serialize.call(this, {
  34115. name: "SwitchBooleanAction",
  34116. properties: [
  34117. BABYLON.Action._GetTargetProperty(this._target),
  34118. { name: "propertyPath", value: this.propertyPath }
  34119. ]
  34120. }, parent);
  34121. };
  34122. return SwitchBooleanAction;
  34123. }(BABYLON.Action));
  34124. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34125. var SetStateAction = (function (_super) {
  34126. __extends(SetStateAction, _super);
  34127. function SetStateAction(triggerOptions, target, value, condition) {
  34128. _super.call(this, triggerOptions, condition);
  34129. this.value = value;
  34130. this._target = target;
  34131. }
  34132. SetStateAction.prototype.execute = function () {
  34133. this._target.state = this.value;
  34134. };
  34135. SetStateAction.prototype.serialize = function (parent) {
  34136. return _super.prototype._serialize.call(this, {
  34137. name: "SetStateAction",
  34138. properties: [
  34139. BABYLON.Action._GetTargetProperty(this._target),
  34140. { name: "value", value: this.value }
  34141. ]
  34142. }, parent);
  34143. };
  34144. return SetStateAction;
  34145. }(BABYLON.Action));
  34146. BABYLON.SetStateAction = SetStateAction;
  34147. var SetValueAction = (function (_super) {
  34148. __extends(SetValueAction, _super);
  34149. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34150. _super.call(this, triggerOptions, condition);
  34151. this.propertyPath = propertyPath;
  34152. this.value = value;
  34153. this._target = this._effectiveTarget = target;
  34154. }
  34155. SetValueAction.prototype._prepare = function () {
  34156. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34157. this._property = this._getProperty(this.propertyPath);
  34158. };
  34159. SetValueAction.prototype.execute = function () {
  34160. this._effectiveTarget[this._property] = this.value;
  34161. if (this._target.markAsDirty) {
  34162. this._target.markAsDirty(this._property);
  34163. }
  34164. };
  34165. SetValueAction.prototype.serialize = function (parent) {
  34166. return _super.prototype._serialize.call(this, {
  34167. name: "SetValueAction",
  34168. properties: [
  34169. BABYLON.Action._GetTargetProperty(this._target),
  34170. { name: "propertyPath", value: this.propertyPath },
  34171. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34172. ]
  34173. }, parent);
  34174. };
  34175. return SetValueAction;
  34176. }(BABYLON.Action));
  34177. BABYLON.SetValueAction = SetValueAction;
  34178. var IncrementValueAction = (function (_super) {
  34179. __extends(IncrementValueAction, _super);
  34180. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34181. _super.call(this, triggerOptions, condition);
  34182. this.propertyPath = propertyPath;
  34183. this.value = value;
  34184. this._target = this._effectiveTarget = target;
  34185. }
  34186. IncrementValueAction.prototype._prepare = function () {
  34187. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34188. this._property = this._getProperty(this.propertyPath);
  34189. if (typeof this._effectiveTarget[this._property] !== "number") {
  34190. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34191. }
  34192. };
  34193. IncrementValueAction.prototype.execute = function () {
  34194. this._effectiveTarget[this._property] += this.value;
  34195. if (this._target.markAsDirty) {
  34196. this._target.markAsDirty(this._property);
  34197. }
  34198. };
  34199. IncrementValueAction.prototype.serialize = function (parent) {
  34200. return _super.prototype._serialize.call(this, {
  34201. name: "IncrementValueAction",
  34202. properties: [
  34203. BABYLON.Action._GetTargetProperty(this._target),
  34204. { name: "propertyPath", value: this.propertyPath },
  34205. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34206. ]
  34207. }, parent);
  34208. };
  34209. return IncrementValueAction;
  34210. }(BABYLON.Action));
  34211. BABYLON.IncrementValueAction = IncrementValueAction;
  34212. var PlayAnimationAction = (function (_super) {
  34213. __extends(PlayAnimationAction, _super);
  34214. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34215. _super.call(this, triggerOptions, condition);
  34216. this.from = from;
  34217. this.to = to;
  34218. this.loop = loop;
  34219. this._target = target;
  34220. }
  34221. PlayAnimationAction.prototype._prepare = function () {
  34222. };
  34223. PlayAnimationAction.prototype.execute = function () {
  34224. var scene = this._actionManager.getScene();
  34225. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34226. };
  34227. PlayAnimationAction.prototype.serialize = function (parent) {
  34228. return _super.prototype._serialize.call(this, {
  34229. name: "PlayAnimationAction",
  34230. properties: [
  34231. BABYLON.Action._GetTargetProperty(this._target),
  34232. { name: "from", value: String(this.from) },
  34233. { name: "to", value: String(this.to) },
  34234. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34235. ]
  34236. }, parent);
  34237. };
  34238. return PlayAnimationAction;
  34239. }(BABYLON.Action));
  34240. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34241. var StopAnimationAction = (function (_super) {
  34242. __extends(StopAnimationAction, _super);
  34243. function StopAnimationAction(triggerOptions, target, condition) {
  34244. _super.call(this, triggerOptions, condition);
  34245. this._target = target;
  34246. }
  34247. StopAnimationAction.prototype._prepare = function () {
  34248. };
  34249. StopAnimationAction.prototype.execute = function () {
  34250. var scene = this._actionManager.getScene();
  34251. scene.stopAnimation(this._target);
  34252. };
  34253. StopAnimationAction.prototype.serialize = function (parent) {
  34254. return _super.prototype._serialize.call(this, {
  34255. name: "StopAnimationAction",
  34256. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34257. }, parent);
  34258. };
  34259. return StopAnimationAction;
  34260. }(BABYLON.Action));
  34261. BABYLON.StopAnimationAction = StopAnimationAction;
  34262. var DoNothingAction = (function (_super) {
  34263. __extends(DoNothingAction, _super);
  34264. function DoNothingAction(triggerOptions, condition) {
  34265. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34266. _super.call(this, triggerOptions, condition);
  34267. }
  34268. DoNothingAction.prototype.execute = function () {
  34269. };
  34270. DoNothingAction.prototype.serialize = function (parent) {
  34271. return _super.prototype._serialize.call(this, {
  34272. name: "DoNothingAction",
  34273. properties: []
  34274. }, parent);
  34275. };
  34276. return DoNothingAction;
  34277. }(BABYLON.Action));
  34278. BABYLON.DoNothingAction = DoNothingAction;
  34279. var CombineAction = (function (_super) {
  34280. __extends(CombineAction, _super);
  34281. function CombineAction(triggerOptions, children, condition) {
  34282. _super.call(this, triggerOptions, condition);
  34283. this.children = children;
  34284. }
  34285. CombineAction.prototype._prepare = function () {
  34286. for (var index = 0; index < this.children.length; index++) {
  34287. this.children[index]._actionManager = this._actionManager;
  34288. this.children[index]._prepare();
  34289. }
  34290. };
  34291. CombineAction.prototype.execute = function (evt) {
  34292. for (var index = 0; index < this.children.length; index++) {
  34293. this.children[index].execute(evt);
  34294. }
  34295. };
  34296. CombineAction.prototype.serialize = function (parent) {
  34297. var serializationObject = _super.prototype._serialize.call(this, {
  34298. name: "CombineAction",
  34299. properties: [],
  34300. combine: []
  34301. }, parent);
  34302. for (var i = 0; i < this.children.length; i++) {
  34303. serializationObject.combine.push(this.children[i].serialize(null));
  34304. }
  34305. return serializationObject;
  34306. };
  34307. return CombineAction;
  34308. }(BABYLON.Action));
  34309. BABYLON.CombineAction = CombineAction;
  34310. var ExecuteCodeAction = (function (_super) {
  34311. __extends(ExecuteCodeAction, _super);
  34312. function ExecuteCodeAction(triggerOptions, func, condition) {
  34313. _super.call(this, triggerOptions, condition);
  34314. this.func = func;
  34315. }
  34316. ExecuteCodeAction.prototype.execute = function (evt) {
  34317. this.func(evt);
  34318. };
  34319. return ExecuteCodeAction;
  34320. }(BABYLON.Action));
  34321. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34322. var SetParentAction = (function (_super) {
  34323. __extends(SetParentAction, _super);
  34324. function SetParentAction(triggerOptions, target, parent, condition) {
  34325. _super.call(this, triggerOptions, condition);
  34326. this._target = target;
  34327. this._parent = parent;
  34328. }
  34329. SetParentAction.prototype._prepare = function () {
  34330. };
  34331. SetParentAction.prototype.execute = function () {
  34332. if (this._target.parent === this._parent) {
  34333. return;
  34334. }
  34335. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34336. invertParentWorldMatrix.invert();
  34337. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34338. this._target.parent = this._parent;
  34339. };
  34340. SetParentAction.prototype.serialize = function (parent) {
  34341. return _super.prototype._serialize.call(this, {
  34342. name: "SetParentAction",
  34343. properties: [
  34344. BABYLON.Action._GetTargetProperty(this._target),
  34345. BABYLON.Action._GetTargetProperty(this._parent),
  34346. ]
  34347. }, parent);
  34348. };
  34349. return SetParentAction;
  34350. }(BABYLON.Action));
  34351. BABYLON.SetParentAction = SetParentAction;
  34352. var PlaySoundAction = (function (_super) {
  34353. __extends(PlaySoundAction, _super);
  34354. function PlaySoundAction(triggerOptions, sound, condition) {
  34355. _super.call(this, triggerOptions, condition);
  34356. this._sound = sound;
  34357. }
  34358. PlaySoundAction.prototype._prepare = function () {
  34359. };
  34360. PlaySoundAction.prototype.execute = function () {
  34361. if (this._sound !== undefined)
  34362. this._sound.play();
  34363. };
  34364. PlaySoundAction.prototype.serialize = function (parent) {
  34365. return _super.prototype._serialize.call(this, {
  34366. name: "PlaySoundAction",
  34367. properties: [{ name: "sound", value: this._sound.name }]
  34368. }, parent);
  34369. };
  34370. return PlaySoundAction;
  34371. }(BABYLON.Action));
  34372. BABYLON.PlaySoundAction = PlaySoundAction;
  34373. var StopSoundAction = (function (_super) {
  34374. __extends(StopSoundAction, _super);
  34375. function StopSoundAction(triggerOptions, sound, condition) {
  34376. _super.call(this, triggerOptions, condition);
  34377. this._sound = sound;
  34378. }
  34379. StopSoundAction.prototype._prepare = function () {
  34380. };
  34381. StopSoundAction.prototype.execute = function () {
  34382. if (this._sound !== undefined)
  34383. this._sound.stop();
  34384. };
  34385. StopSoundAction.prototype.serialize = function (parent) {
  34386. return _super.prototype._serialize.call(this, {
  34387. name: "StopSoundAction",
  34388. properties: [{ name: "sound", value: this._sound.name }]
  34389. }, parent);
  34390. };
  34391. return StopSoundAction;
  34392. }(BABYLON.Action));
  34393. BABYLON.StopSoundAction = StopSoundAction;
  34394. })(BABYLON || (BABYLON = {}));
  34395. var BABYLON;
  34396. (function (BABYLON) {
  34397. var Geometry = (function () {
  34398. function Geometry(id, scene, vertexData, updatable, mesh) {
  34399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34400. this._totalVertices = 0;
  34401. this._isDisposed = false;
  34402. this.id = id;
  34403. this._engine = scene.getEngine();
  34404. this._meshes = [];
  34405. this._scene = scene;
  34406. //Init vertex buffer cache
  34407. this._vertexBuffers = {};
  34408. this._indices = [];
  34409. // vertexData
  34410. if (vertexData) {
  34411. this.setAllVerticesData(vertexData, updatable);
  34412. }
  34413. else {
  34414. this._totalVertices = 0;
  34415. this._indices = [];
  34416. }
  34417. // applyToMesh
  34418. if (mesh) {
  34419. if (mesh instanceof BABYLON.LinesMesh) {
  34420. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34421. this.updateExtend();
  34422. }
  34423. this.applyToMesh(mesh);
  34424. mesh.computeWorldMatrix(true);
  34425. }
  34426. }
  34427. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34428. /**
  34429. * 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
  34430. * @returns The Bias Vector
  34431. */
  34432. get: function () {
  34433. return this._boundingBias;
  34434. },
  34435. set: function (value) {
  34436. if (this._boundingBias && this._boundingBias.equals(value)) {
  34437. return;
  34438. }
  34439. this._boundingBias = value.clone();
  34440. this.updateBoundingInfo(true, null);
  34441. },
  34442. enumerable: true,
  34443. configurable: true
  34444. });
  34445. Object.defineProperty(Geometry.prototype, "extend", {
  34446. get: function () {
  34447. return this._extend;
  34448. },
  34449. enumerable: true,
  34450. configurable: true
  34451. });
  34452. Geometry.prototype.getScene = function () {
  34453. return this._scene;
  34454. };
  34455. Geometry.prototype.getEngine = function () {
  34456. return this._engine;
  34457. };
  34458. Geometry.prototype.isReady = function () {
  34459. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34460. };
  34461. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34462. vertexData.applyToGeometry(this, updatable);
  34463. this.notifyUpdate();
  34464. };
  34465. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34466. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34467. this.setVerticesBuffer(buffer);
  34468. };
  34469. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34470. var kind = buffer.getKind();
  34471. if (this._vertexBuffers[kind]) {
  34472. this._vertexBuffers[kind].dispose();
  34473. }
  34474. this._vertexBuffers[kind] = buffer;
  34475. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34476. var data = buffer.getData();
  34477. var stride = buffer.getStrideSize();
  34478. this._totalVertices = data.length / stride;
  34479. this.updateExtend(data, stride);
  34480. var meshes = this._meshes;
  34481. var numOfMeshes = meshes.length;
  34482. for (var index = 0; index < numOfMeshes; index++) {
  34483. var mesh = meshes[index];
  34484. mesh._resetPointsArrayCache();
  34485. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34486. mesh._createGlobalSubMesh();
  34487. mesh.computeWorldMatrix(true);
  34488. }
  34489. }
  34490. this.notifyUpdate(kind);
  34491. };
  34492. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34493. var vertexBuffer = this.getVertexBuffer(kind);
  34494. if (!vertexBuffer) {
  34495. return;
  34496. }
  34497. vertexBuffer.updateDirectly(data, offset);
  34498. this.notifyUpdate(kind);
  34499. };
  34500. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34501. var vertexBuffer = this.getVertexBuffer(kind);
  34502. if (!vertexBuffer) {
  34503. return;
  34504. }
  34505. vertexBuffer.update(data);
  34506. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34507. var stride = vertexBuffer.getStrideSize();
  34508. this._totalVertices = data.length / stride;
  34509. this.updateBoundingInfo(updateExtends, data);
  34510. }
  34511. this.notifyUpdate(kind);
  34512. };
  34513. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34514. if (updateExtends) {
  34515. this.updateExtend(data);
  34516. }
  34517. var meshes = this._meshes;
  34518. var numOfMeshes = meshes.length;
  34519. for (var index = 0; index < numOfMeshes; index++) {
  34520. var mesh = meshes[index];
  34521. mesh._resetPointsArrayCache();
  34522. if (updateExtends) {
  34523. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34524. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34525. var subMesh = mesh.subMeshes[subIndex];
  34526. subMesh.refreshBoundingInfo();
  34527. }
  34528. }
  34529. }
  34530. };
  34531. Geometry.prototype.getTotalVertices = function () {
  34532. if (!this.isReady()) {
  34533. return 0;
  34534. }
  34535. return this._totalVertices;
  34536. };
  34537. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  34538. var vertexBuffer = this.getVertexBuffer(kind);
  34539. if (!vertexBuffer) {
  34540. return null;
  34541. }
  34542. var orig = vertexBuffer.getData();
  34543. if (!copyWhenShared || this._meshes.length === 1) {
  34544. return orig;
  34545. }
  34546. else {
  34547. var len = orig.length;
  34548. var copy = [];
  34549. for (var i = 0; i < len; i++) {
  34550. copy.push(orig[i]);
  34551. }
  34552. return copy;
  34553. }
  34554. };
  34555. Geometry.prototype.getVertexBuffer = function (kind) {
  34556. if (!this.isReady()) {
  34557. return null;
  34558. }
  34559. return this._vertexBuffers[kind];
  34560. };
  34561. Geometry.prototype.getVertexBuffers = function () {
  34562. if (!this.isReady()) {
  34563. return null;
  34564. }
  34565. return this._vertexBuffers;
  34566. };
  34567. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34568. if (!this._vertexBuffers) {
  34569. if (this._delayInfo) {
  34570. return this._delayInfo.indexOf(kind) !== -1;
  34571. }
  34572. return false;
  34573. }
  34574. return this._vertexBuffers[kind] !== undefined;
  34575. };
  34576. Geometry.prototype.getVerticesDataKinds = function () {
  34577. var result = [];
  34578. var kind;
  34579. if (!this._vertexBuffers && this._delayInfo) {
  34580. for (kind in this._delayInfo) {
  34581. result.push(kind);
  34582. }
  34583. }
  34584. else {
  34585. for (kind in this._vertexBuffers) {
  34586. result.push(kind);
  34587. }
  34588. }
  34589. return result;
  34590. };
  34591. Geometry.prototype.setIndices = function (indices, totalVertices) {
  34592. if (this._indexBuffer) {
  34593. this._engine._releaseBuffer(this._indexBuffer);
  34594. }
  34595. this._indices = indices;
  34596. if (this._meshes.length !== 0 && this._indices) {
  34597. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34598. }
  34599. if (totalVertices !== undefined) {
  34600. this._totalVertices = totalVertices;
  34601. }
  34602. var meshes = this._meshes;
  34603. var numOfMeshes = meshes.length;
  34604. for (var index = 0; index < numOfMeshes; index++) {
  34605. meshes[index]._createGlobalSubMesh();
  34606. }
  34607. this.notifyUpdate();
  34608. };
  34609. Geometry.prototype.getTotalIndices = function () {
  34610. if (!this.isReady()) {
  34611. return 0;
  34612. }
  34613. return this._indices.length;
  34614. };
  34615. Geometry.prototype.getIndices = function (copyWhenShared) {
  34616. if (!this.isReady()) {
  34617. return null;
  34618. }
  34619. var orig = this._indices;
  34620. if (!copyWhenShared || this._meshes.length === 1) {
  34621. return orig;
  34622. }
  34623. else {
  34624. var len = orig.length;
  34625. var copy = [];
  34626. for (var i = 0; i < len; i++) {
  34627. copy.push(orig[i]);
  34628. }
  34629. return copy;
  34630. }
  34631. };
  34632. Geometry.prototype.getIndexBuffer = function () {
  34633. if (!this.isReady()) {
  34634. return null;
  34635. }
  34636. return this._indexBuffer;
  34637. };
  34638. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34639. var meshes = this._meshes;
  34640. var index = meshes.indexOf(mesh);
  34641. if (index === -1) {
  34642. return;
  34643. }
  34644. for (var kind in this._vertexBuffers) {
  34645. this._vertexBuffers[kind].dispose();
  34646. }
  34647. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  34648. this._indexBuffer = null;
  34649. }
  34650. meshes.splice(index, 1);
  34651. mesh._geometry = null;
  34652. if (meshes.length === 0 && shouldDispose) {
  34653. this.dispose();
  34654. }
  34655. };
  34656. Geometry.prototype.applyToMesh = function (mesh) {
  34657. if (mesh._geometry === this) {
  34658. return;
  34659. }
  34660. var previousGeometry = mesh._geometry;
  34661. if (previousGeometry) {
  34662. previousGeometry.releaseForMesh(mesh);
  34663. }
  34664. var meshes = this._meshes;
  34665. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34666. mesh._geometry = this;
  34667. this._scene.pushGeometry(this);
  34668. meshes.push(mesh);
  34669. if (this.isReady()) {
  34670. this._applyToMesh(mesh);
  34671. }
  34672. else {
  34673. mesh._boundingInfo = this._boundingInfo;
  34674. }
  34675. };
  34676. Geometry.prototype.updateExtend = function (data, stride) {
  34677. if (data === void 0) { data = null; }
  34678. if (!data) {
  34679. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34680. }
  34681. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34682. };
  34683. Geometry.prototype._applyToMesh = function (mesh) {
  34684. var numOfMeshes = this._meshes.length;
  34685. // vertexBuffers
  34686. for (var kind in this._vertexBuffers) {
  34687. if (numOfMeshes === 1) {
  34688. this._vertexBuffers[kind].create();
  34689. }
  34690. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  34691. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34692. mesh._resetPointsArrayCache();
  34693. if (!this._extend) {
  34694. this.updateExtend(this._vertexBuffers[kind].getData());
  34695. }
  34696. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34697. mesh._createGlobalSubMesh();
  34698. //bounding info was just created again, world matrix should be applied again.
  34699. mesh._updateBoundingInfo();
  34700. }
  34701. }
  34702. // indexBuffer
  34703. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34704. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34705. }
  34706. if (this._indexBuffer) {
  34707. this._indexBuffer.references = numOfMeshes;
  34708. }
  34709. };
  34710. Geometry.prototype.notifyUpdate = function (kind) {
  34711. if (this.onGeometryUpdated) {
  34712. this.onGeometryUpdated(this, kind);
  34713. }
  34714. };
  34715. Geometry.prototype.load = function (scene, onLoaded) {
  34716. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34717. return;
  34718. }
  34719. if (this.isReady()) {
  34720. if (onLoaded) {
  34721. onLoaded();
  34722. }
  34723. return;
  34724. }
  34725. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34726. this._queueLoad(scene, onLoaded);
  34727. };
  34728. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34729. var _this = this;
  34730. scene._addPendingData(this);
  34731. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  34732. _this._delayLoadingFunction(JSON.parse(data), _this);
  34733. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34734. _this._delayInfo = [];
  34735. scene._removePendingData(_this);
  34736. var meshes = _this._meshes;
  34737. var numOfMeshes = meshes.length;
  34738. for (var index = 0; index < numOfMeshes; index++) {
  34739. _this._applyToMesh(meshes[index]);
  34740. }
  34741. if (onLoaded) {
  34742. onLoaded();
  34743. }
  34744. }, function () { }, scene.database);
  34745. };
  34746. /**
  34747. * Invert the geometry to move from a right handed system to a left handed one.
  34748. */
  34749. Geometry.prototype.toLeftHanded = function () {
  34750. // Flip faces
  34751. var tIndices = this.getIndices(false);
  34752. if (tIndices != null && tIndices.length > 0) {
  34753. for (var i = 0; i < tIndices.length; i += 3) {
  34754. var tTemp = tIndices[i + 0];
  34755. tIndices[i + 0] = tIndices[i + 2];
  34756. tIndices[i + 2] = tTemp;
  34757. }
  34758. this.setIndices(tIndices);
  34759. }
  34760. // Negate position.z
  34761. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34762. if (tPositions != null && tPositions.length > 0) {
  34763. for (var i = 0; i < tPositions.length; i += 3) {
  34764. tPositions[i + 2] = -tPositions[i + 2];
  34765. }
  34766. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34767. }
  34768. // Negate normal.z
  34769. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34770. if (tNormals != null && tNormals.length > 0) {
  34771. for (var i = 0; i < tNormals.length; i += 3) {
  34772. tNormals[i + 2] = -tNormals[i + 2];
  34773. }
  34774. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34775. }
  34776. };
  34777. Geometry.prototype.isDisposed = function () {
  34778. return this._isDisposed;
  34779. };
  34780. Geometry.prototype.dispose = function () {
  34781. var meshes = this._meshes;
  34782. var numOfMeshes = meshes.length;
  34783. var index;
  34784. for (index = 0; index < numOfMeshes; index++) {
  34785. this.releaseForMesh(meshes[index]);
  34786. }
  34787. this._meshes = [];
  34788. for (var kind in this._vertexBuffers) {
  34789. this._vertexBuffers[kind].dispose();
  34790. }
  34791. this._vertexBuffers = {};
  34792. this._totalVertices = 0;
  34793. if (this._indexBuffer) {
  34794. this._engine._releaseBuffer(this._indexBuffer);
  34795. }
  34796. this._indexBuffer = null;
  34797. this._indices = [];
  34798. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34799. this.delayLoadingFile = null;
  34800. this._delayLoadingFunction = null;
  34801. this._delayInfo = [];
  34802. this._boundingInfo = null;
  34803. this._scene.removeGeometry(this);
  34804. this._isDisposed = true;
  34805. };
  34806. Geometry.prototype.copy = function (id) {
  34807. var vertexData = new BABYLON.VertexData();
  34808. vertexData.indices = [];
  34809. var indices = this.getIndices();
  34810. for (var index = 0; index < indices.length; index++) {
  34811. vertexData.indices.push(indices[index]);
  34812. }
  34813. var updatable = false;
  34814. var stopChecking = false;
  34815. var kind;
  34816. for (kind in this._vertexBuffers) {
  34817. // using slice() to make a copy of the array and not just reference it
  34818. var data = this.getVerticesData(kind);
  34819. if (data instanceof Float32Array) {
  34820. vertexData.set(new Float32Array(data), kind);
  34821. }
  34822. else {
  34823. vertexData.set(data.slice(0), kind);
  34824. }
  34825. if (!stopChecking) {
  34826. updatable = this.getVertexBuffer(kind).isUpdatable();
  34827. stopChecking = !updatable;
  34828. }
  34829. }
  34830. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  34831. geometry.delayLoadState = this.delayLoadState;
  34832. geometry.delayLoadingFile = this.delayLoadingFile;
  34833. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34834. for (kind in this._delayInfo) {
  34835. geometry._delayInfo = geometry._delayInfo || [];
  34836. geometry._delayInfo.push(kind);
  34837. }
  34838. // Bounding info
  34839. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34840. return geometry;
  34841. };
  34842. Geometry.prototype.serialize = function () {
  34843. var serializationObject = {};
  34844. serializationObject.id = this.id;
  34845. if (BABYLON.Tags.HasTags(this)) {
  34846. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34847. }
  34848. return serializationObject;
  34849. };
  34850. Geometry.prototype.serializeVerticeData = function () {
  34851. var serializationObject = this.serialize();
  34852. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34853. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34854. }
  34855. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34856. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34857. }
  34858. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34859. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34860. }
  34861. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34862. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  34863. }
  34864. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34865. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  34866. }
  34867. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34868. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  34869. }
  34870. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34871. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  34872. }
  34873. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34874. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  34875. }
  34876. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34877. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34878. }
  34879. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34880. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34881. serializationObject.matricesIndices._isExpanded = true;
  34882. }
  34883. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34884. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34885. }
  34886. serializationObject.indices = this.getIndices();
  34887. return serializationObject;
  34888. };
  34889. // Statics
  34890. Geometry.ExtractFromMesh = function (mesh, id) {
  34891. var geometry = mesh._geometry;
  34892. if (!geometry) {
  34893. return null;
  34894. }
  34895. return geometry.copy(id);
  34896. };
  34897. /**
  34898. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34899. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34900. * Be aware Math.random() could cause collisions, but:
  34901. * "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"
  34902. */
  34903. Geometry.RandomId = function () {
  34904. return BABYLON.Tools.RandomId();
  34905. };
  34906. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  34907. var scene = mesh.getScene();
  34908. // Geometry
  34909. var geometryId = parsedGeometry.geometryId;
  34910. if (geometryId) {
  34911. var geometry = scene.getGeometryByID(geometryId);
  34912. if (geometry) {
  34913. geometry.applyToMesh(mesh);
  34914. }
  34915. }
  34916. else if (parsedGeometry instanceof ArrayBuffer) {
  34917. var binaryInfo = mesh._binaryInfo;
  34918. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34919. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34920. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34921. }
  34922. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34923. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34924. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34925. }
  34926. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34927. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34928. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34929. }
  34930. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34931. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34932. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34933. }
  34934. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34935. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34936. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34937. }
  34938. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34939. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34940. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34941. }
  34942. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34943. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34944. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34945. }
  34946. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34947. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34948. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34949. }
  34950. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34951. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34952. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34953. }
  34954. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34955. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34956. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34957. }
  34958. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34959. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34960. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34961. }
  34962. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34963. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34964. mesh.setIndices(indicesData);
  34965. }
  34966. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34967. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34968. mesh.subMeshes = [];
  34969. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34970. var materialIndex = subMeshesData[(i * 5) + 0];
  34971. var verticesStart = subMeshesData[(i * 5) + 1];
  34972. var verticesCount = subMeshesData[(i * 5) + 2];
  34973. var indexStart = subMeshesData[(i * 5) + 3];
  34974. var indexCount = subMeshesData[(i * 5) + 4];
  34975. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34976. }
  34977. }
  34978. }
  34979. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34980. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  34981. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  34982. if (parsedGeometry.uvs) {
  34983. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  34984. }
  34985. if (parsedGeometry.uvs2) {
  34986. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  34987. }
  34988. if (parsedGeometry.uvs3) {
  34989. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  34990. }
  34991. if (parsedGeometry.uvs4) {
  34992. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  34993. }
  34994. if (parsedGeometry.uvs5) {
  34995. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  34996. }
  34997. if (parsedGeometry.uvs6) {
  34998. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  34999. }
  35000. if (parsedGeometry.colors) {
  35001. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  35002. }
  35003. if (parsedGeometry.matricesIndices) {
  35004. if (!parsedGeometry.matricesIndices._isExpanded) {
  35005. var floatIndices = [];
  35006. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35007. var matricesIndex = parsedGeometry.matricesIndices[i];
  35008. floatIndices.push(matricesIndex & 0x000000FF);
  35009. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35010. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35011. floatIndices.push(matricesIndex >> 24);
  35012. }
  35013. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  35014. }
  35015. else {
  35016. delete parsedGeometry.matricesIndices._isExpanded;
  35017. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  35018. }
  35019. }
  35020. if (parsedGeometry.matricesIndicesExtra) {
  35021. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35022. var floatIndices = [];
  35023. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35024. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35025. floatIndices.push(matricesIndex & 0x000000FF);
  35026. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35027. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35028. floatIndices.push(matricesIndex >> 24);
  35029. }
  35030. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  35031. }
  35032. else {
  35033. delete parsedGeometry.matricesIndices._isExpanded;
  35034. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  35035. }
  35036. }
  35037. if (parsedGeometry.matricesWeights) {
  35038. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  35039. }
  35040. if (parsedGeometry.matricesWeightsExtra) {
  35041. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  35042. }
  35043. mesh.setIndices(parsedGeometry.indices);
  35044. }
  35045. // SubMeshes
  35046. if (parsedGeometry.subMeshes) {
  35047. mesh.subMeshes = [];
  35048. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35049. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35050. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35051. }
  35052. }
  35053. // Flat shading
  35054. if (mesh._shouldGenerateFlatShading) {
  35055. mesh.convertToFlatShadedMesh();
  35056. delete mesh._shouldGenerateFlatShading;
  35057. }
  35058. // Update
  35059. mesh.computeWorldMatrix(true);
  35060. // Octree
  35061. if (scene['_selectionOctree']) {
  35062. scene['_selectionOctree'].addMesh(mesh);
  35063. }
  35064. };
  35065. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35066. if (scene.getGeometryByID(parsedVertexData.id)) {
  35067. return null; // null since geometry could be something else than a box...
  35068. }
  35069. var geometry = new Geometry(parsedVertexData.id, scene);
  35070. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35071. if (parsedVertexData.delayLoadingFile) {
  35072. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35073. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35074. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35075. geometry._delayInfo = [];
  35076. if (parsedVertexData.hasUVs) {
  35077. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35078. }
  35079. if (parsedVertexData.hasUVs2) {
  35080. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35081. }
  35082. if (parsedVertexData.hasUVs3) {
  35083. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35084. }
  35085. if (parsedVertexData.hasUVs4) {
  35086. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35087. }
  35088. if (parsedVertexData.hasUVs5) {
  35089. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35090. }
  35091. if (parsedVertexData.hasUVs6) {
  35092. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35093. }
  35094. if (parsedVertexData.hasColors) {
  35095. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35096. }
  35097. if (parsedVertexData.hasMatricesIndices) {
  35098. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35099. }
  35100. if (parsedVertexData.hasMatricesWeights) {
  35101. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35102. }
  35103. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35104. }
  35105. else {
  35106. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35107. }
  35108. scene.pushGeometry(geometry, true);
  35109. return geometry;
  35110. };
  35111. return Geometry;
  35112. }());
  35113. BABYLON.Geometry = Geometry;
  35114. /////// Primitives //////////////////////////////////////////////
  35115. var Geometry;
  35116. (function (Geometry) {
  35117. var Primitives;
  35118. (function (Primitives) {
  35119. /// Abstract class
  35120. var _Primitive = (function (_super) {
  35121. __extends(_Primitive, _super);
  35122. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  35123. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  35124. this._canBeRegenerated = _canBeRegenerated;
  35125. this._beingRegenerated = true;
  35126. this.regenerate();
  35127. this._beingRegenerated = false;
  35128. }
  35129. _Primitive.prototype.canBeRegenerated = function () {
  35130. return this._canBeRegenerated;
  35131. };
  35132. _Primitive.prototype.regenerate = function () {
  35133. if (!this._canBeRegenerated) {
  35134. return;
  35135. }
  35136. this._beingRegenerated = true;
  35137. this.setAllVerticesData(this._regenerateVertexData(), false);
  35138. this._beingRegenerated = false;
  35139. };
  35140. _Primitive.prototype.asNewGeometry = function (id) {
  35141. return _super.prototype.copy.call(this, id);
  35142. };
  35143. // overrides
  35144. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  35145. if (!this._beingRegenerated) {
  35146. return;
  35147. }
  35148. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35149. };
  35150. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  35151. if (!this._beingRegenerated) {
  35152. return;
  35153. }
  35154. _super.prototype.setVerticesData.call(this, kind, data, false);
  35155. };
  35156. // to override
  35157. // protected
  35158. _Primitive.prototype._regenerateVertexData = function () {
  35159. throw new Error("Abstract method");
  35160. };
  35161. _Primitive.prototype.copy = function (id) {
  35162. throw new Error("Must be overriden in sub-classes.");
  35163. };
  35164. _Primitive.prototype.serialize = function () {
  35165. var serializationObject = _super.prototype.serialize.call(this);
  35166. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35167. return serializationObject;
  35168. };
  35169. return _Primitive;
  35170. }(Geometry));
  35171. Primitives._Primitive = _Primitive;
  35172. var Ribbon = (function (_super) {
  35173. __extends(Ribbon, _super);
  35174. // Members
  35175. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  35176. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35177. _super.call(this, id, scene, canBeRegenerated, mesh);
  35178. this.pathArray = pathArray;
  35179. this.closeArray = closeArray;
  35180. this.closePath = closePath;
  35181. this.offset = offset;
  35182. this.side = side;
  35183. }
  35184. Ribbon.prototype._regenerateVertexData = function () {
  35185. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35186. };
  35187. Ribbon.prototype.copy = function (id) {
  35188. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  35189. };
  35190. return Ribbon;
  35191. }(_Primitive));
  35192. Primitives.Ribbon = Ribbon;
  35193. var Box = (function (_super) {
  35194. __extends(Box, _super);
  35195. // Members
  35196. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  35197. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35198. _super.call(this, id, scene, canBeRegenerated, mesh);
  35199. this.size = size;
  35200. this.side = side;
  35201. }
  35202. Box.prototype._regenerateVertexData = function () {
  35203. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35204. };
  35205. Box.prototype.copy = function (id) {
  35206. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35207. };
  35208. Box.prototype.serialize = function () {
  35209. var serializationObject = _super.prototype.serialize.call(this);
  35210. serializationObject.size = this.size;
  35211. return serializationObject;
  35212. };
  35213. Box.Parse = function (parsedBox, scene) {
  35214. if (scene.getGeometryByID(parsedBox.id)) {
  35215. return null; // null since geometry could be something else than a box...
  35216. }
  35217. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35218. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35219. scene.pushGeometry(box, true);
  35220. return box;
  35221. };
  35222. return Box;
  35223. }(_Primitive));
  35224. Primitives.Box = Box;
  35225. var Sphere = (function (_super) {
  35226. __extends(Sphere, _super);
  35227. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  35228. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35229. _super.call(this, id, scene, canBeRegenerated, mesh);
  35230. this.segments = segments;
  35231. this.diameter = diameter;
  35232. this.side = side;
  35233. }
  35234. Sphere.prototype._regenerateVertexData = function () {
  35235. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35236. };
  35237. Sphere.prototype.copy = function (id) {
  35238. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35239. };
  35240. Sphere.prototype.serialize = function () {
  35241. var serializationObject = _super.prototype.serialize.call(this);
  35242. serializationObject.segments = this.segments;
  35243. serializationObject.diameter = this.diameter;
  35244. return serializationObject;
  35245. };
  35246. Sphere.Parse = function (parsedSphere, scene) {
  35247. if (scene.getGeometryByID(parsedSphere.id)) {
  35248. return null; // null since geometry could be something else than a sphere...
  35249. }
  35250. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35251. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35252. scene.pushGeometry(sphere, true);
  35253. return sphere;
  35254. };
  35255. return Sphere;
  35256. }(_Primitive));
  35257. Primitives.Sphere = Sphere;
  35258. var Disc = (function (_super) {
  35259. __extends(Disc, _super);
  35260. // Members
  35261. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  35262. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35263. _super.call(this, id, scene, canBeRegenerated, mesh);
  35264. this.radius = radius;
  35265. this.tessellation = tessellation;
  35266. this.side = side;
  35267. }
  35268. Disc.prototype._regenerateVertexData = function () {
  35269. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35270. };
  35271. Disc.prototype.copy = function (id) {
  35272. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35273. };
  35274. return Disc;
  35275. }(_Primitive));
  35276. Primitives.Disc = Disc;
  35277. var Cylinder = (function (_super) {
  35278. __extends(Cylinder, _super);
  35279. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  35280. if (subdivisions === void 0) { subdivisions = 1; }
  35281. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35282. _super.call(this, id, scene, canBeRegenerated, mesh);
  35283. this.height = height;
  35284. this.diameterTop = diameterTop;
  35285. this.diameterBottom = diameterBottom;
  35286. this.tessellation = tessellation;
  35287. this.subdivisions = subdivisions;
  35288. this.side = side;
  35289. }
  35290. Cylinder.prototype._regenerateVertexData = function () {
  35291. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35292. };
  35293. Cylinder.prototype.copy = function (id) {
  35294. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35295. };
  35296. Cylinder.prototype.serialize = function () {
  35297. var serializationObject = _super.prototype.serialize.call(this);
  35298. serializationObject.height = this.height;
  35299. serializationObject.diameterTop = this.diameterTop;
  35300. serializationObject.diameterBottom = this.diameterBottom;
  35301. serializationObject.tessellation = this.tessellation;
  35302. return serializationObject;
  35303. };
  35304. Cylinder.Parse = function (parsedCylinder, scene) {
  35305. if (scene.getGeometryByID(parsedCylinder.id)) {
  35306. return null; // null since geometry could be something else than a cylinder...
  35307. }
  35308. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35309. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35310. scene.pushGeometry(cylinder, true);
  35311. return cylinder;
  35312. };
  35313. return Cylinder;
  35314. }(_Primitive));
  35315. Primitives.Cylinder = Cylinder;
  35316. var Torus = (function (_super) {
  35317. __extends(Torus, _super);
  35318. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  35319. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35320. _super.call(this, id, scene, canBeRegenerated, mesh);
  35321. this.diameter = diameter;
  35322. this.thickness = thickness;
  35323. this.tessellation = tessellation;
  35324. this.side = side;
  35325. }
  35326. Torus.prototype._regenerateVertexData = function () {
  35327. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35328. };
  35329. Torus.prototype.copy = function (id) {
  35330. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35331. };
  35332. Torus.prototype.serialize = function () {
  35333. var serializationObject = _super.prototype.serialize.call(this);
  35334. serializationObject.diameter = this.diameter;
  35335. serializationObject.thickness = this.thickness;
  35336. serializationObject.tessellation = this.tessellation;
  35337. return serializationObject;
  35338. };
  35339. Torus.Parse = function (parsedTorus, scene) {
  35340. if (scene.getGeometryByID(parsedTorus.id)) {
  35341. return null; // null since geometry could be something else than a torus...
  35342. }
  35343. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35344. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35345. scene.pushGeometry(torus, true);
  35346. return torus;
  35347. };
  35348. return Torus;
  35349. }(_Primitive));
  35350. Primitives.Torus = Torus;
  35351. var Ground = (function (_super) {
  35352. __extends(Ground, _super);
  35353. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  35354. _super.call(this, id, scene, canBeRegenerated, mesh);
  35355. this.width = width;
  35356. this.height = height;
  35357. this.subdivisions = subdivisions;
  35358. }
  35359. Ground.prototype._regenerateVertexData = function () {
  35360. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35361. };
  35362. Ground.prototype.copy = function (id) {
  35363. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35364. };
  35365. Ground.prototype.serialize = function () {
  35366. var serializationObject = _super.prototype.serialize.call(this);
  35367. serializationObject.width = this.width;
  35368. serializationObject.height = this.height;
  35369. serializationObject.subdivisions = this.subdivisions;
  35370. return serializationObject;
  35371. };
  35372. Ground.Parse = function (parsedGround, scene) {
  35373. if (scene.getGeometryByID(parsedGround.id)) {
  35374. return null; // null since geometry could be something else than a ground...
  35375. }
  35376. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35377. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35378. scene.pushGeometry(ground, true);
  35379. return ground;
  35380. };
  35381. return Ground;
  35382. }(_Primitive));
  35383. Primitives.Ground = Ground;
  35384. var TiledGround = (function (_super) {
  35385. __extends(TiledGround, _super);
  35386. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  35387. _super.call(this, id, scene, canBeRegenerated, mesh);
  35388. this.xmin = xmin;
  35389. this.zmin = zmin;
  35390. this.xmax = xmax;
  35391. this.zmax = zmax;
  35392. this.subdivisions = subdivisions;
  35393. this.precision = precision;
  35394. }
  35395. TiledGround.prototype._regenerateVertexData = function () {
  35396. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35397. };
  35398. TiledGround.prototype.copy = function (id) {
  35399. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35400. };
  35401. return TiledGround;
  35402. }(_Primitive));
  35403. Primitives.TiledGround = TiledGround;
  35404. var Plane = (function (_super) {
  35405. __extends(Plane, _super);
  35406. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  35407. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35408. _super.call(this, id, scene, canBeRegenerated, mesh);
  35409. this.size = size;
  35410. this.side = side;
  35411. }
  35412. Plane.prototype._regenerateVertexData = function () {
  35413. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35414. };
  35415. Plane.prototype.copy = function (id) {
  35416. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35417. };
  35418. Plane.prototype.serialize = function () {
  35419. var serializationObject = _super.prototype.serialize.call(this);
  35420. serializationObject.size = this.size;
  35421. return serializationObject;
  35422. };
  35423. Plane.Parse = function (parsedPlane, scene) {
  35424. if (scene.getGeometryByID(parsedPlane.id)) {
  35425. return null; // null since geometry could be something else than a ground...
  35426. }
  35427. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35428. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35429. scene.pushGeometry(plane, true);
  35430. return plane;
  35431. };
  35432. return Plane;
  35433. }(_Primitive));
  35434. Primitives.Plane = Plane;
  35435. var TorusKnot = (function (_super) {
  35436. __extends(TorusKnot, _super);
  35437. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  35438. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35439. _super.call(this, id, scene, canBeRegenerated, mesh);
  35440. this.radius = radius;
  35441. this.tube = tube;
  35442. this.radialSegments = radialSegments;
  35443. this.tubularSegments = tubularSegments;
  35444. this.p = p;
  35445. this.q = q;
  35446. this.side = side;
  35447. }
  35448. TorusKnot.prototype._regenerateVertexData = function () {
  35449. 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 });
  35450. };
  35451. TorusKnot.prototype.copy = function (id) {
  35452. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35453. };
  35454. TorusKnot.prototype.serialize = function () {
  35455. var serializationObject = _super.prototype.serialize.call(this);
  35456. serializationObject.radius = this.radius;
  35457. serializationObject.tube = this.tube;
  35458. serializationObject.radialSegments = this.radialSegments;
  35459. serializationObject.tubularSegments = this.tubularSegments;
  35460. serializationObject.p = this.p;
  35461. serializationObject.q = this.q;
  35462. return serializationObject;
  35463. };
  35464. ;
  35465. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  35466. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35467. return null; // null since geometry could be something else than a ground...
  35468. }
  35469. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35470. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35471. scene.pushGeometry(torusKnot, true);
  35472. return torusKnot;
  35473. };
  35474. return TorusKnot;
  35475. }(_Primitive));
  35476. Primitives.TorusKnot = TorusKnot;
  35477. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  35478. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  35479. })(BABYLON || (BABYLON = {}));
  35480. var BABYLON;
  35481. (function (BABYLON) {
  35482. var GroundMesh = (function (_super) {
  35483. __extends(GroundMesh, _super);
  35484. function GroundMesh(name, scene) {
  35485. _super.call(this, name, scene);
  35486. this.generateOctree = false;
  35487. this._worldInverse = new BABYLON.Matrix();
  35488. }
  35489. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  35490. get: function () {
  35491. return Math.min(this._subdivisionsX, this._subdivisionsY);
  35492. },
  35493. enumerable: true,
  35494. configurable: true
  35495. });
  35496. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  35497. get: function () {
  35498. return this._subdivisionsX;
  35499. },
  35500. enumerable: true,
  35501. configurable: true
  35502. });
  35503. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  35504. get: function () {
  35505. return this._subdivisionsY;
  35506. },
  35507. enumerable: true,
  35508. configurable: true
  35509. });
  35510. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  35511. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  35512. this._subdivisionsX = chunksCount;
  35513. this._subdivisionsY = chunksCount;
  35514. this.subdivide(chunksCount);
  35515. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  35516. };
  35517. /**
  35518. * Returns a height (y) value in the Worl system :
  35519. * the ground altitude at the coordinates (x, z) expressed in the World system.
  35520. * Returns the ground y position if (x, z) are outside the ground surface.
  35521. * Not pertinent if the ground is rotated.
  35522. */
  35523. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  35524. // express x and y in the ground local system
  35525. x -= this.position.x;
  35526. z -= this.position.z;
  35527. x /= this.scaling.x;
  35528. z /= this.scaling.z;
  35529. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35530. return this.position.y;
  35531. }
  35532. if (!this._heightQuads || this._heightQuads.length == 0) {
  35533. this._initHeightQuads();
  35534. this._computeHeightQuads();
  35535. }
  35536. var facet = this._getFacetAt(x, z);
  35537. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  35538. // return y in the World system
  35539. return y * this.scaling.y + this.position.y;
  35540. };
  35541. /**
  35542. * Returns a normalized vector (Vector3) orthogonal to the ground
  35543. * at the ground coordinates (x, z) expressed in the World system.
  35544. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  35545. * Not pertinent if the ground is rotated.
  35546. */
  35547. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  35548. var normal = new BABYLON.Vector3(0, 1, 0);
  35549. this.getNormalAtCoordinatesToRef(x, z, normal);
  35550. return normal;
  35551. };
  35552. /**
  35553. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  35554. * at the ground coordinates (x, z) expressed in the World system.
  35555. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  35556. * Not pertinent if the ground is rotated.
  35557. */
  35558. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  35559. // express x and y in the ground local system
  35560. x -= this.position.x;
  35561. z -= this.position.z;
  35562. x /= this.scaling.x;
  35563. z /= this.scaling.z;
  35564. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35565. return;
  35566. }
  35567. if (!this._heightQuads || this._heightQuads.length == 0) {
  35568. this._initHeightQuads();
  35569. this._computeHeightQuads();
  35570. }
  35571. var facet = this._getFacetAt(x, z);
  35572. ref.x = facet.x;
  35573. ref.y = facet.y;
  35574. ref.z = facet.z;
  35575. };
  35576. /**
  35577. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  35578. * if the ground has been updated.
  35579. * This can be used in the render loop
  35580. */
  35581. GroundMesh.prototype.updateCoordinateHeights = function () {
  35582. if (!this._heightQuads || this._heightQuads.length == 0) {
  35583. this._initHeightQuads();
  35584. }
  35585. this._computeHeightQuads();
  35586. };
  35587. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  35588. GroundMesh.prototype._getFacetAt = function (x, z) {
  35589. // retrieve col and row from x, z coordinates in the ground local system
  35590. var subdivisionsX = this._subdivisionsX;
  35591. var subdivisionsY = this._subdivisionsY;
  35592. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  35593. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  35594. var quad = this._heightQuads[row * this._subdivisionsX + col];
  35595. var facet;
  35596. if (z < quad.slope.x * x + quad.slope.y) {
  35597. facet = quad.facet1;
  35598. }
  35599. else {
  35600. facet = quad.facet2;
  35601. }
  35602. return facet;
  35603. };
  35604. // Creates and populates the heightMap array with "facet" elements :
  35605. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  35606. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35607. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35608. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35609. GroundMesh.prototype._initHeightQuads = function () {
  35610. var subdivisionsX = this._subdivisionsX;
  35611. var subdivisionsY = this._subdivisionsY;
  35612. this._heightQuads = new Array();
  35613. for (var row = 0; row < subdivisionsY; row++) {
  35614. for (var col = 0; col < subdivisionsX; col++) {
  35615. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  35616. this._heightQuads[row * subdivisionsX + col] = quad;
  35617. }
  35618. }
  35619. };
  35620. // Compute each quad element values and update the the heightMap array :
  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._computeHeightQuads = function () {
  35625. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35626. var v1 = BABYLON.Tmp.Vector3[3];
  35627. var v2 = BABYLON.Tmp.Vector3[2];
  35628. var v3 = BABYLON.Tmp.Vector3[1];
  35629. var v4 = BABYLON.Tmp.Vector3[0];
  35630. var v1v2 = BABYLON.Tmp.Vector3[4];
  35631. var v1v3 = BABYLON.Tmp.Vector3[5];
  35632. var v1v4 = BABYLON.Tmp.Vector3[6];
  35633. var norm1 = BABYLON.Tmp.Vector3[7];
  35634. var norm2 = BABYLON.Tmp.Vector3[8];
  35635. var i = 0;
  35636. var j = 0;
  35637. var k = 0;
  35638. var cd = 0; // 2D slope coefficient : z = cd * x + h
  35639. var h = 0;
  35640. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  35641. var d2 = 0;
  35642. var subdivisionsX = this._subdivisionsX;
  35643. var subdivisionsY = this._subdivisionsY;
  35644. for (var row = 0; row < subdivisionsY; row++) {
  35645. for (var col = 0; col < subdivisionsX; col++) {
  35646. i = col * 3;
  35647. j = row * (subdivisionsX + 1) * 3;
  35648. k = (row + 1) * (subdivisionsX + 1) * 3;
  35649. v1.x = positions[j + i];
  35650. v1.y = positions[j + i + 1];
  35651. v1.z = positions[j + i + 2];
  35652. v2.x = positions[j + i + 3];
  35653. v2.y = positions[j + i + 4];
  35654. v2.z = positions[j + i + 5];
  35655. v3.x = positions[k + i];
  35656. v3.y = positions[k + i + 1];
  35657. v3.z = positions[k + i + 2];
  35658. v4.x = positions[k + i + 3];
  35659. v4.y = positions[k + i + 4];
  35660. v4.z = positions[k + i + 5];
  35661. // 2D slope V1V4
  35662. cd = (v4.z - v1.z) / (v4.x - v1.x);
  35663. h = v1.z - cd * v1.x; // v1 belongs to the slope
  35664. // facet equations :
  35665. // we compute each facet normal vector
  35666. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  35667. // we compute the value d by applying the equation to v1 which belongs to the plane
  35668. // then we store the facet equation in a Vector4
  35669. v2.subtractToRef(v1, v1v2);
  35670. v3.subtractToRef(v1, v1v3);
  35671. v4.subtractToRef(v1, v1v4);
  35672. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  35673. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  35674. norm1.normalize();
  35675. norm2.normalize();
  35676. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  35677. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  35678. var quad = this._heightQuads[row * subdivisionsX + col];
  35679. quad.slope.copyFromFloats(cd, h);
  35680. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  35681. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  35682. }
  35683. }
  35684. };
  35685. return GroundMesh;
  35686. }(BABYLON.Mesh));
  35687. BABYLON.GroundMesh = GroundMesh;
  35688. })(BABYLON || (BABYLON = {}));
  35689. var BABYLON;
  35690. (function (BABYLON) {
  35691. var LinesMesh = (function (_super) {
  35692. __extends(LinesMesh, _super);
  35693. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  35694. if (parent === void 0) { parent = null; }
  35695. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  35696. this.color = new BABYLON.Color3(1, 1, 1);
  35697. this.alpha = 1;
  35698. this._positionBuffer = {};
  35699. if (source) {
  35700. this.color = source.color.clone();
  35701. this.alpha = source.alpha;
  35702. }
  35703. this._intersectionThreshold = 0.1;
  35704. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  35705. attributes: [BABYLON.VertexBuffer.PositionKind],
  35706. uniforms: ["worldViewProjection", "color"],
  35707. needAlphaBlending: true
  35708. });
  35709. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  35710. }
  35711. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  35712. /**
  35713. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35714. * This margin is expressed in world space coordinates, so its value may vary.
  35715. * Default value is 0.1
  35716. * @returns the intersection Threshold value.
  35717. */
  35718. get: function () {
  35719. return this._intersectionThreshold;
  35720. },
  35721. /**
  35722. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35723. * This margin is expressed in world space coordinates, so its value may vary.
  35724. * @param value the new threshold to apply
  35725. */
  35726. set: function (value) {
  35727. if (this._intersectionThreshold === value) {
  35728. return;
  35729. }
  35730. this._intersectionThreshold = value;
  35731. if (this.geometry) {
  35732. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  35733. }
  35734. },
  35735. enumerable: true,
  35736. configurable: true
  35737. });
  35738. Object.defineProperty(LinesMesh.prototype, "material", {
  35739. get: function () {
  35740. return this._colorShader;
  35741. },
  35742. enumerable: true,
  35743. configurable: true
  35744. });
  35745. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  35746. get: function () {
  35747. return false;
  35748. },
  35749. enumerable: true,
  35750. configurable: true
  35751. });
  35752. LinesMesh.prototype.createInstance = function (name) {
  35753. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  35754. return null;
  35755. };
  35756. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  35757. var engine = this.getScene().getEngine();
  35758. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  35759. // VBOs
  35760. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  35761. // Color
  35762. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  35763. };
  35764. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  35765. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  35766. return;
  35767. }
  35768. var engine = this.getScene().getEngine();
  35769. // Draw order
  35770. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  35771. };
  35772. LinesMesh.prototype.dispose = function (doNotRecurse) {
  35773. this._colorShader.dispose();
  35774. _super.prototype.dispose.call(this, doNotRecurse);
  35775. };
  35776. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  35777. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  35778. };
  35779. return LinesMesh;
  35780. }(BABYLON.Mesh));
  35781. BABYLON.LinesMesh = LinesMesh;
  35782. })(BABYLON || (BABYLON = {}));
  35783. var BABYLON;
  35784. (function (BABYLON) {
  35785. var DefaultLoadingScreen = (function () {
  35786. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  35787. var _this = this;
  35788. if (_loadingText === void 0) { _loadingText = ""; }
  35789. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  35790. this._renderingCanvas = _renderingCanvas;
  35791. this._loadingText = _loadingText;
  35792. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  35793. // Resize
  35794. this._resizeLoadingUI = function () {
  35795. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  35796. _this._loadingDiv.style.position = "absolute";
  35797. _this._loadingDiv.style.left = canvasRect.left + "px";
  35798. _this._loadingDiv.style.top = canvasRect.top + "px";
  35799. _this._loadingDiv.style.width = canvasRect.width + "px";
  35800. _this._loadingDiv.style.height = canvasRect.height + "px";
  35801. };
  35802. }
  35803. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  35804. var _this = this;
  35805. if (this._loadingDiv) {
  35806. // Do not add a loading screen if there is already one
  35807. return;
  35808. }
  35809. this._loadingDiv = document.createElement("div");
  35810. this._loadingDiv.id = "babylonjsLoadingDiv";
  35811. this._loadingDiv.style.opacity = "0";
  35812. this._loadingDiv.style.transition = "opacity 1.5s ease";
  35813. // Loading text
  35814. this._loadingTextDiv = document.createElement("div");
  35815. this._loadingTextDiv.style.position = "absolute";
  35816. this._loadingTextDiv.style.left = "0";
  35817. this._loadingTextDiv.style.top = "50%";
  35818. this._loadingTextDiv.style.marginTop = "80px";
  35819. this._loadingTextDiv.style.width = "100%";
  35820. this._loadingTextDiv.style.height = "20px";
  35821. this._loadingTextDiv.style.fontFamily = "Arial";
  35822. this._loadingTextDiv.style.fontSize = "14px";
  35823. this._loadingTextDiv.style.color = "white";
  35824. this._loadingTextDiv.style.textAlign = "center";
  35825. this._loadingTextDiv.innerHTML = "Loading";
  35826. this._loadingDiv.appendChild(this._loadingTextDiv);
  35827. //set the predefined text
  35828. this._loadingTextDiv.innerHTML = this._loadingText;
  35829. // Loading img
  35830. var imgBack = new Image();
  35831. 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==";
  35832. imgBack.style.position = "absolute";
  35833. imgBack.style.left = "50%";
  35834. imgBack.style.top = "50%";
  35835. imgBack.style.marginLeft = "-50px";
  35836. imgBack.style.marginTop = "-50px";
  35837. imgBack.style.transition = "transform 1.0s ease";
  35838. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  35839. var deg = 360;
  35840. var onTransitionEnd = function () {
  35841. deg += 360;
  35842. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  35843. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  35844. };
  35845. imgBack.addEventListener("transitionend", onTransitionEnd);
  35846. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  35847. this._loadingDiv.appendChild(imgBack);
  35848. // front image
  35849. var imgFront = new Image();
  35850. 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=";
  35851. imgFront.style.position = "absolute";
  35852. imgFront.style.left = "50%";
  35853. imgFront.style.top = "50%";
  35854. imgFront.style.marginLeft = "-50px";
  35855. imgFront.style.marginTop = "-50px";
  35856. this._loadingDiv.appendChild(imgFront);
  35857. this._resizeLoadingUI();
  35858. window.addEventListener("resize", this._resizeLoadingUI);
  35859. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35860. document.body.appendChild(this._loadingDiv);
  35861. setTimeout(function () {
  35862. _this._loadingDiv.style.opacity = "1";
  35863. imgBack.style.transform = "rotateZ(360deg)";
  35864. imgBack.style.webkitTransform = "rotateZ(360deg)";
  35865. }, 0);
  35866. };
  35867. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  35868. var _this = this;
  35869. if (!this._loadingDiv) {
  35870. return;
  35871. }
  35872. var onTransitionEnd = function () {
  35873. if (!_this._loadingDiv) {
  35874. return;
  35875. }
  35876. document.body.removeChild(_this._loadingDiv);
  35877. window.removeEventListener("resize", _this._resizeLoadingUI);
  35878. _this._loadingDiv = null;
  35879. };
  35880. this._loadingDiv.style.opacity = "0";
  35881. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  35882. };
  35883. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  35884. set: function (text) {
  35885. this._loadingText = text;
  35886. if (this._loadingTextDiv) {
  35887. this._loadingTextDiv.innerHTML = this._loadingText;
  35888. }
  35889. },
  35890. enumerable: true,
  35891. configurable: true
  35892. });
  35893. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  35894. get: function () {
  35895. return this._loadingDivBackgroundColor;
  35896. },
  35897. set: function (color) {
  35898. this._loadingDivBackgroundColor = color;
  35899. if (!this._loadingDiv) {
  35900. return;
  35901. }
  35902. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35903. },
  35904. enumerable: true,
  35905. configurable: true
  35906. });
  35907. return DefaultLoadingScreen;
  35908. }());
  35909. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  35910. })(BABYLON || (BABYLON = {}));
  35911. var BABYLON;
  35912. (function (BABYLON) {
  35913. var AudioEngine = (function () {
  35914. function AudioEngine() {
  35915. this._audioContext = null;
  35916. this._audioContextInitialized = false;
  35917. this.canUseWebAudio = false;
  35918. this.WarnedWebAudioUnsupported = false;
  35919. this.unlocked = false;
  35920. this.isMP3supported = false;
  35921. this.isOGGsupported = false;
  35922. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35923. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35924. this.canUseWebAudio = true;
  35925. }
  35926. var audioElem = document.createElement('audio');
  35927. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  35928. this.isMP3supported = true;
  35929. }
  35930. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  35931. this.isOGGsupported = true;
  35932. }
  35933. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35934. this._unlockiOSaudio();
  35935. }
  35936. else {
  35937. this.unlocked = true;
  35938. }
  35939. }
  35940. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35941. get: function () {
  35942. if (!this._audioContextInitialized) {
  35943. this._initializeAudioContext();
  35944. }
  35945. return this._audioContext;
  35946. },
  35947. enumerable: true,
  35948. configurable: true
  35949. });
  35950. AudioEngine.prototype._unlockiOSaudio = function () {
  35951. var _this = this;
  35952. var unlockaudio = function () {
  35953. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35954. var source = _this.audioContext.createBufferSource();
  35955. source.buffer = buffer;
  35956. source.connect(_this.audioContext.destination);
  35957. source.start(0);
  35958. setTimeout(function () {
  35959. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35960. _this.unlocked = true;
  35961. window.removeEventListener('touchend', unlockaudio, false);
  35962. if (_this.onAudioUnlocked) {
  35963. _this.onAudioUnlocked();
  35964. }
  35965. }
  35966. }, 0);
  35967. };
  35968. window.addEventListener('touchend', unlockaudio, false);
  35969. };
  35970. AudioEngine.prototype._initializeAudioContext = function () {
  35971. try {
  35972. if (this.canUseWebAudio) {
  35973. this._audioContext = new AudioContext();
  35974. // create a global volume gain node
  35975. this.masterGain = this._audioContext.createGain();
  35976. this.masterGain.gain.value = 1;
  35977. this.masterGain.connect(this._audioContext.destination);
  35978. this._audioContextInitialized = true;
  35979. }
  35980. }
  35981. catch (e) {
  35982. this.canUseWebAudio = false;
  35983. BABYLON.Tools.Error("Web Audio: " + e.message);
  35984. }
  35985. };
  35986. AudioEngine.prototype.dispose = function () {
  35987. if (this.canUseWebAudio && this._audioContextInitialized) {
  35988. if (this._connectedAnalyser) {
  35989. this._connectedAnalyser.stopDebugCanvas();
  35990. this._connectedAnalyser.dispose();
  35991. this.masterGain.disconnect();
  35992. this.masterGain.connect(this._audioContext.destination);
  35993. this._connectedAnalyser = null;
  35994. }
  35995. this.masterGain.gain.value = 1;
  35996. }
  35997. this.WarnedWebAudioUnsupported = false;
  35998. };
  35999. AudioEngine.prototype.getGlobalVolume = function () {
  36000. if (this.canUseWebAudio && this._audioContextInitialized) {
  36001. return this.masterGain.gain.value;
  36002. }
  36003. else {
  36004. return -1;
  36005. }
  36006. };
  36007. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  36008. if (this.canUseWebAudio && this._audioContextInitialized) {
  36009. this.masterGain.gain.value = newVolume;
  36010. }
  36011. };
  36012. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  36013. if (this._connectedAnalyser) {
  36014. this._connectedAnalyser.stopDebugCanvas();
  36015. }
  36016. if (this.canUseWebAudio && this._audioContextInitialized) {
  36017. this._connectedAnalyser = analyser;
  36018. this.masterGain.disconnect();
  36019. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  36020. }
  36021. };
  36022. return AudioEngine;
  36023. }());
  36024. BABYLON.AudioEngine = AudioEngine;
  36025. })(BABYLON || (BABYLON = {}));
  36026. var BABYLON;
  36027. (function (BABYLON) {
  36028. var Sound = (function () {
  36029. /**
  36030. * Create a sound and attach it to a scene
  36031. * @param name Name of your sound
  36032. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  36033. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  36034. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  36035. */
  36036. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  36037. var _this = this;
  36038. this.autoplay = false;
  36039. this.loop = false;
  36040. this.useCustomAttenuation = false;
  36041. this.spatialSound = false;
  36042. this.refDistance = 1;
  36043. this.rolloffFactor = 1;
  36044. this.maxDistance = 100;
  36045. this.distanceModel = "linear";
  36046. this._panningModel = "equalpower";
  36047. this._playbackRate = 1;
  36048. this._streaming = false;
  36049. this._startTime = 0;
  36050. this._startOffset = 0;
  36051. this._position = BABYLON.Vector3.Zero();
  36052. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  36053. this._volume = 1;
  36054. this._isLoaded = false;
  36055. this._isReadyToPlay = false;
  36056. this.isPlaying = false;
  36057. this.isPaused = false;
  36058. this._isDirectional = false;
  36059. // Used if you'd like to create a directional sound.
  36060. // If not set, the sound will be omnidirectional
  36061. this._coneInnerAngle = 360;
  36062. this._coneOuterAngle = 360;
  36063. this._coneOuterGain = 0;
  36064. this._isOutputConnected = false;
  36065. this._urlType = "Unknown";
  36066. this.name = name;
  36067. this._scene = scene;
  36068. this._readyToPlayCallback = readyToPlayCallback;
  36069. // Default custom attenuation function is a linear attenuation
  36070. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  36071. if (currentDistance < maxDistance) {
  36072. return currentVolume * (1 - currentDistance / maxDistance);
  36073. }
  36074. else {
  36075. return 0;
  36076. }
  36077. };
  36078. if (options) {
  36079. this.autoplay = options.autoplay || false;
  36080. this.loop = options.loop || false;
  36081. // if volume === 0, we need another way to check this option
  36082. if (options.volume !== undefined) {
  36083. this._volume = options.volume;
  36084. }
  36085. this.spatialSound = options.spatialSound || false;
  36086. this.maxDistance = options.maxDistance || 100;
  36087. this.useCustomAttenuation = options.useCustomAttenuation || false;
  36088. this.rolloffFactor = options.rolloffFactor || 1;
  36089. this.refDistance = options.refDistance || 1;
  36090. this.distanceModel = options.distanceModel || "linear";
  36091. this._playbackRate = options.playbackRate || 1;
  36092. this._streaming = options.streaming || false;
  36093. }
  36094. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36095. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  36096. this._soundGain.gain.value = this._volume;
  36097. this._inputAudioNode = this._soundGain;
  36098. this._ouputAudioNode = this._soundGain;
  36099. if (this.spatialSound) {
  36100. this._createSpatialParameters();
  36101. }
  36102. this._scene.mainSoundTrack.AddSound(this);
  36103. var validParameter = true;
  36104. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  36105. if (urlOrArrayBuffer) {
  36106. if (typeof (urlOrArrayBuffer) === "string")
  36107. this._urlType = "String";
  36108. if (Array.isArray(urlOrArrayBuffer))
  36109. this._urlType = "Array";
  36110. if (urlOrArrayBuffer instanceof ArrayBuffer)
  36111. this._urlType = "ArrayBuffer";
  36112. var urls = [];
  36113. var codecSupportedFound = false;
  36114. switch (this._urlType) {
  36115. case "ArrayBuffer":
  36116. if (urlOrArrayBuffer.byteLength > 0) {
  36117. codecSupportedFound = true;
  36118. this._soundLoaded(urlOrArrayBuffer);
  36119. }
  36120. break;
  36121. case "String":
  36122. urls.push(urlOrArrayBuffer);
  36123. case "Array":
  36124. if (urls.length === 0)
  36125. urls = urlOrArrayBuffer;
  36126. // If we found a supported format, we load it immediately and stop the loop
  36127. for (var i = 0; i < urls.length; i++) {
  36128. var url = urls[i];
  36129. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  36130. codecSupportedFound = true;
  36131. }
  36132. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  36133. codecSupportedFound = true;
  36134. }
  36135. if (url.indexOf(".wav", url.length - 4) !== -1) {
  36136. codecSupportedFound = true;
  36137. }
  36138. if (codecSupportedFound) {
  36139. // Loading sound using XHR2
  36140. if (!this._streaming) {
  36141. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  36142. }
  36143. else {
  36144. this._htmlAudioElement = new Audio(url);
  36145. this._htmlAudioElement.controls = false;
  36146. this._htmlAudioElement.loop = this.loop;
  36147. this._htmlAudioElement.crossOrigin = "anonymous";
  36148. this._htmlAudioElement.preload = "auto";
  36149. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  36150. _this._isReadyToPlay = true;
  36151. if (_this.autoplay) {
  36152. _this.play();
  36153. }
  36154. if (_this._readyToPlayCallback) {
  36155. _this._readyToPlayCallback();
  36156. }
  36157. });
  36158. document.body.appendChild(this._htmlAudioElement);
  36159. }
  36160. break;
  36161. }
  36162. }
  36163. break;
  36164. default:
  36165. validParameter = false;
  36166. break;
  36167. }
  36168. if (!validParameter) {
  36169. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  36170. }
  36171. else {
  36172. if (!codecSupportedFound) {
  36173. this._isReadyToPlay = true;
  36174. // Simulating a ready to play event to avoid breaking code path
  36175. if (this._readyToPlayCallback) {
  36176. window.setTimeout(function () {
  36177. _this._readyToPlayCallback();
  36178. }, 1000);
  36179. }
  36180. }
  36181. }
  36182. }
  36183. }
  36184. else {
  36185. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  36186. this._scene.mainSoundTrack.AddSound(this);
  36187. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  36188. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  36189. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  36190. }
  36191. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  36192. if (this._readyToPlayCallback) {
  36193. window.setTimeout(function () {
  36194. _this._readyToPlayCallback();
  36195. }, 1000);
  36196. }
  36197. }
  36198. }
  36199. Sound.prototype.dispose = function () {
  36200. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  36201. if (this.isPlaying) {
  36202. this.stop();
  36203. }
  36204. this._isReadyToPlay = false;
  36205. if (this.soundTrackId === -1) {
  36206. this._scene.mainSoundTrack.RemoveSound(this);
  36207. }
  36208. else {
  36209. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  36210. }
  36211. if (this._soundGain) {
  36212. this._soundGain.disconnect();
  36213. this._soundGain = null;
  36214. }
  36215. if (this._soundPanner) {
  36216. this._soundPanner.disconnect();
  36217. this._soundPanner = null;
  36218. }
  36219. if (this._soundSource) {
  36220. this._soundSource.disconnect();
  36221. this._soundSource = null;
  36222. }
  36223. this._audioBuffer = null;
  36224. if (this._htmlAudioElement) {
  36225. this._htmlAudioElement.pause();
  36226. this._htmlAudioElement.src = "";
  36227. document.body.removeChild(this._htmlAudioElement);
  36228. }
  36229. if (this._connectedMesh) {
  36230. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36231. this._connectedMesh = null;
  36232. }
  36233. }
  36234. };
  36235. Sound.prototype._soundLoaded = function (audioData) {
  36236. var _this = this;
  36237. this._isLoaded = true;
  36238. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  36239. _this._audioBuffer = buffer;
  36240. _this._isReadyToPlay = true;
  36241. if (_this.autoplay) {
  36242. _this.play();
  36243. }
  36244. if (_this._readyToPlayCallback) {
  36245. _this._readyToPlayCallback();
  36246. }
  36247. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  36248. };
  36249. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  36250. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36251. this._audioBuffer = audioBuffer;
  36252. this._isReadyToPlay = true;
  36253. }
  36254. };
  36255. Sound.prototype.updateOptions = function (options) {
  36256. if (options) {
  36257. this.loop = options.loop || this.loop;
  36258. this.maxDistance = options.maxDistance || this.maxDistance;
  36259. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  36260. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  36261. this.refDistance = options.refDistance || this.refDistance;
  36262. this.distanceModel = options.distanceModel || this.distanceModel;
  36263. this._playbackRate = options.playbackRate || this._playbackRate;
  36264. this._updateSpatialParameters();
  36265. if (this.isPlaying) {
  36266. if (this._streaming) {
  36267. this._htmlAudioElement.playbackRate = this._playbackRate;
  36268. }
  36269. else {
  36270. this._soundSource.playbackRate.value = this._playbackRate;
  36271. }
  36272. }
  36273. }
  36274. };
  36275. Sound.prototype._createSpatialParameters = function () {
  36276. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36277. if (this._scene.headphone) {
  36278. this._panningModel = "HRTF";
  36279. }
  36280. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  36281. this._updateSpatialParameters();
  36282. this._soundPanner.connect(this._ouputAudioNode);
  36283. this._inputAudioNode = this._soundPanner;
  36284. }
  36285. };
  36286. Sound.prototype._updateSpatialParameters = function () {
  36287. if (this.spatialSound) {
  36288. if (this.useCustomAttenuation) {
  36289. // Tricks to disable in a way embedded Web Audio attenuation
  36290. this._soundPanner.distanceModel = "linear";
  36291. this._soundPanner.maxDistance = Number.MAX_VALUE;
  36292. this._soundPanner.refDistance = 1;
  36293. this._soundPanner.rolloffFactor = 1;
  36294. this._soundPanner.panningModel = this._panningModel;
  36295. }
  36296. else {
  36297. this._soundPanner.distanceModel = this.distanceModel;
  36298. this._soundPanner.maxDistance = this.maxDistance;
  36299. this._soundPanner.refDistance = this.refDistance;
  36300. this._soundPanner.rolloffFactor = this.rolloffFactor;
  36301. this._soundPanner.panningModel = this._panningModel;
  36302. }
  36303. }
  36304. };
  36305. Sound.prototype.switchPanningModelToHRTF = function () {
  36306. this._panningModel = "HRTF";
  36307. this._switchPanningModel();
  36308. };
  36309. Sound.prototype.switchPanningModelToEqualPower = function () {
  36310. this._panningModel = "equalpower";
  36311. this._switchPanningModel();
  36312. };
  36313. Sound.prototype._switchPanningModel = function () {
  36314. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36315. this._soundPanner.panningModel = this._panningModel;
  36316. }
  36317. };
  36318. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  36319. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36320. if (this._isOutputConnected) {
  36321. this._ouputAudioNode.disconnect();
  36322. }
  36323. this._ouputAudioNode.connect(soundTrackAudioNode);
  36324. this._isOutputConnected = true;
  36325. }
  36326. };
  36327. /**
  36328. * Transform this sound into a directional source
  36329. * @param coneInnerAngle Size of the inner cone in degree
  36330. * @param coneOuterAngle Size of the outer cone in degree
  36331. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  36332. */
  36333. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  36334. if (coneOuterAngle < coneInnerAngle) {
  36335. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  36336. return;
  36337. }
  36338. this._coneInnerAngle = coneInnerAngle;
  36339. this._coneOuterAngle = coneOuterAngle;
  36340. this._coneOuterGain = coneOuterGain;
  36341. this._isDirectional = true;
  36342. if (this.isPlaying && this.loop) {
  36343. this.stop();
  36344. this.play();
  36345. }
  36346. };
  36347. Sound.prototype.setPosition = function (newPosition) {
  36348. this._position = newPosition;
  36349. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36350. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36351. }
  36352. };
  36353. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  36354. this._localDirection = newLocalDirection;
  36355. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  36356. this._updateDirection();
  36357. }
  36358. };
  36359. Sound.prototype._updateDirection = function () {
  36360. var mat = this._connectedMesh.getWorldMatrix();
  36361. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  36362. direction.normalize();
  36363. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  36364. };
  36365. Sound.prototype.updateDistanceFromListener = function () {
  36366. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  36367. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  36368. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  36369. }
  36370. };
  36371. Sound.prototype.setAttenuationFunction = function (callback) {
  36372. this._customAttenuationFunction = callback;
  36373. };
  36374. /**
  36375. * Play the sound
  36376. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  36377. * @param offset (optional) Start the sound setting it at a specific time
  36378. */
  36379. Sound.prototype.play = function (time, offset) {
  36380. var _this = this;
  36381. if (this._isReadyToPlay && this._scene.audioEnabled) {
  36382. try {
  36383. if (this._startOffset < 0) {
  36384. time = -this._startOffset;
  36385. this._startOffset = 0;
  36386. }
  36387. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36388. if (!this._soundSource || !this._streamingSource) {
  36389. if (this.spatialSound) {
  36390. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36391. if (this._isDirectional) {
  36392. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  36393. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  36394. this._soundPanner.coneOuterGain = this._coneOuterGain;
  36395. if (this._connectedMesh) {
  36396. this._updateDirection();
  36397. }
  36398. else {
  36399. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  36400. }
  36401. }
  36402. }
  36403. }
  36404. if (this._streaming) {
  36405. if (!this._streamingSource) {
  36406. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  36407. this._htmlAudioElement.onended = function () { _this._onended(); };
  36408. this._htmlAudioElement.playbackRate = this._playbackRate;
  36409. }
  36410. this._streamingSource.disconnect();
  36411. this._streamingSource.connect(this._inputAudioNode);
  36412. this._htmlAudioElement.play();
  36413. }
  36414. else {
  36415. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  36416. this._soundSource.buffer = this._audioBuffer;
  36417. this._soundSource.connect(this._inputAudioNode);
  36418. this._soundSource.loop = this.loop;
  36419. this._soundSource.playbackRate.value = this._playbackRate;
  36420. this._soundSource.onended = function () { _this._onended(); };
  36421. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  36422. }
  36423. this._startTime = startTime;
  36424. this.isPlaying = true;
  36425. this.isPaused = false;
  36426. }
  36427. catch (ex) {
  36428. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  36429. }
  36430. }
  36431. };
  36432. Sound.prototype._onended = function () {
  36433. this.isPlaying = false;
  36434. if (this.onended) {
  36435. this.onended();
  36436. }
  36437. };
  36438. /**
  36439. * Stop the sound
  36440. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  36441. */
  36442. Sound.prototype.stop = function (time) {
  36443. if (this.isPlaying) {
  36444. if (this._streaming) {
  36445. this._htmlAudioElement.pause();
  36446. // Test needed for Firefox or it will generate an Invalid State Error
  36447. if (this._htmlAudioElement.currentTime > 0) {
  36448. this._htmlAudioElement.currentTime = 0;
  36449. }
  36450. }
  36451. else {
  36452. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36453. this._soundSource.stop(stopTime);
  36454. this._soundSource.onended = null;
  36455. if (!this.isPaused) {
  36456. this._startOffset = 0;
  36457. }
  36458. }
  36459. this.isPlaying = false;
  36460. }
  36461. };
  36462. Sound.prototype.pause = function () {
  36463. if (this.isPlaying) {
  36464. this.isPaused = true;
  36465. if (this._streaming) {
  36466. this._htmlAudioElement.pause();
  36467. }
  36468. else {
  36469. this.stop(0);
  36470. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  36471. }
  36472. }
  36473. };
  36474. Sound.prototype.setVolume = function (newVolume, time) {
  36475. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36476. if (time) {
  36477. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  36478. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  36479. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  36480. }
  36481. else {
  36482. this._soundGain.gain.value = newVolume;
  36483. }
  36484. }
  36485. this._volume = newVolume;
  36486. };
  36487. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  36488. this._playbackRate = newPlaybackRate;
  36489. if (this.isPlaying) {
  36490. if (this._streaming) {
  36491. this._htmlAudioElement.playbackRate = this._playbackRate;
  36492. }
  36493. else {
  36494. this._soundSource.playbackRate.value = this._playbackRate;
  36495. }
  36496. }
  36497. };
  36498. Sound.prototype.getVolume = function () {
  36499. return this._volume;
  36500. };
  36501. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  36502. var _this = this;
  36503. if (this._connectedMesh) {
  36504. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36505. this._registerFunc = null;
  36506. }
  36507. this._connectedMesh = meshToConnectTo;
  36508. if (!this.spatialSound) {
  36509. this.spatialSound = true;
  36510. this._createSpatialParameters();
  36511. if (this.isPlaying && this.loop) {
  36512. this.stop();
  36513. this.play();
  36514. }
  36515. }
  36516. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  36517. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  36518. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  36519. };
  36520. Sound.prototype.detachFromMesh = function () {
  36521. if (this._connectedMesh) {
  36522. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36523. this._registerFunc = null;
  36524. this._connectedMesh = null;
  36525. }
  36526. };
  36527. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  36528. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  36529. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  36530. this._updateDirection();
  36531. }
  36532. };
  36533. Sound.prototype.clone = function () {
  36534. var _this = this;
  36535. if (!this._streaming) {
  36536. var setBufferAndRun = function () {
  36537. if (_this._isReadyToPlay) {
  36538. clonedSound._audioBuffer = _this.getAudioBuffer();
  36539. clonedSound._isReadyToPlay = true;
  36540. if (clonedSound.autoplay) {
  36541. clonedSound.play();
  36542. }
  36543. }
  36544. else {
  36545. window.setTimeout(setBufferAndRun, 300);
  36546. }
  36547. };
  36548. var currentOptions = {
  36549. autoplay: this.autoplay, loop: this.loop,
  36550. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  36551. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  36552. refDistance: this.refDistance, distanceModel: this.distanceModel
  36553. };
  36554. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  36555. if (this.useCustomAttenuation) {
  36556. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  36557. }
  36558. clonedSound.setPosition(this._position);
  36559. clonedSound.setPlaybackRate(this._playbackRate);
  36560. setBufferAndRun();
  36561. return clonedSound;
  36562. }
  36563. else {
  36564. return null;
  36565. }
  36566. };
  36567. Sound.prototype.getAudioBuffer = function () {
  36568. return this._audioBuffer;
  36569. };
  36570. Sound.prototype.serialize = function () {
  36571. var serializationObject = {
  36572. name: this.name,
  36573. url: this.name,
  36574. autoplay: this.autoplay,
  36575. loop: this.loop,
  36576. volume: this._volume,
  36577. spatialSound: this.spatialSound,
  36578. maxDistance: this.maxDistance,
  36579. rolloffFactor: this.rolloffFactor,
  36580. refDistance: this.refDistance,
  36581. distanceModel: this.distanceModel,
  36582. playbackRate: this._playbackRate,
  36583. panningModel: this._panningModel,
  36584. soundTrackId: this.soundTrackId
  36585. };
  36586. if (this.spatialSound) {
  36587. if (this._connectedMesh)
  36588. serializationObject.connectedMeshId = this._connectedMesh.id;
  36589. serializationObject.position = this._position.asArray();
  36590. serializationObject.refDistance = this.refDistance;
  36591. serializationObject.distanceModel = this.distanceModel;
  36592. serializationObject.isDirectional = this._isDirectional;
  36593. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  36594. serializationObject.coneInnerAngle = this._coneInnerAngle;
  36595. serializationObject.coneOuterAngle = this._coneOuterAngle;
  36596. serializationObject.coneOuterGain = this._coneOuterGain;
  36597. }
  36598. return serializationObject;
  36599. };
  36600. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  36601. var soundName = parsedSound.name;
  36602. var soundUrl;
  36603. if (parsedSound.url) {
  36604. soundUrl = rootUrl + parsedSound.url;
  36605. }
  36606. else {
  36607. soundUrl = rootUrl + soundName;
  36608. }
  36609. var options = {
  36610. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  36611. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  36612. rolloffFactor: parsedSound.rolloffFactor,
  36613. refDistance: parsedSound.refDistance,
  36614. distanceModel: parsedSound.distanceModel,
  36615. playbackRate: parsedSound.playbackRate
  36616. };
  36617. var newSound;
  36618. if (!sourceSound) {
  36619. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  36620. scene._addPendingData(newSound);
  36621. }
  36622. else {
  36623. var setBufferAndRun = function () {
  36624. if (sourceSound._isReadyToPlay) {
  36625. newSound._audioBuffer = sourceSound.getAudioBuffer();
  36626. newSound._isReadyToPlay = true;
  36627. if (newSound.autoplay) {
  36628. newSound.play();
  36629. }
  36630. }
  36631. else {
  36632. window.setTimeout(setBufferAndRun, 300);
  36633. }
  36634. };
  36635. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  36636. setBufferAndRun();
  36637. }
  36638. if (parsedSound.position) {
  36639. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  36640. newSound.setPosition(soundPosition);
  36641. }
  36642. if (parsedSound.isDirectional) {
  36643. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  36644. if (parsedSound.localDirectionToMesh) {
  36645. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  36646. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  36647. }
  36648. }
  36649. if (parsedSound.connectedMeshId) {
  36650. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  36651. if (connectedMesh) {
  36652. newSound.attachToMesh(connectedMesh);
  36653. }
  36654. }
  36655. return newSound;
  36656. };
  36657. return Sound;
  36658. }());
  36659. BABYLON.Sound = Sound;
  36660. })(BABYLON || (BABYLON = {}));
  36661. var BABYLON;
  36662. (function (BABYLON) {
  36663. var SoundTrack = (function () {
  36664. function SoundTrack(scene, options) {
  36665. this.id = -1;
  36666. this._isMainTrack = false;
  36667. this._isInitialized = false;
  36668. this._scene = scene;
  36669. this.soundCollection = new Array();
  36670. this._options = options;
  36671. if (!this._isMainTrack) {
  36672. this._scene.soundTracks.push(this);
  36673. this.id = this._scene.soundTracks.length - 1;
  36674. }
  36675. }
  36676. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  36677. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36678. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  36679. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  36680. if (this._options) {
  36681. if (this._options.volume) {
  36682. this._outputAudioNode.gain.value = this._options.volume;
  36683. }
  36684. if (this._options.mainTrack) {
  36685. this._isMainTrack = this._options.mainTrack;
  36686. }
  36687. }
  36688. this._isInitialized = true;
  36689. }
  36690. };
  36691. SoundTrack.prototype.dispose = function () {
  36692. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36693. if (this._connectedAnalyser) {
  36694. this._connectedAnalyser.stopDebugCanvas();
  36695. }
  36696. while (this.soundCollection.length) {
  36697. this.soundCollection[0].dispose();
  36698. }
  36699. if (this._outputAudioNode) {
  36700. this._outputAudioNode.disconnect();
  36701. }
  36702. this._outputAudioNode = null;
  36703. }
  36704. };
  36705. SoundTrack.prototype.AddSound = function (sound) {
  36706. if (!this._isInitialized) {
  36707. this._initializeSoundTrackAudioGraph();
  36708. }
  36709. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36710. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  36711. }
  36712. if (sound.soundTrackId) {
  36713. if (sound.soundTrackId === -1) {
  36714. this._scene.mainSoundTrack.RemoveSound(sound);
  36715. }
  36716. else {
  36717. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  36718. }
  36719. }
  36720. this.soundCollection.push(sound);
  36721. sound.soundTrackId = this.id;
  36722. };
  36723. SoundTrack.prototype.RemoveSound = function (sound) {
  36724. var index = this.soundCollection.indexOf(sound);
  36725. if (index !== -1) {
  36726. this.soundCollection.splice(index, 1);
  36727. }
  36728. };
  36729. SoundTrack.prototype.setVolume = function (newVolume) {
  36730. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36731. this._outputAudioNode.gain.value = newVolume;
  36732. }
  36733. };
  36734. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  36735. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36736. for (var i = 0; i < this.soundCollection.length; i++) {
  36737. this.soundCollection[i].switchPanningModelToHRTF();
  36738. }
  36739. }
  36740. };
  36741. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  36742. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36743. for (var i = 0; i < this.soundCollection.length; i++) {
  36744. this.soundCollection[i].switchPanningModelToEqualPower();
  36745. }
  36746. }
  36747. };
  36748. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  36749. if (this._connectedAnalyser) {
  36750. this._connectedAnalyser.stopDebugCanvas();
  36751. }
  36752. this._connectedAnalyser = analyser;
  36753. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36754. this._outputAudioNode.disconnect();
  36755. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  36756. }
  36757. };
  36758. return SoundTrack;
  36759. }());
  36760. BABYLON.SoundTrack = SoundTrack;
  36761. })(BABYLON || (BABYLON = {}));
  36762. var BABYLON;
  36763. (function (BABYLON) {
  36764. /**
  36765. * Special Glow Blur post process only blurring the alpha channel
  36766. * It enforces keeping the most luminous color in the color channel.
  36767. */
  36768. var GlowBlurPostProcess = (function (_super) {
  36769. __extends(GlowBlurPostProcess, _super);
  36770. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  36771. var _this = this;
  36772. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36773. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  36774. this.direction = direction;
  36775. this.blurWidth = blurWidth;
  36776. this.onApplyObservable.add(function (effect) {
  36777. effect.setFloat2("screenSize", _this.width, _this.height);
  36778. effect.setVector2("direction", _this.direction);
  36779. effect.setFloat("blurWidth", _this.blurWidth);
  36780. });
  36781. }
  36782. return GlowBlurPostProcess;
  36783. }(BABYLON.PostProcess));
  36784. /**
  36785. * The highlight layer Helps adding a glow effect around a mesh.
  36786. *
  36787. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  36788. * glowy meshes to your scene.
  36789. *
  36790. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  36791. */
  36792. var HighlightLayer = (function () {
  36793. /**
  36794. * Instantiates a new highlight Layer and references it to the scene..
  36795. * @param name The name of the layer
  36796. * @param scene The scene to use the layer in
  36797. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  36798. */
  36799. function HighlightLayer(name, scene, options) {
  36800. this._vertexBuffers = {};
  36801. this._mainTextureDesiredSize = { width: 0, height: 0 };
  36802. this._meshes = {};
  36803. this._maxSize = 0;
  36804. this._shouldRender = false;
  36805. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  36806. this._excludedMeshes = {};
  36807. /**
  36808. * Specifies whether or not the inner glow is ACTIVE in the layer.
  36809. */
  36810. this.innerGlow = true;
  36811. /**
  36812. * Specifies whether or not the outer glow is ACTIVE in the layer.
  36813. */
  36814. this.outerGlow = true;
  36815. /**
  36816. * An event triggered when the highlight layer has been disposed.
  36817. * @type {BABYLON.Observable}
  36818. */
  36819. this.onDisposeObservable = new BABYLON.Observable();
  36820. /**
  36821. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  36822. * @type {BABYLON.Observable}
  36823. */
  36824. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  36825. /**
  36826. * An event triggered when the highlight layer is being blurred.
  36827. * @type {BABYLON.Observable}
  36828. */
  36829. this.onBeforeBlurObservable = new BABYLON.Observable();
  36830. /**
  36831. * An event triggered when the highlight layer has been blurred.
  36832. * @type {BABYLON.Observable}
  36833. */
  36834. this.onAfterBlurObservable = new BABYLON.Observable();
  36835. /**
  36836. * An event triggered when the glowing blurred texture is being merged in the scene.
  36837. * @type {BABYLON.Observable}
  36838. */
  36839. this.onBeforeComposeObservable = new BABYLON.Observable();
  36840. /**
  36841. * An event triggered when the glowing blurred texture has been merged in the scene.
  36842. * @type {BABYLON.Observable}
  36843. */
  36844. this.onAfterComposeObservable = new BABYLON.Observable();
  36845. /**
  36846. * An event triggered when the highlight layer changes its size.
  36847. * @type {BABYLON.Observable}
  36848. */
  36849. this.onSizeChangedObservable = new BABYLON.Observable();
  36850. this._scene = scene;
  36851. var engine = scene.getEngine();
  36852. this._engine = engine;
  36853. this._maxSize = this._engine.getCaps().maxTextureSize;
  36854. this._scene.highlightLayers.push(this);
  36855. // Warn on stencil.
  36856. if (!this._engine.isStencilEnable) {
  36857. 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 }");
  36858. }
  36859. // Adapt options
  36860. this._options = options || {
  36861. mainTextureRatio: 0.25,
  36862. blurTextureSizeRatio: 0.5,
  36863. blurHorizontalSize: 1,
  36864. blurVerticalSize: 1,
  36865. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  36866. };
  36867. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  36868. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  36869. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  36870. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  36871. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  36872. // VBO
  36873. var vertices = [];
  36874. vertices.push(1, 1);
  36875. vertices.push(-1, 1);
  36876. vertices.push(-1, -1);
  36877. vertices.push(1, -1);
  36878. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36879. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  36880. // Indices
  36881. var indices = [];
  36882. indices.push(0);
  36883. indices.push(1);
  36884. indices.push(2);
  36885. indices.push(0);
  36886. indices.push(2);
  36887. indices.push(3);
  36888. this._indexBuffer = engine.createIndexBuffer(indices);
  36889. // Effect
  36890. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  36891. // Render target
  36892. this.setMainTextureSize();
  36893. // Create Textures and post processes
  36894. this.createTextureAndPostProcesses();
  36895. }
  36896. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  36897. /**
  36898. * Gets the horizontal size of the blur.
  36899. */
  36900. get: function () {
  36901. return this._horizontalBlurPostprocess.blurWidth;
  36902. },
  36903. /**
  36904. * Specifies the horizontal size of the blur.
  36905. */
  36906. set: function (value) {
  36907. this._horizontalBlurPostprocess.blurWidth = value;
  36908. },
  36909. enumerable: true,
  36910. configurable: true
  36911. });
  36912. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  36913. /**
  36914. * Gets the vertical size of the blur.
  36915. */
  36916. get: function () {
  36917. return this._verticalBlurPostprocess.blurWidth;
  36918. },
  36919. /**
  36920. * Specifies the vertical size of the blur.
  36921. */
  36922. set: function (value) {
  36923. this._verticalBlurPostprocess.blurWidth = value;
  36924. },
  36925. enumerable: true,
  36926. configurable: true
  36927. });
  36928. Object.defineProperty(HighlightLayer.prototype, "camera", {
  36929. /**
  36930. * Gets the camera attached to the layer.
  36931. */
  36932. get: function () {
  36933. return this._options.camera;
  36934. },
  36935. enumerable: true,
  36936. configurable: true
  36937. });
  36938. /**
  36939. * Creates the render target textures and post processes used in the highlight layer.
  36940. */
  36941. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  36942. var _this = this;
  36943. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  36944. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  36945. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  36946. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  36947. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  36948. width: this._mainTextureDesiredSize.width,
  36949. height: this._mainTextureDesiredSize.height
  36950. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36951. this._mainTexture.activeCamera = this._options.camera;
  36952. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36953. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36954. this._mainTexture.anisotropicFilteringLevel = 1;
  36955. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36956. this._mainTexture.renderParticles = false;
  36957. this._mainTexture.renderList = null;
  36958. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  36959. width: blurTextureWidth,
  36960. height: blurTextureHeight
  36961. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36962. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36963. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36964. this._blurTexture.anisotropicFilteringLevel = 16;
  36965. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36966. this._blurTexture.renderParticles = false;
  36967. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36968. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  36969. effect.setTexture("textureSampler", _this._mainTexture);
  36970. });
  36971. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36972. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  36973. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  36974. });
  36975. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  36976. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  36977. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  36978. });
  36979. this._mainTexture.onAfterUnbindObservable.add(function () {
  36980. _this.onBeforeBlurObservable.notifyObservers(_this);
  36981. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  36982. _this.onAfterBlurObservable.notifyObservers(_this);
  36983. });
  36984. // Custom render function
  36985. var renderSubMesh = function (subMesh) {
  36986. var mesh = subMesh.getRenderingMesh();
  36987. var scene = _this._scene;
  36988. var engine = scene.getEngine();
  36989. // Culling
  36990. engine.setState(subMesh.getMaterial().backFaceCulling);
  36991. // Managing instances
  36992. var batch = mesh._getInstancesRenderList(subMesh._id);
  36993. if (batch.mustReturn) {
  36994. return;
  36995. }
  36996. // Excluded Mesh
  36997. if (_this._excludedMeshes[mesh.id]) {
  36998. return;
  36999. }
  37000. ;
  37001. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37002. var highlightLayerMesh = _this._meshes[mesh.id];
  37003. var material = subMesh.getMaterial();
  37004. var emissiveTexture = null;
  37005. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  37006. emissiveTexture = material.emissiveTexture;
  37007. }
  37008. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  37009. engine.enableEffect(_this._glowMapGenerationEffect);
  37010. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  37011. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  37012. if (highlightLayerMesh) {
  37013. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  37014. }
  37015. else {
  37016. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  37017. }
  37018. // Alpha test
  37019. if (material && material.needAlphaTesting()) {
  37020. var alphaTexture = material.getAlphaTestTexture();
  37021. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  37022. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37023. }
  37024. // Glow emissive only
  37025. if (emissiveTexture) {
  37026. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  37027. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  37028. }
  37029. // Bones
  37030. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37031. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37032. }
  37033. // Draw
  37034. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  37035. }
  37036. else {
  37037. // Need to reset refresh rate of the shadowMap
  37038. _this._mainTexture.resetRefreshCounter();
  37039. }
  37040. };
  37041. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  37042. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  37043. var index;
  37044. for (index = 0; index < opaqueSubMeshes.length; index++) {
  37045. renderSubMesh(opaqueSubMeshes.data[index]);
  37046. }
  37047. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  37048. renderSubMesh(alphaTestSubMeshes.data[index]);
  37049. }
  37050. for (index = 0; index < transparentSubMeshes.length; index++) {
  37051. renderSubMesh(transparentSubMeshes.data[index]);
  37052. }
  37053. };
  37054. this._mainTexture.onClearObservable.add(function (engine) {
  37055. engine.clear(HighlightLayer.neutralColor, true, true, true);
  37056. });
  37057. };
  37058. /**
  37059. * Checks for the readiness of the element composing the layer.
  37060. * @param subMesh the mesh to check for
  37061. * @param useInstances specify wether or not to use instances to render the mesh
  37062. * @param emissiveTexture the associated emissive texture used to generate the glow
  37063. * @return true if ready otherwise, false
  37064. */
  37065. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  37066. if (!subMesh.getMaterial().isReady()) {
  37067. return false;
  37068. }
  37069. var defines = [];
  37070. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37071. var mesh = subMesh.getMesh();
  37072. var material = subMesh.getMaterial();
  37073. var uv1 = false;
  37074. var uv2 = false;
  37075. // Alpha test
  37076. if (material && material.needAlphaTesting()) {
  37077. var alphaTexture = material.getAlphaTestTexture();
  37078. if (alphaTexture) {
  37079. defines.push("#define ALPHATEST");
  37080. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37081. alphaTexture.coordinatesIndex === 1) {
  37082. defines.push("#define DIFFUSEUV2");
  37083. uv2 = true;
  37084. }
  37085. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37086. defines.push("#define DIFFUSEUV1");
  37087. uv1 = true;
  37088. }
  37089. }
  37090. }
  37091. // Emissive
  37092. if (emissiveTexture) {
  37093. defines.push("#define EMISSIVE");
  37094. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37095. emissiveTexture.coordinatesIndex === 1) {
  37096. defines.push("#define EMISSIVEUV2");
  37097. uv2 = true;
  37098. }
  37099. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37100. defines.push("#define EMISSIVEUV1");
  37101. uv1 = true;
  37102. }
  37103. }
  37104. if (uv1) {
  37105. attribs.push(BABYLON.VertexBuffer.UVKind);
  37106. defines.push("#define UV1");
  37107. }
  37108. if (uv2) {
  37109. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37110. defines.push("#define UV2");
  37111. }
  37112. // Bones
  37113. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37114. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37115. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37116. if (mesh.numBoneInfluencers > 4) {
  37117. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37118. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37119. }
  37120. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37121. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37122. }
  37123. else {
  37124. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37125. }
  37126. // Instances
  37127. if (useInstances) {
  37128. defines.push("#define INSTANCES");
  37129. attribs.push("world0");
  37130. attribs.push("world1");
  37131. attribs.push("world2");
  37132. attribs.push("world3");
  37133. }
  37134. // Get correct effect
  37135. var join = defines.join("\n");
  37136. if (this._cachedDefines !== join) {
  37137. this._cachedDefines = join;
  37138. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  37139. }
  37140. return this._glowMapGenerationEffect.isReady();
  37141. };
  37142. /**
  37143. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  37144. */
  37145. HighlightLayer.prototype.render = function () {
  37146. var currentEffect = this._glowMapMergeEffect;
  37147. // Check
  37148. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  37149. return;
  37150. var engine = this._scene.getEngine();
  37151. this.onBeforeComposeObservable.notifyObservers(this);
  37152. // Render
  37153. engine.enableEffect(currentEffect);
  37154. engine.setState(false);
  37155. // Cache
  37156. var previousStencilBuffer = engine.getStencilBuffer();
  37157. var previousStencilFunction = engine.getStencilFunction();
  37158. var previousStencilMask = engine.getStencilMask();
  37159. var previousAlphaMode = engine.getAlphaMode();
  37160. // Texture
  37161. currentEffect.setTexture("textureSampler", this._blurTexture);
  37162. // VBOs
  37163. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  37164. // Draw order
  37165. engine.setAlphaMode(this._options.alphaBlendingMode);
  37166. engine.setStencilMask(0x00);
  37167. engine.setStencilBuffer(true);
  37168. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  37169. if (this.outerGlow) {
  37170. currentEffect.setFloat("offset", 0);
  37171. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  37172. engine.draw(true, 0, 6);
  37173. }
  37174. if (this.innerGlow) {
  37175. currentEffect.setFloat("offset", 1);
  37176. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  37177. engine.draw(true, 0, 6);
  37178. }
  37179. // Restore Cache
  37180. engine.setStencilFunction(previousStencilFunction);
  37181. engine.setStencilMask(previousStencilMask);
  37182. engine.setAlphaMode(previousAlphaMode);
  37183. engine.setStencilBuffer(previousStencilBuffer);
  37184. this.onAfterComposeObservable.notifyObservers(this);
  37185. // Handle size changes.
  37186. var size = this._mainTexture.getSize();
  37187. this.setMainTextureSize();
  37188. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  37189. // Recreate RTT and post processes on size change.
  37190. this.onSizeChangedObservable.notifyObservers(this);
  37191. this.disposeTextureAndPostProcesses();
  37192. this.createTextureAndPostProcesses();
  37193. }
  37194. };
  37195. /**
  37196. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  37197. * @param mesh The mesh to exclude from the highlight layer
  37198. */
  37199. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  37200. var meshExcluded = this._excludedMeshes[mesh.id];
  37201. if (!meshExcluded) {
  37202. this._excludedMeshes[mesh.id] = {
  37203. mesh: mesh,
  37204. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  37205. mesh.getEngine().setStencilBuffer(false);
  37206. }),
  37207. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  37208. mesh.getEngine().setStencilBuffer(true);
  37209. }),
  37210. };
  37211. }
  37212. };
  37213. /**
  37214. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  37215. * @param mesh The mesh to highlight
  37216. */
  37217. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  37218. var meshExcluded = this._excludedMeshes[mesh.id];
  37219. if (meshExcluded) {
  37220. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  37221. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  37222. }
  37223. this._excludedMeshes[mesh.id] = undefined;
  37224. };
  37225. /**
  37226. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  37227. * @param mesh The mesh to highlight
  37228. * @param color The color of the highlight
  37229. * @param glowEmissiveOnly Extract the glow from the emissive texture
  37230. */
  37231. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  37232. var _this = this;
  37233. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  37234. var meshHighlight = this._meshes[mesh.id];
  37235. if (meshHighlight) {
  37236. meshHighlight.color = color;
  37237. }
  37238. else {
  37239. this._meshes[mesh.id] = {
  37240. mesh: mesh,
  37241. color: color,
  37242. // Lambda required for capture due to Observable this context
  37243. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  37244. if (_this._excludedMeshes[mesh.id]) {
  37245. _this.defaultStencilReference(mesh);
  37246. }
  37247. else {
  37248. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  37249. }
  37250. }),
  37251. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  37252. glowEmissiveOnly: glowEmissiveOnly
  37253. };
  37254. }
  37255. this._shouldRender = true;
  37256. };
  37257. /**
  37258. * Remove a mesh from the highlight layer in order to make it stop glowing.
  37259. * @param mesh The mesh to highlight
  37260. */
  37261. HighlightLayer.prototype.removeMesh = function (mesh) {
  37262. var meshHighlight = this._meshes[mesh.id];
  37263. if (meshHighlight) {
  37264. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37265. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37266. }
  37267. this._meshes[mesh.id] = undefined;
  37268. this._shouldRender = false;
  37269. for (var meshHighlightToCheck in this._meshes) {
  37270. if (meshHighlightToCheck) {
  37271. this._shouldRender = true;
  37272. break;
  37273. }
  37274. }
  37275. };
  37276. /**
  37277. * Returns true if the layer contains information to display, otherwise false.
  37278. */
  37279. HighlightLayer.prototype.shouldRender = function () {
  37280. return this._shouldRender;
  37281. };
  37282. /**
  37283. * Sets the main texture desired size which is the closest power of two
  37284. * of the engine canvas size.
  37285. */
  37286. HighlightLayer.prototype.setMainTextureSize = function () {
  37287. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  37288. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  37289. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  37290. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  37291. };
  37292. /**
  37293. * Force the stencil to the normal expected value for none glowing parts
  37294. */
  37295. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  37296. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  37297. };
  37298. /**
  37299. * Dispose only the render target textures and post process.
  37300. */
  37301. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  37302. this._blurTexture.dispose();
  37303. this._mainTexture.dispose();
  37304. this._downSamplePostprocess.dispose();
  37305. this._horizontalBlurPostprocess.dispose();
  37306. this._verticalBlurPostprocess.dispose();
  37307. };
  37308. /**
  37309. * Dispose the highlight layer and free resources.
  37310. */
  37311. HighlightLayer.prototype.dispose = function () {
  37312. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37313. if (vertexBuffer) {
  37314. vertexBuffer.dispose();
  37315. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37316. }
  37317. if (this._indexBuffer) {
  37318. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37319. this._indexBuffer = null;
  37320. }
  37321. // Clean textures and post processes
  37322. this.disposeTextureAndPostProcesses();
  37323. // Clean mesh references
  37324. for (var id in this._meshes) {
  37325. var meshHighlight = this._meshes[id];
  37326. if (meshHighlight && meshHighlight.mesh) {
  37327. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37328. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37329. }
  37330. }
  37331. this._meshes = null;
  37332. for (var id in this._excludedMeshes) {
  37333. var meshHighlight = this._excludedMeshes[id];
  37334. if (meshHighlight) {
  37335. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  37336. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  37337. }
  37338. }
  37339. this._excludedMeshes = null;
  37340. // Remove from scene
  37341. var index = this._scene.highlightLayers.indexOf(this, 0);
  37342. if (index > -1) {
  37343. this._scene.highlightLayers.splice(index, 1);
  37344. }
  37345. // Callback
  37346. this.onDisposeObservable.notifyObservers(this);
  37347. this.onDisposeObservable.clear();
  37348. this.onBeforeRenderMainTextureObservable.clear();
  37349. this.onBeforeBlurObservable.clear();
  37350. this.onBeforeComposeObservable.clear();
  37351. this.onAfterComposeObservable.clear();
  37352. this.onSizeChangedObservable.clear();
  37353. };
  37354. /**
  37355. * The neutral color used during the preparation of the glow effect.
  37356. * This is black by default as the blend operation is a blend operation.
  37357. */
  37358. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  37359. /**
  37360. * Stencil value used for glowing meshes.
  37361. */
  37362. HighlightLayer.glowingMeshStencilReference = 0x02;
  37363. /**
  37364. * Stencil value used for the other meshes in the scene.
  37365. */
  37366. HighlightLayer.normalMeshStencilReference = 0x01;
  37367. return HighlightLayer;
  37368. }());
  37369. BABYLON.HighlightLayer = HighlightLayer;
  37370. })(BABYLON || (BABYLON = {}));
  37371. var BABYLON;
  37372. (function (BABYLON) {
  37373. var SIMDVector3 = (function () {
  37374. function SIMDVector3() {
  37375. }
  37376. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  37377. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  37378. };
  37379. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  37380. var m = transformation.m;
  37381. var m0 = SIMD.Float32x4.load(m, 0);
  37382. var m1 = SIMD.Float32x4.load(m, 4);
  37383. var m2 = SIMD.Float32x4.load(m, 8);
  37384. var m3 = SIMD.Float32x4.load(m, 12);
  37385. 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));
  37386. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  37387. result.x = SIMD.Float32x4.extractLane(r, 0);
  37388. result.y = SIMD.Float32x4.extractLane(r, 1);
  37389. result.z = SIMD.Float32x4.extractLane(r, 2);
  37390. };
  37391. return SIMDVector3;
  37392. }());
  37393. var SIMDMatrix = (function () {
  37394. function SIMDMatrix() {
  37395. }
  37396. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  37397. var tm = this.m;
  37398. var om = other.m;
  37399. var m0 = SIMD.Float32x4.load(om, 0);
  37400. var m1 = SIMD.Float32x4.load(om, 4);
  37401. var m2 = SIMD.Float32x4.load(om, 8);
  37402. var m3 = SIMD.Float32x4.load(om, 12);
  37403. for (var i = 0; i < 16; i += 4) {
  37404. 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)))));
  37405. }
  37406. return this;
  37407. };
  37408. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  37409. var src = this.m;
  37410. var dest = other.m;
  37411. // Load the 4 rows
  37412. var src0 = SIMD.Float32x4.load(src, 0);
  37413. var src1 = SIMD.Float32x4.load(src, 4);
  37414. var src2 = SIMD.Float32x4.load(src, 8);
  37415. var src3 = SIMD.Float32x4.load(src, 12);
  37416. // Transpose the source matrix. Sort of. Not a true transpose operation
  37417. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  37418. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  37419. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  37420. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  37421. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  37422. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  37423. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  37424. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  37425. // This is a true transposition, but it will lead to an incorrect result
  37426. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  37427. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  37428. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37429. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37430. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  37431. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  37432. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37433. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37434. // ----
  37435. tmp1 = SIMD.Float32x4.mul(row2, row3);
  37436. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37437. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  37438. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  37439. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37440. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  37441. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  37442. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  37443. // ----
  37444. tmp1 = SIMD.Float32x4.mul(row1, row2);
  37445. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37446. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  37447. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  37448. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37449. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  37450. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  37451. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  37452. // ----
  37453. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  37454. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37455. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  37456. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  37457. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  37458. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37459. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  37460. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  37461. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  37462. // ----
  37463. tmp1 = SIMD.Float32x4.mul(row0, row1);
  37464. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37465. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37466. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  37467. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37468. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37469. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  37470. // ----
  37471. tmp1 = SIMD.Float32x4.mul(row0, row3);
  37472. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37473. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  37474. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  37475. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37476. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  37477. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  37478. // ----
  37479. tmp1 = SIMD.Float32x4.mul(row0, row2);
  37480. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37481. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  37482. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  37483. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37484. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  37485. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  37486. // Compute determinant
  37487. var det = SIMD.Float32x4.mul(row0, minor0);
  37488. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  37489. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  37490. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  37491. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  37492. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  37493. // These shuffles aren't necessary if the faulty transposition is done
  37494. // up at the top of this function.
  37495. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  37496. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  37497. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  37498. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  37499. // Compute final values by multiplying with 1/det
  37500. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  37501. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  37502. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  37503. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  37504. return this;
  37505. };
  37506. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  37507. var out = result.m;
  37508. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  37509. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  37510. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  37511. // cc.kmVec3Subtract(f, pCenter, pEye);
  37512. var f = SIMD.Float32x4.sub(center, eye);
  37513. // cc.kmVec3Normalize(f, f);
  37514. var tmp = SIMD.Float32x4.mul(f, f);
  37515. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37516. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37517. // cc.kmVec3Assign(up, pUp);
  37518. // cc.kmVec3Normalize(up, up);
  37519. tmp = SIMD.Float32x4.mul(up, up);
  37520. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37521. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37522. // cc.kmVec3Cross(s, f, up);
  37523. 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)));
  37524. // cc.kmVec3Normalize(s, s);
  37525. tmp = SIMD.Float32x4.mul(s, s);
  37526. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37527. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37528. // cc.kmVec3Cross(u, s, f);
  37529. 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)));
  37530. // cc.kmVec3Normalize(s, s);
  37531. tmp = SIMD.Float32x4.mul(s, s);
  37532. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37533. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37534. var zero = SIMD.Float32x4.splat(0.0);
  37535. s = SIMD.Float32x4.neg(s);
  37536. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  37537. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  37538. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  37539. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  37540. 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);
  37541. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  37542. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  37543. 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)))));
  37544. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  37545. 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)))));
  37546. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  37547. 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)))));
  37548. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  37549. 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)))));
  37550. };
  37551. return SIMDMatrix;
  37552. }());
  37553. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  37554. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  37555. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  37556. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  37557. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  37558. var SIMDHelper = (function () {
  37559. function SIMDHelper() {
  37560. }
  37561. Object.defineProperty(SIMDHelper, "IsEnabled", {
  37562. get: function () {
  37563. return SIMDHelper._isEnabled;
  37564. },
  37565. enumerable: true,
  37566. configurable: true
  37567. });
  37568. SIMDHelper.DisableSIMD = function () {
  37569. // Replace functions
  37570. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  37571. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  37572. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  37573. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  37574. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  37575. SIMDHelper._isEnabled = false;
  37576. };
  37577. SIMDHelper.EnableSIMD = function () {
  37578. if (self.SIMD === undefined) {
  37579. return;
  37580. }
  37581. // check if polyfills needed
  37582. if (!self.Math.fround) {
  37583. self.Math.fround = (function (array) { return function (x) {
  37584. return array[0] = x, array[0];
  37585. }; })(new Float32Array(1));
  37586. }
  37587. if (!self.Math.imul) {
  37588. self.Math.imul = function (a, b) {
  37589. var ah = (a >>> 16) & 0xffff;
  37590. var al = a & 0xffff;
  37591. var bh = (b >>> 16) & 0xffff;
  37592. var bl = b & 0xffff;
  37593. // the shift by 0 fixes the sign on the high part
  37594. // the final |0 converts the unsigned value into a signed value
  37595. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  37596. };
  37597. }
  37598. // Replace functions
  37599. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  37600. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  37601. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  37602. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  37603. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  37604. SIMDHelper._isEnabled = true;
  37605. };
  37606. SIMDHelper._isEnabled = false;
  37607. return SIMDHelper;
  37608. }());
  37609. BABYLON.SIMDHelper = SIMDHelper;
  37610. })(BABYLON || (BABYLON = {}));
  37611. var BABYLON;
  37612. (function (BABYLON) {
  37613. /**
  37614. * This class describe a rectangle that were added to the map.
  37615. * You have access to its coordinates either in pixel or normalized (UV)
  37616. */
  37617. var PackedRect = (function () {
  37618. function PackedRect(root, parent, pos, size) {
  37619. this._pos = pos;
  37620. this._size = size;
  37621. this._root = root;
  37622. this._parent = parent;
  37623. }
  37624. Object.defineProperty(PackedRect.prototype, "pos", {
  37625. /**
  37626. * @returns the position of this node into the map
  37627. */
  37628. get: function () {
  37629. return this._pos;
  37630. },
  37631. enumerable: true,
  37632. configurable: true
  37633. });
  37634. Object.defineProperty(PackedRect.prototype, "contentSize", {
  37635. /**
  37636. * @returns the size of the rectangle this node handles
  37637. */
  37638. get: function () {
  37639. return this._contentSize;
  37640. },
  37641. enumerable: true,
  37642. configurable: true
  37643. });
  37644. Object.defineProperty(PackedRect.prototype, "UVs", {
  37645. /**
  37646. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  37647. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  37648. */
  37649. get: function () {
  37650. return this.getUVsForCustomSize(this._root._size);
  37651. },
  37652. enumerable: true,
  37653. configurable: true
  37654. });
  37655. /**
  37656. * 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.
  37657. * This method will return the UVs for this part by given the custom size of what you really use
  37658. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  37659. */
  37660. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  37661. var mainWidth = this._root._size.width;
  37662. var mainHeight = this._root._size.height;
  37663. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  37664. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  37665. var uvs = new Array();
  37666. uvs.push(topLeft);
  37667. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  37668. uvs.push(rightBottom);
  37669. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  37670. return uvs;
  37671. };
  37672. /**
  37673. * Free this rectangle from the map.
  37674. * Call this method when you no longer need the rectangle to be in the map.
  37675. */
  37676. PackedRect.prototype.freeContent = function () {
  37677. if (!this.contentSize) {
  37678. return;
  37679. }
  37680. this._contentSize = null;
  37681. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  37682. this.attemptDefrag();
  37683. };
  37684. Object.defineProperty(PackedRect.prototype, "isUsed", {
  37685. get: function () {
  37686. return this._contentSize != null || this._leftNode != null;
  37687. },
  37688. enumerable: true,
  37689. configurable: true
  37690. });
  37691. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  37692. var node = this.findNode(contentSize);
  37693. // Not enough space...
  37694. if (!node) {
  37695. return null;
  37696. }
  37697. node.splitNode(contentSize);
  37698. return node;
  37699. };
  37700. PackedRect.prototype.findNode = function (size) {
  37701. var resNode = null;
  37702. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  37703. if (this.isUsed) {
  37704. if (this._leftNode) {
  37705. resNode = this._leftNode.findNode(size);
  37706. }
  37707. if (!resNode && this._rightNode) {
  37708. resNode = this._rightNode.findNode(size);
  37709. }
  37710. if (!resNode && this._bottomNode) {
  37711. resNode = this._bottomNode.findNode(size);
  37712. }
  37713. }
  37714. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  37715. resNode = this;
  37716. }
  37717. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  37718. resNode = this;
  37719. }
  37720. return resNode;
  37721. };
  37722. PackedRect.prototype.splitNode = function (contentSize) {
  37723. // 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)
  37724. if (!this._contentSize && this._initialSize) {
  37725. 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));
  37726. return this._leftNode.splitNode(contentSize);
  37727. }
  37728. else {
  37729. this._contentSize = contentSize.clone();
  37730. this._initialSize = contentSize.clone();
  37731. if (contentSize.width !== this._size.width) {
  37732. 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));
  37733. }
  37734. if (contentSize.height !== this._size.height) {
  37735. 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));
  37736. }
  37737. return this;
  37738. }
  37739. };
  37740. PackedRect.prototype.attemptDefrag = function () {
  37741. if (!this.isUsed && this.isRecursiveFree) {
  37742. this.clearNode();
  37743. if (this._parent) {
  37744. this._parent.attemptDefrag();
  37745. }
  37746. }
  37747. };
  37748. PackedRect.prototype.clearNode = function () {
  37749. this._initialSize = null;
  37750. this._rightNode = null;
  37751. this._bottomNode = null;
  37752. };
  37753. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  37754. get: function () {
  37755. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  37756. },
  37757. enumerable: true,
  37758. configurable: true
  37759. });
  37760. PackedRect.prototype.evalFreeSize = function (size) {
  37761. var levelSize = 0;
  37762. if (!this.isUsed) {
  37763. if (this._initialSize) {
  37764. levelSize = this._initialSize.surface;
  37765. }
  37766. else {
  37767. levelSize = this._size.surface;
  37768. }
  37769. }
  37770. if (this._rightNode) {
  37771. levelSize += this._rightNode.evalFreeSize(0);
  37772. }
  37773. if (this._bottomNode) {
  37774. levelSize += this._bottomNode.evalFreeSize(0);
  37775. }
  37776. return levelSize + size;
  37777. };
  37778. return PackedRect;
  37779. }());
  37780. BABYLON.PackedRect = PackedRect;
  37781. /**
  37782. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  37783. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  37784. * 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.
  37785. */
  37786. var RectPackingMap = (function (_super) {
  37787. __extends(RectPackingMap, _super);
  37788. /**
  37789. * Create an instance of the object with a dimension using the given size
  37790. * @param size The dimension of the rectangle that will contain all the sub ones.
  37791. */
  37792. function RectPackingMap(size) {
  37793. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  37794. this._root = this;
  37795. }
  37796. /**
  37797. * Add a rectangle, finding the best location to store it into the map
  37798. * @param size the dimension of the rectangle to store
  37799. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  37800. */
  37801. RectPackingMap.prototype.addRect = function (size) {
  37802. var node = this.findAndSplitNode(size);
  37803. return node;
  37804. };
  37805. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  37806. /**
  37807. * Return the current space free normalized between [0;1]
  37808. * @returns {}
  37809. */
  37810. get: function () {
  37811. var freeSize = 0;
  37812. freeSize = this.evalFreeSize(freeSize);
  37813. return freeSize / (this._size.width * this._size.height);
  37814. },
  37815. enumerable: true,
  37816. configurable: true
  37817. });
  37818. return RectPackingMap;
  37819. }(PackedRect));
  37820. BABYLON.RectPackingMap = RectPackingMap;
  37821. })(BABYLON || (BABYLON = {}));
  37822. var BABYLON;
  37823. (function (BABYLON) {
  37824. var DynamicFloatArrayElementInfo = (function () {
  37825. function DynamicFloatArrayElementInfo() {
  37826. }
  37827. return DynamicFloatArrayElementInfo;
  37828. }());
  37829. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  37830. /**
  37831. * 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.
  37832. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  37833. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  37834. * 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.
  37835. * 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.
  37836. * 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".
  37837. */
  37838. var DynamicFloatArray = (function () {
  37839. /**
  37840. * Construct an instance of the dynamic float array
  37841. * @param stride size of one element in float (i.e. not bytes!)
  37842. * @param initialElementCount the number of available entries at construction
  37843. */
  37844. function DynamicFloatArray(stride, initialElementCount) {
  37845. this.compareValueOffset = null;
  37846. this.sortingAscending = true;
  37847. this._stride = stride;
  37848. this.buffer = new Float32Array(stride * initialElementCount);
  37849. this._lastUsed = 0;
  37850. this._firstFree = 0;
  37851. this._allEntries = new Array(initialElementCount);
  37852. this._freeEntries = new Array(initialElementCount);
  37853. for (var i = 0; i < initialElementCount; i++) {
  37854. var element = new DynamicFloatArrayElementInfo();
  37855. element.offset = i * stride;
  37856. this._allEntries[i] = element;
  37857. this._freeEntries[initialElementCount - i - 1] = element;
  37858. }
  37859. }
  37860. /**
  37861. * Allocate an element in the array.
  37862. * @return the element info instance that contains the offset into the main buffer of the element's location.
  37863. * Beware, this offset may change when you call pack()
  37864. */
  37865. DynamicFloatArray.prototype.allocElement = function () {
  37866. if (this._freeEntries.length === 0) {
  37867. this._growBuffer();
  37868. }
  37869. var el = this._freeEntries.pop();
  37870. this._lastUsed = Math.max(el.offset, this._lastUsed);
  37871. if (el.offset === this._firstFree) {
  37872. if (this._freeEntries.length > 0) {
  37873. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  37874. }
  37875. else {
  37876. this._firstFree += this._stride;
  37877. }
  37878. }
  37879. return el;
  37880. };
  37881. /**
  37882. * Free the element corresponding to the given element info
  37883. * @param elInfo the element that describe the allocated element
  37884. */
  37885. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  37886. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  37887. this._freeEntries.push(elInfo);
  37888. };
  37889. /**
  37890. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  37891. * 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().
  37892. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  37893. */
  37894. DynamicFloatArray.prototype.pack = function () {
  37895. // no free slot? no need to pack
  37896. if (this._freeEntries.length === 0) {
  37897. return this.buffer;
  37898. }
  37899. // If the buffer is already packed the last used will always be lower than the first free
  37900. // 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.
  37901. if (this._lastUsed < this._firstFree) {
  37902. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  37903. return elementsBuffer_1;
  37904. }
  37905. var s = this._stride;
  37906. // 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
  37907. var lastFree = new DynamicFloatArrayElementInfo();
  37908. lastFree.offset = this.totalElementCount * s;
  37909. this._freeEntries.push(lastFree);
  37910. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  37911. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37912. var firstFreeSlotOffset = sortedFree[0].offset;
  37913. var freeZoneSize = 1;
  37914. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  37915. var prevOffset = sortedFree[0].offset;
  37916. for (var i = 1; i < sortedFree.length; i++) {
  37917. // 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
  37918. if (firstFreeSlotOffset >= occupiedZoneSize) {
  37919. break;
  37920. }
  37921. var curFree = sortedFree[i];
  37922. var curOffset = curFree.offset;
  37923. // Compute the distance between this offset and the previous
  37924. var distance = curOffset - prevOffset;
  37925. // If the distance is the stride size, they are adjacent, it good, move to the next
  37926. if (distance === s) {
  37927. // Free zone is one element bigger
  37928. ++freeZoneSize;
  37929. // as we're about to iterate to the next, the cur becomes the previous...
  37930. prevOffset = curOffset;
  37931. continue;
  37932. }
  37933. // Distance is bigger, which means there's x element between the previous free and this one
  37934. var usedRange = (distance / s) - 1;
  37935. // Two cases the free zone is smaller than the data to move or bigger
  37936. // Copy what can fit in the free zone
  37937. var curMoveOffset = curOffset - s;
  37938. var copyCount = Math.min(freeZoneSize, usedRange);
  37939. for (var j = 0; j < copyCount; j++) {
  37940. var freeI = firstFreeSlotOffset / s;
  37941. var curI = curMoveOffset / s;
  37942. var moveEl = sortedAll[curI];
  37943. this._moveElement(moveEl, firstFreeSlotOffset);
  37944. var replacedEl = sortedAll[freeI];
  37945. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  37946. replacedEl.offset = curMoveOffset;
  37947. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  37948. sortedAll[freeI] = moveEl;
  37949. sortedAll[curI] = replacedEl;
  37950. curMoveOffset -= s;
  37951. firstFreeSlotOffset += s;
  37952. }
  37953. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  37954. if (freeZoneSize <= usedRange) {
  37955. firstFreeSlotOffset = curMoveOffset + s;
  37956. freeZoneSize = 1 + copyCount;
  37957. }
  37958. else {
  37959. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  37960. }
  37961. // as we're about to iterate to the next, the cur becomes the previous...
  37962. prevOffset = curOffset;
  37963. }
  37964. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  37965. this._lastUsed = firstFreeSlotOffset - s;
  37966. this._firstFree = firstFreeSlotOffset;
  37967. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  37968. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  37969. this._allEntries = sortedAll;
  37970. return elementsBuffer;
  37971. };
  37972. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  37973. for (var i = 0; i < this._stride; i++) {
  37974. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  37975. }
  37976. element.offset = destOffset;
  37977. };
  37978. DynamicFloatArray.prototype._growBuffer = function () {
  37979. // Allocate the new buffer with 50% more entries, copy the content of the current one
  37980. var newElCount = Math.floor(this.totalElementCount * 1.5);
  37981. var newBuffer = new Float32Array(newElCount * this._stride);
  37982. newBuffer.set(this.buffer);
  37983. var curCount = this.totalElementCount;
  37984. var addedCount = newElCount - this.totalElementCount;
  37985. for (var i = 0; i < addedCount; i++) {
  37986. var element = new DynamicFloatArrayElementInfo();
  37987. element.offset = (curCount + i) * this.stride;
  37988. this._allEntries.push(element);
  37989. this._freeEntries[addedCount - i - 1] = element;
  37990. }
  37991. this._firstFree = curCount * this.stride;
  37992. this.buffer = newBuffer;
  37993. };
  37994. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  37995. /**
  37996. * Get the total count of entries that can fit in the current buffer
  37997. * @returns the elements count
  37998. */
  37999. get: function () {
  38000. return this._allEntries.length;
  38001. },
  38002. enumerable: true,
  38003. configurable: true
  38004. });
  38005. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  38006. /**
  38007. * Get the count of free entries that can still be allocated without resizing the buffer
  38008. * @returns the free elements count
  38009. */
  38010. get: function () {
  38011. return this._freeEntries.length;
  38012. },
  38013. enumerable: true,
  38014. configurable: true
  38015. });
  38016. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  38017. /**
  38018. * Get the count of allocated elements
  38019. * @returns the allocated elements count
  38020. */
  38021. get: function () {
  38022. return this._allEntries.length - this._freeEntries.length;
  38023. },
  38024. enumerable: true,
  38025. configurable: true
  38026. });
  38027. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  38028. /**
  38029. * Return the size of one element in float
  38030. * @returns the size in float
  38031. */
  38032. get: function () {
  38033. return this._stride;
  38034. },
  38035. enumerable: true,
  38036. configurable: true
  38037. });
  38038. DynamicFloatArray.prototype.sort = function () {
  38039. var _this = this;
  38040. if (!this.compareValueOffset) {
  38041. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  38042. }
  38043. var count = this.usedElementCount;
  38044. // Do we have to (re)create the sort table?
  38045. if (!this._sortTable || this._sortTable.length < count) {
  38046. // 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...
  38047. var newCount = Math.min(this.totalElementCount, count * 2);
  38048. this._sortTable = new Array(newCount);
  38049. }
  38050. if (!this._sortedTable || this._sortedTable.length !== count) {
  38051. this._sortedTable = new Array(count);
  38052. }
  38053. // Because, you know...
  38054. this.pack();
  38055. //let stride = this.stride;
  38056. //for (let i = 0; i < count; i++) {
  38057. // let si = this._sortTable[i];
  38058. // if (!si) {
  38059. // si = new SortInfo();
  38060. // this._sortTable[i] = si;
  38061. // }
  38062. // si.entry = this._allEntries[i];
  38063. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  38064. // si.swapedOffset = null;
  38065. // this._sortedTable[i] = si;
  38066. //}
  38067. var curOffset = 0;
  38068. var stride = this.stride;
  38069. for (var i = 0; i < count; i++, curOffset += stride) {
  38070. var si = this._sortTable[i];
  38071. if (!si) {
  38072. si = new SortInfo();
  38073. this._sortTable[i] = si;
  38074. }
  38075. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  38076. si.offset = curOffset;
  38077. si.swapedOffset = null;
  38078. this._sortedTable[i] = si;
  38079. }
  38080. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  38081. if (this.sortingAscending) {
  38082. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  38083. }
  38084. else {
  38085. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  38086. }
  38087. var swapElements = function (src, dst) {
  38088. for (var i = 0; i < stride; i++) {
  38089. var tps = _this.buffer[dst + i];
  38090. _this.buffer[dst + i] = _this.buffer[src + i];
  38091. _this.buffer[src + i] = tps;
  38092. }
  38093. };
  38094. // 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:
  38095. // 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),
  38096. // and I still want something with a good algorithm complexity.
  38097. // 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,
  38098. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  38099. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  38100. // 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
  38101. // until we find a SortInfo object without a swapedOffset which means we got the right location
  38102. // 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
  38103. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  38104. for (var i = 0; i < count; i++) {
  38105. // Get the element to move
  38106. var sourceSI = this._sortedTable[i];
  38107. var destSI = this._sortTable[i];
  38108. var sourceOff = sourceSI.offset;
  38109. // If the source changed location, find the new one
  38110. if (sourceSI.swapedOffset) {
  38111. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  38112. var curSI = sourceSI;
  38113. while (curSI.swapedOffset) {
  38114. curSI = this._sortTable[curSI.swapedOffset / stride];
  38115. }
  38116. // Finally get the right location
  38117. sourceOff = curSI.offset;
  38118. }
  38119. // Tag the element being replaced with its new location
  38120. destSI.swapedOffset = sourceOff;
  38121. // Swap elements (only if needed)
  38122. if (sourceOff !== destSI.offset) {
  38123. swapElements(sourceOff, destSI.offset);
  38124. }
  38125. // Update the offset in the corresponding DFAE
  38126. //sourceSI.entry.offset = destSI.entry.offset;
  38127. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  38128. }
  38129. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  38130. return true;
  38131. };
  38132. return DynamicFloatArray;
  38133. }());
  38134. BABYLON.DynamicFloatArray = DynamicFloatArray;
  38135. var SortInfo = (function () {
  38136. function SortInfo() {
  38137. this.compareData = this.offset = this.swapedOffset = null;
  38138. }
  38139. return SortInfo;
  38140. }());
  38141. })(BABYLON || (BABYLON = {}));
  38142. var BABYLON;
  38143. (function (BABYLON) {
  38144. /**
  38145. * This class given information about a given character.
  38146. */
  38147. var CharInfo = (function () {
  38148. function CharInfo() {
  38149. }
  38150. return CharInfo;
  38151. }());
  38152. BABYLON.CharInfo = CharInfo;
  38153. var FontTexture = (function (_super) {
  38154. __extends(FontTexture, _super);
  38155. /**
  38156. * Create a new instance of the FontTexture class
  38157. * @param name the name of the texture
  38158. * @param font the font to use, use the W3C CSS notation
  38159. * @param scene the scene that owns the texture
  38160. * @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
  38161. * @param samplingMode the texture sampling mode
  38162. * @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.
  38163. */
  38164. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  38165. if (maxCharCount === void 0) { maxCharCount = 200; }
  38166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38167. if (superSample === void 0) { superSample = false; }
  38168. _super.call(this, null, scene, true, false, samplingMode);
  38169. this._charInfos = {};
  38170. this._curCharCount = 0;
  38171. this._lastUpdateCharCount = -1;
  38172. this._usedCounter = 1;
  38173. this.name = name;
  38174. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38175. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38176. this._superSample = false;
  38177. if (superSample) {
  38178. var sfont = this.getSuperSampleFont(font);
  38179. if (sfont) {
  38180. this._superSample = true;
  38181. font = sfont;
  38182. }
  38183. }
  38184. // First canvas creation to determine the size of the texture to create
  38185. this._canvas = document.createElement("canvas");
  38186. this._context = this._canvas.getContext("2d");
  38187. this._context.font = font;
  38188. this._context.fillStyle = "white";
  38189. this._cachedFontId = null;
  38190. var res = this.getFontHeight(font);
  38191. this._lineHeightSuper = res.height;
  38192. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  38193. this._offset = res.offset - 1;
  38194. var maxCharWidth = this._context.measureText("W").width;
  38195. this._spaceWidthSuper = this._context.measureText(" ").width;
  38196. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  38197. // This is an approximate size, but should always be able to fit at least the maxCharCount
  38198. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  38199. var edge = Math.sqrt(totalEstSurface);
  38200. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  38201. // Create the texture that will store the font characters
  38202. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  38203. var textureSize = this.getSize();
  38204. this.hasAlpha = true;
  38205. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  38206. this._canvas = document.createElement("canvas");
  38207. this._canvas.width = textureSize.width;
  38208. this._canvas.height = textureSize.height;
  38209. this._context = this._canvas.getContext("2d");
  38210. this._context.textBaseline = "top";
  38211. this._context.font = font;
  38212. this._context.fillStyle = "white";
  38213. this._context.imageSmoothingEnabled = false;
  38214. this._currentFreePosition = BABYLON.Vector2.Zero();
  38215. // Add the basic ASCII based characters
  38216. for (var i = 0x20; i < 0x7F; i++) {
  38217. var c = String.fromCharCode(i);
  38218. this.getChar(c);
  38219. }
  38220. this.update();
  38221. }
  38222. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  38223. get: function () {
  38224. return this._superSample;
  38225. },
  38226. enumerable: true,
  38227. configurable: true
  38228. });
  38229. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  38230. get: function () {
  38231. return this._spaceWidth;
  38232. },
  38233. enumerable: true,
  38234. configurable: true
  38235. });
  38236. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  38237. get: function () {
  38238. return this._lineHeight;
  38239. },
  38240. enumerable: true,
  38241. configurable: true
  38242. });
  38243. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  38244. if (supersample === void 0) { supersample = false; }
  38245. var s = scene;
  38246. if (!s.__fontTextureCache__) {
  38247. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  38248. }
  38249. var dic = s.__fontTextureCache__;
  38250. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  38251. var ft = dic.get(lfn);
  38252. if (ft) {
  38253. ++ft._usedCounter;
  38254. return ft;
  38255. }
  38256. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  38257. ft._cachedFontId = lfn;
  38258. dic.add(lfn, ft);
  38259. return ft;
  38260. };
  38261. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  38262. if (supersample === void 0) { supersample = false; }
  38263. var s = scene;
  38264. var dic = s.__fontTextureCache__;
  38265. if (!dic) {
  38266. return;
  38267. }
  38268. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  38269. var font = dic.get(lfn);
  38270. if (--font._usedCounter === 0) {
  38271. dic.remove(lfn);
  38272. font.dispose();
  38273. }
  38274. };
  38275. /**
  38276. * Make sure the given char is present in the font map.
  38277. * @param char the character to get or add
  38278. * @return the CharInfo instance corresponding to the given character
  38279. */
  38280. FontTexture.prototype.getChar = function (char) {
  38281. if (char.length !== 1) {
  38282. return null;
  38283. }
  38284. var info = this._charInfos[char];
  38285. if (info) {
  38286. return info;
  38287. }
  38288. info = new CharInfo();
  38289. var measure = this._context.measureText(char);
  38290. var textureSize = this.getSize();
  38291. // we reached the end of the current line?
  38292. var width = Math.round(measure.width);
  38293. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  38294. var yMargin = xMargin;
  38295. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  38296. this._currentFreePosition.x = 0;
  38297. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  38298. // No more room?
  38299. if (this._currentFreePosition.y > textureSize.height) {
  38300. return this.getChar("!");
  38301. }
  38302. }
  38303. // Draw the character in the texture
  38304. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  38305. // Fill the CharInfo object
  38306. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  38307. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  38308. info.charWidth = this._superSample ? (width / 2) : width;
  38309. // Add the info structure
  38310. this._charInfos[char] = info;
  38311. this._curCharCount++;
  38312. // Set the next position
  38313. this._currentFreePosition.x += width + xMargin;
  38314. return info;
  38315. };
  38316. FontTexture.prototype.measureText = function (text, tabulationSize) {
  38317. if (tabulationSize === void 0) { tabulationSize = 4; }
  38318. var maxWidth = 0;
  38319. var curWidth = 0;
  38320. var lineCount = 1;
  38321. var charxpos = 0;
  38322. // Parse each char of the string
  38323. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  38324. var char = text_1[_i];
  38325. // Next line feed?
  38326. if (char === "\n") {
  38327. maxWidth = Math.max(maxWidth, curWidth);
  38328. charxpos = 0;
  38329. curWidth = 0;
  38330. ++lineCount;
  38331. continue;
  38332. }
  38333. // Tabulation ?
  38334. if (char === "\t") {
  38335. var nextPos = charxpos + tabulationSize;
  38336. nextPos = nextPos - (nextPos % tabulationSize);
  38337. curWidth += (nextPos - charxpos) * this.spaceWidth;
  38338. charxpos = nextPos;
  38339. continue;
  38340. }
  38341. if (char < " ") {
  38342. continue;
  38343. }
  38344. curWidth += this.getChar(char).charWidth;
  38345. ++charxpos;
  38346. }
  38347. maxWidth = Math.max(maxWidth, curWidth);
  38348. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  38349. };
  38350. FontTexture.prototype.getSuperSampleFont = function (font) {
  38351. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  38352. 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*$/;
  38353. var res = font.toLocaleLowerCase().match(regex);
  38354. if (res == null) {
  38355. return null;
  38356. }
  38357. var size = parseInt(res[4]);
  38358. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  38359. var newFont = "";
  38360. for (var j = 1; j < res.length; j++) {
  38361. if (res[j] != null) {
  38362. newFont += res[j] + " ";
  38363. }
  38364. }
  38365. return newFont;
  38366. };
  38367. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  38368. FontTexture.prototype.getFontHeight = function (font) {
  38369. var fontDraw = document.createElement("canvas");
  38370. var ctx = fontDraw.getContext('2d');
  38371. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  38372. ctx.textBaseline = 'top';
  38373. ctx.fillStyle = 'white';
  38374. ctx.font = font;
  38375. ctx.fillText('jH|', 0, 0);
  38376. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  38377. var start = -1;
  38378. var end = -1;
  38379. for (var row = 0; row < fontDraw.height; row++) {
  38380. for (var column = 0; column < fontDraw.width; column++) {
  38381. var index = (row * fontDraw.width + column) * 4;
  38382. if (pixels[index] === 0) {
  38383. if (column === fontDraw.width - 1 && start !== -1) {
  38384. end = row;
  38385. row = fontDraw.height;
  38386. break;
  38387. }
  38388. continue;
  38389. }
  38390. else {
  38391. if (start === -1) {
  38392. start = row;
  38393. }
  38394. break;
  38395. }
  38396. }
  38397. }
  38398. return { height: (end - start) + 1, offset: start - 1 };
  38399. };
  38400. Object.defineProperty(FontTexture.prototype, "canRescale", {
  38401. get: function () {
  38402. return false;
  38403. },
  38404. enumerable: true,
  38405. configurable: true
  38406. });
  38407. FontTexture.prototype.getContext = function () {
  38408. return this._context;
  38409. };
  38410. /**
  38411. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  38412. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  38413. */
  38414. FontTexture.prototype.update = function () {
  38415. // Update only if there's new char added since the previous update
  38416. if (this._lastUpdateCharCount < this._curCharCount) {
  38417. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  38418. this._lastUpdateCharCount = this._curCharCount;
  38419. }
  38420. };
  38421. // cloning should be prohibited, there's no point to duplicate this texture at all
  38422. FontTexture.prototype.clone = function () {
  38423. return null;
  38424. };
  38425. /**
  38426. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  38427. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  38428. */
  38429. FontTexture.prototype.incCachedFontTextureCounter = function () {
  38430. ++this._usedCounter;
  38431. };
  38432. /**
  38433. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  38434. */
  38435. FontTexture.prototype.decCachedFontTextureCounter = function () {
  38436. var s = this.getScene();
  38437. var dic = s.__fontTextureCache__;
  38438. if (!dic) {
  38439. return;
  38440. }
  38441. if (--this._usedCounter === 0) {
  38442. dic.remove(this._cachedFontId);
  38443. this.dispose();
  38444. }
  38445. };
  38446. return FontTexture;
  38447. }(BABYLON.Texture));
  38448. BABYLON.FontTexture = FontTexture;
  38449. })(BABYLON || (BABYLON = {}));
  38450. var BABYLON;
  38451. (function (BABYLON) {
  38452. var MapTexture = (function (_super) {
  38453. __extends(MapTexture, _super);
  38454. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  38455. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38456. if (useMipMap === void 0) { useMipMap = false; }
  38457. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  38458. this.name = name;
  38459. this._size = size;
  38460. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38461. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38462. // Create the rectPackMap that will allocate portion of the texture
  38463. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  38464. // Create the texture that will store the content
  38465. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  38466. }
  38467. /**
  38468. * Allocate a rectangle of a given size in the texture map
  38469. * @param size the size of the rectangle to allocation
  38470. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  38471. */
  38472. MapTexture.prototype.allocateRect = function (size) {
  38473. return this._rectPackingMap.addRect(size);
  38474. };
  38475. /**
  38476. * Free a given rectangle from the texture map
  38477. * @param rectInfo the instance corresponding to the rect to free.
  38478. */
  38479. MapTexture.prototype.freeRect = function (rectInfo) {
  38480. if (rectInfo) {
  38481. rectInfo.freeContent();
  38482. }
  38483. };
  38484. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  38485. /**
  38486. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  38487. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  38488. * @returns {}
  38489. */
  38490. get: function () {
  38491. return this._rectPackingMap.freeSpace;
  38492. },
  38493. enumerable: true,
  38494. configurable: true
  38495. });
  38496. /**
  38497. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  38498. * 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.
  38499. * Don't forget to call unbindTexture when you're done rendering
  38500. * @param rect the zone to render to
  38501. * @param clear true to clear the portion's color/depth data
  38502. */
  38503. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  38504. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  38505. };
  38506. /**
  38507. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  38508. * 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.
  38509. * Don't forget to call unbindTexture when you're done rendering
  38510. * @param pos the position into the texture
  38511. * @param size the portion to fit the clip space to
  38512. * @param clear true to clear the portion's color/depth data
  38513. */
  38514. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  38515. var engine = this.getScene().getEngine();
  38516. engine.bindFramebuffer(this._texture);
  38517. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  38518. if (clear) {
  38519. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  38520. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  38521. }
  38522. };
  38523. /**
  38524. * Unbind the texture map from the rendering engine.
  38525. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  38526. * @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.
  38527. */
  38528. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  38529. // Dump ?
  38530. if (dumpForDebug) {
  38531. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  38532. }
  38533. var engine = this.getScene().getEngine();
  38534. if (this._replacedViewport) {
  38535. engine.setViewport(this._replacedViewport);
  38536. this._replacedViewport = null;
  38537. }
  38538. engine.unBindFramebuffer(this._texture);
  38539. };
  38540. Object.defineProperty(MapTexture.prototype, "canRescale", {
  38541. get: function () {
  38542. return false;
  38543. },
  38544. enumerable: true,
  38545. configurable: true
  38546. });
  38547. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  38548. // Anyway, there's not much point to use this method for this kind of texture I guess
  38549. MapTexture.prototype.clone = function () {
  38550. return null;
  38551. };
  38552. return MapTexture;
  38553. }(BABYLON.Texture));
  38554. BABYLON.MapTexture = MapTexture;
  38555. })(BABYLON || (BABYLON = {}));
  38556. var BABYLON;
  38557. (function (BABYLON) {
  38558. var ShaderMaterial = (function (_super) {
  38559. __extends(ShaderMaterial, _super);
  38560. function ShaderMaterial(name, scene, shaderPath, options) {
  38561. _super.call(this, name, scene);
  38562. this._textures = {};
  38563. this._textureArrays = {};
  38564. this._floats = {};
  38565. this._floatsArrays = {};
  38566. this._colors3 = {};
  38567. this._colors4 = {};
  38568. this._vectors2 = {};
  38569. this._vectors3 = {};
  38570. this._vectors4 = {};
  38571. this._matrices = {};
  38572. this._matrices3x3 = {};
  38573. this._matrices2x2 = {};
  38574. this._vectors3Arrays = {};
  38575. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  38576. this._shaderPath = shaderPath;
  38577. options.needAlphaBlending = options.needAlphaBlending || false;
  38578. options.needAlphaTesting = options.needAlphaTesting || false;
  38579. options.attributes = options.attributes || ["position", "normal", "uv"];
  38580. options.uniforms = options.uniforms || ["worldViewProjection"];
  38581. options.samplers = options.samplers || [];
  38582. options.defines = options.defines || [];
  38583. this._options = options;
  38584. }
  38585. ShaderMaterial.prototype.needAlphaBlending = function () {
  38586. return this._options.needAlphaBlending;
  38587. };
  38588. ShaderMaterial.prototype.needAlphaTesting = function () {
  38589. return this._options.needAlphaTesting;
  38590. };
  38591. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  38592. if (this._options.uniforms.indexOf(uniformName) === -1) {
  38593. this._options.uniforms.push(uniformName);
  38594. }
  38595. };
  38596. ShaderMaterial.prototype.setTexture = function (name, texture) {
  38597. if (this._options.samplers.indexOf(name) === -1) {
  38598. this._options.samplers.push(name);
  38599. }
  38600. this._textures[name] = texture;
  38601. return this;
  38602. };
  38603. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  38604. if (this._options.samplers.indexOf(name) === -1) {
  38605. this._options.samplers.push(name);
  38606. }
  38607. this._checkUniform(name);
  38608. this._textureArrays[name] = textures;
  38609. return this;
  38610. };
  38611. ShaderMaterial.prototype.setFloat = function (name, value) {
  38612. this._checkUniform(name);
  38613. this._floats[name] = value;
  38614. return this;
  38615. };
  38616. ShaderMaterial.prototype.setFloats = function (name, value) {
  38617. this._checkUniform(name);
  38618. this._floatsArrays[name] = value;
  38619. return this;
  38620. };
  38621. ShaderMaterial.prototype.setColor3 = function (name, value) {
  38622. this._checkUniform(name);
  38623. this._colors3[name] = value;
  38624. return this;
  38625. };
  38626. ShaderMaterial.prototype.setColor4 = function (name, value) {
  38627. this._checkUniform(name);
  38628. this._colors4[name] = value;
  38629. return this;
  38630. };
  38631. ShaderMaterial.prototype.setVector2 = function (name, value) {
  38632. this._checkUniform(name);
  38633. this._vectors2[name] = value;
  38634. return this;
  38635. };
  38636. ShaderMaterial.prototype.setVector3 = function (name, value) {
  38637. this._checkUniform(name);
  38638. this._vectors3[name] = value;
  38639. return this;
  38640. };
  38641. ShaderMaterial.prototype.setVector4 = function (name, value) {
  38642. this._checkUniform(name);
  38643. this._vectors4[name] = value;
  38644. return this;
  38645. };
  38646. ShaderMaterial.prototype.setMatrix = function (name, value) {
  38647. this._checkUniform(name);
  38648. this._matrices[name] = value;
  38649. return this;
  38650. };
  38651. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  38652. this._checkUniform(name);
  38653. this._matrices3x3[name] = value;
  38654. return this;
  38655. };
  38656. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  38657. this._checkUniform(name);
  38658. this._matrices2x2[name] = value;
  38659. return this;
  38660. };
  38661. ShaderMaterial.prototype.setArray3 = function (name, value) {
  38662. this._checkUniform(name);
  38663. this._vectors3Arrays[name] = value;
  38664. return this;
  38665. };
  38666. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  38667. var scene = this.getScene();
  38668. var engine = scene.getEngine();
  38669. if (!this.checkReadyOnEveryCall) {
  38670. if (this._renderId === scene.getRenderId()) {
  38671. return true;
  38672. }
  38673. }
  38674. // Instances
  38675. var defines = [];
  38676. var fallbacks = new BABYLON.EffectFallbacks();
  38677. if (useInstances) {
  38678. defines.push("#define INSTANCES");
  38679. }
  38680. for (var index = 0; index < this._options.defines.length; index++) {
  38681. defines.push(this._options.defines[index]);
  38682. }
  38683. // Bones
  38684. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  38685. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38686. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38687. fallbacks.addCPUSkinningFallback(0, mesh);
  38688. }
  38689. // Alpha test
  38690. if (engine.getAlphaTesting()) {
  38691. defines.push("#define ALPHATEST");
  38692. }
  38693. var previousEffect = this._effect;
  38694. var join = defines.join("\n");
  38695. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  38696. if (!this._effect.isReady()) {
  38697. return false;
  38698. }
  38699. if (previousEffect !== this._effect) {
  38700. scene.resetCachedMaterial();
  38701. }
  38702. this._renderId = scene.getRenderId();
  38703. return true;
  38704. };
  38705. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38706. var scene = this.getScene();
  38707. if (this._options.uniforms.indexOf("world") !== -1) {
  38708. this._effect.setMatrix("world", world);
  38709. }
  38710. if (this._options.uniforms.indexOf("worldView") !== -1) {
  38711. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  38712. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  38713. }
  38714. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  38715. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  38716. }
  38717. };
  38718. ShaderMaterial.prototype.bind = function (world, mesh) {
  38719. // Std values
  38720. this.bindOnlyWorldMatrix(world);
  38721. if (this.getScene().getCachedMaterial() !== this) {
  38722. if (this._options.uniforms.indexOf("view") !== -1) {
  38723. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  38724. }
  38725. if (this._options.uniforms.indexOf("projection") !== -1) {
  38726. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  38727. }
  38728. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  38729. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  38730. }
  38731. // Bones
  38732. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  38733. var name;
  38734. // Texture
  38735. for (name in this._textures) {
  38736. this._effect.setTexture(name, this._textures[name]);
  38737. }
  38738. // Texture arrays
  38739. for (name in this._textureArrays) {
  38740. this._effect.setTextureArray(name, this._textureArrays[name]);
  38741. }
  38742. // Float
  38743. for (name in this._floats) {
  38744. this._effect.setFloat(name, this._floats[name]);
  38745. }
  38746. // Float s
  38747. for (name in this._floatsArrays) {
  38748. this._effect.setArray(name, this._floatsArrays[name]);
  38749. }
  38750. // Color3
  38751. for (name in this._colors3) {
  38752. this._effect.setColor3(name, this._colors3[name]);
  38753. }
  38754. // Color4
  38755. for (name in this._colors4) {
  38756. var color = this._colors4[name];
  38757. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  38758. }
  38759. // Vector2
  38760. for (name in this._vectors2) {
  38761. this._effect.setVector2(name, this._vectors2[name]);
  38762. }
  38763. // Vector3
  38764. for (name in this._vectors3) {
  38765. this._effect.setVector3(name, this._vectors3[name]);
  38766. }
  38767. // Vector4
  38768. for (name in this._vectors4) {
  38769. this._effect.setVector4(name, this._vectors4[name]);
  38770. }
  38771. // Matrix
  38772. for (name in this._matrices) {
  38773. this._effect.setMatrix(name, this._matrices[name]);
  38774. }
  38775. // Matrix 3x3
  38776. for (name in this._matrices3x3) {
  38777. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  38778. }
  38779. // Matrix 2x2
  38780. for (name in this._matrices2x2) {
  38781. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  38782. }
  38783. // Vector3Array
  38784. for (name in this._vectors3Arrays) {
  38785. this._effect.setArray3(name, this._vectors3Arrays[name]);
  38786. }
  38787. }
  38788. _super.prototype.bind.call(this, world, mesh);
  38789. };
  38790. ShaderMaterial.prototype.clone = function (name) {
  38791. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  38792. return newShaderMaterial;
  38793. };
  38794. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38795. if (forceDisposeTextures) {
  38796. var name;
  38797. for (name in this._textures) {
  38798. this._textures[name].dispose();
  38799. }
  38800. for (name in this._textureArrays) {
  38801. var array = this._textureArrays[name];
  38802. for (var index = 0; index < array.length; index++) {
  38803. array[index].dispose();
  38804. }
  38805. }
  38806. }
  38807. this._textures = {};
  38808. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38809. };
  38810. ShaderMaterial.prototype.serialize = function () {
  38811. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38812. serializationObject.customType = "BABYLON.ShaderMaterial";
  38813. serializationObject.options = this._options;
  38814. serializationObject.shaderPath = this._shaderPath;
  38815. var name;
  38816. // Texture
  38817. serializationObject.textures = {};
  38818. for (name in this._textures) {
  38819. serializationObject.textures[name] = this._textures[name].serialize();
  38820. }
  38821. // Texture arrays
  38822. serializationObject.textureArrays = {};
  38823. for (name in this._textureArrays) {
  38824. serializationObject.textureArrays[name] = [];
  38825. var array = this._textureArrays[name];
  38826. for (var index = 0; index < array.length; index++) {
  38827. serializationObject.textureArrays[name].push(array[index].serialize());
  38828. }
  38829. }
  38830. // Float
  38831. serializationObject.floats = {};
  38832. for (name in this._floats) {
  38833. serializationObject.floats[name] = this._floats[name];
  38834. }
  38835. // Float s
  38836. serializationObject.floatArrays = {};
  38837. for (name in this._floatsArrays) {
  38838. serializationObject.floatArrays[name] = this._floatsArrays[name];
  38839. }
  38840. // Color3
  38841. serializationObject.colors3 = {};
  38842. for (name in this._colors3) {
  38843. serializationObject.colors3[name] = this._colors3[name].asArray();
  38844. }
  38845. // Color4
  38846. serializationObject.colors4 = {};
  38847. for (name in this._colors4) {
  38848. serializationObject.colors4[name] = this._colors4[name].asArray();
  38849. }
  38850. // Vector2
  38851. serializationObject.vectors2 = {};
  38852. for (name in this._vectors2) {
  38853. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  38854. }
  38855. // Vector3
  38856. serializationObject.vectors3 = {};
  38857. for (name in this._vectors3) {
  38858. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  38859. }
  38860. // Vector4
  38861. serializationObject.vectors4 = {};
  38862. for (name in this._vectors4) {
  38863. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  38864. }
  38865. // Matrix
  38866. serializationObject.matrices = {};
  38867. for (name in this._matrices) {
  38868. serializationObject.matrices[name] = this._matrices[name].asArray();
  38869. }
  38870. // Matrix 3x3
  38871. serializationObject.matrices3x3 = {};
  38872. for (name in this._matrices3x3) {
  38873. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  38874. }
  38875. // Matrix 2x2
  38876. serializationObject.matrices2x2 = {};
  38877. for (name in this._matrices2x2) {
  38878. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  38879. }
  38880. // Vector3Array
  38881. serializationObject.vectors3Arrays = {};
  38882. for (name in this._vectors3Arrays) {
  38883. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  38884. }
  38885. return serializationObject;
  38886. };
  38887. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  38888. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  38889. var name;
  38890. // Texture
  38891. for (name in source.textures) {
  38892. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  38893. }
  38894. // Texture arrays
  38895. for (name in source.textureArrays) {
  38896. var array = source.textureArrays[name];
  38897. var textureArray = new Array();
  38898. for (var index = 0; index < array.length; index++) {
  38899. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  38900. }
  38901. material.setTextureArray(name, textureArray);
  38902. }
  38903. // Float
  38904. for (name in source.floats) {
  38905. material.setFloat(name, source.floats[name]);
  38906. }
  38907. // Float s
  38908. for (name in source.floatsArrays) {
  38909. material.setFloats(name, source.floatsArrays[name]);
  38910. }
  38911. // Color3
  38912. for (name in source.colors3) {
  38913. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  38914. }
  38915. // Color4
  38916. for (name in source.colors4) {
  38917. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  38918. }
  38919. // Vector2
  38920. for (name in source.vectors2) {
  38921. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  38922. }
  38923. // Vector3
  38924. for (name in source.vectors3) {
  38925. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  38926. }
  38927. // Vector4
  38928. for (name in source.vectors4) {
  38929. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  38930. }
  38931. // Matrix
  38932. for (name in source.matrices) {
  38933. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  38934. }
  38935. // Matrix 3x3
  38936. for (name in source.matrices3x3) {
  38937. material.setMatrix3x3(name, source.matrices3x3[name]);
  38938. }
  38939. // Matrix 2x2
  38940. for (name in source.matrices2x2) {
  38941. material.setMatrix2x2(name, source.matrices2x2[name]);
  38942. }
  38943. // Vector3Array
  38944. for (name in source.vectors3Arrays) {
  38945. material.setArray3(name, source.vectors3Arrays[name]);
  38946. }
  38947. return material;
  38948. };
  38949. return ShaderMaterial;
  38950. }(BABYLON.Material));
  38951. BABYLON.ShaderMaterial = ShaderMaterial;
  38952. })(BABYLON || (BABYLON = {}));
  38953. var BABYLON;
  38954. (function (BABYLON) {
  38955. var Internals;
  38956. (function (Internals) {
  38957. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  38958. // All values and structures referenced from:
  38959. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  38960. var DDS_MAGIC = 0x20534444;
  38961. 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;
  38962. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  38963. 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;
  38964. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  38965. function FourCCToInt32(value) {
  38966. return value.charCodeAt(0) +
  38967. (value.charCodeAt(1) << 8) +
  38968. (value.charCodeAt(2) << 16) +
  38969. (value.charCodeAt(3) << 24);
  38970. }
  38971. function Int32ToFourCC(value) {
  38972. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  38973. }
  38974. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  38975. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  38976. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  38977. var headerLengthInt = 31; // The header length in 32 bit ints
  38978. // Offsets into the header array
  38979. var off_magic = 0;
  38980. var off_size = 1;
  38981. var off_flags = 2;
  38982. var off_height = 3;
  38983. var off_width = 4;
  38984. var off_mipmapCount = 7;
  38985. var off_pfFlags = 20;
  38986. var off_pfFourCC = 21;
  38987. var off_RGBbpp = 22;
  38988. var off_RMask = 23;
  38989. var off_GMask = 24;
  38990. var off_BMask = 25;
  38991. var off_AMask = 26;
  38992. var off_caps1 = 27;
  38993. var off_caps2 = 28;
  38994. ;
  38995. var DDSTools = (function () {
  38996. function DDSTools() {
  38997. }
  38998. DDSTools.GetDDSInfo = function (arrayBuffer) {
  38999. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  39000. var mipmapCount = 1;
  39001. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  39002. mipmapCount = Math.max(1, header[off_mipmapCount]);
  39003. }
  39004. return {
  39005. width: header[off_width],
  39006. height: header[off_height],
  39007. mipmapCount: mipmapCount,
  39008. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  39009. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  39010. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  39011. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  39012. };
  39013. };
  39014. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39015. var byteArray = new Uint8Array(dataLength);
  39016. var srcData = new Uint8Array(arrayBuffer);
  39017. var index = 0;
  39018. for (var y = height - 1; y >= 0; y--) {
  39019. for (var x = 0; x < width; x++) {
  39020. var srcPos = dataOffset + (x + y * width) * 4;
  39021. byteArray[index + 2] = srcData[srcPos];
  39022. byteArray[index + 1] = srcData[srcPos + 1];
  39023. byteArray[index] = srcData[srcPos + 2];
  39024. byteArray[index + 3] = srcData[srcPos + 3];
  39025. index += 4;
  39026. }
  39027. }
  39028. return byteArray;
  39029. };
  39030. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39031. var byteArray = new Uint8Array(dataLength);
  39032. var srcData = new Uint8Array(arrayBuffer);
  39033. var index = 0;
  39034. for (var y = height - 1; y >= 0; y--) {
  39035. for (var x = 0; x < width; x++) {
  39036. var srcPos = dataOffset + (x + y * width) * 3;
  39037. byteArray[index + 2] = srcData[srcPos];
  39038. byteArray[index + 1] = srcData[srcPos + 1];
  39039. byteArray[index] = srcData[srcPos + 2];
  39040. index += 3;
  39041. }
  39042. }
  39043. return byteArray;
  39044. };
  39045. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39046. var byteArray = new Uint8Array(dataLength);
  39047. var srcData = new Uint8Array(arrayBuffer);
  39048. var index = 0;
  39049. for (var y = height - 1; y >= 0; y--) {
  39050. for (var x = 0; x < width; x++) {
  39051. var srcPos = dataOffset + (x + y * width);
  39052. byteArray[index] = srcData[srcPos];
  39053. index++;
  39054. }
  39055. }
  39056. return byteArray;
  39057. };
  39058. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  39059. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  39060. if (header[off_magic] != DDS_MAGIC) {
  39061. BABYLON.Tools.Error("Invalid magic number in DDS header");
  39062. return;
  39063. }
  39064. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  39065. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  39066. return;
  39067. }
  39068. if (info.isFourCC) {
  39069. fourCC = header[off_pfFourCC];
  39070. switch (fourCC) {
  39071. case FOURCC_DXT1:
  39072. blockBytes = 8;
  39073. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39074. break;
  39075. case FOURCC_DXT3:
  39076. blockBytes = 16;
  39077. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39078. break;
  39079. case FOURCC_DXT5:
  39080. blockBytes = 16;
  39081. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39082. break;
  39083. default:
  39084. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  39085. return;
  39086. }
  39087. }
  39088. mipmapCount = 1;
  39089. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  39090. mipmapCount = Math.max(1, header[off_mipmapCount]);
  39091. }
  39092. var bpp = header[off_RGBbpp];
  39093. for (var face = 0; face < faces; face++) {
  39094. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  39095. width = header[off_width];
  39096. height = header[off_height];
  39097. dataOffset = header[off_size] + 4;
  39098. for (i = 0; i < mipmapCount; ++i) {
  39099. if (info.isRGB) {
  39100. if (bpp === 24) {
  39101. dataLength = width * height * 3;
  39102. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39103. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  39104. }
  39105. else {
  39106. dataLength = width * height * 4;
  39107. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39108. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  39109. }
  39110. }
  39111. else if (info.isLuminance) {
  39112. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  39113. var unpaddedRowSize = width;
  39114. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  39115. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  39116. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39117. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  39118. }
  39119. else {
  39120. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  39121. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  39122. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  39123. }
  39124. dataOffset += dataLength;
  39125. width *= 0.5;
  39126. height *= 0.5;
  39127. width = Math.max(1.0, width);
  39128. height = Math.max(1.0, height);
  39129. }
  39130. }
  39131. };
  39132. return DDSTools;
  39133. }());
  39134. Internals.DDSTools = DDSTools;
  39135. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39136. })(BABYLON || (BABYLON = {}));
  39137. var BABYLON;
  39138. (function (BABYLON) {
  39139. var CannonJSPlugin = (function () {
  39140. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  39141. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  39142. if (iterations === void 0) { iterations = 10; }
  39143. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  39144. this.name = "CannonJSPlugin";
  39145. this._physicsMaterials = [];
  39146. this._fixedTimeStep = 1 / 60;
  39147. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  39148. this._currentCollisionGroup = 2;
  39149. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  39150. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  39151. this._tmpPosition = BABYLON.Vector3.Zero();
  39152. this._tmpQuaternion = new BABYLON.Quaternion();
  39153. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  39154. this._tmpDeltaRotation = new BABYLON.Quaternion();
  39155. this._tmpUnityRotation = new BABYLON.Quaternion();
  39156. if (!this.isSupported()) {
  39157. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  39158. return;
  39159. }
  39160. this.world = new CANNON.World();
  39161. this.world.broadphase = new CANNON.NaiveBroadphase();
  39162. this.world.solver.iterations = iterations;
  39163. }
  39164. CannonJSPlugin.prototype.setGravity = function (gravity) {
  39165. this.world.gravity.copy(gravity);
  39166. };
  39167. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  39168. this._fixedTimeStep = timeStep;
  39169. };
  39170. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  39171. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  39172. };
  39173. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  39174. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  39175. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  39176. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  39177. };
  39178. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  39179. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  39180. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  39181. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  39182. };
  39183. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  39184. //parent-child relationship. Does this impostor has a parent impostor?
  39185. if (impostor.parent) {
  39186. if (impostor.physicsBody) {
  39187. this.removePhysicsBody(impostor);
  39188. //TODO is that needed?
  39189. impostor.forceUpdate();
  39190. }
  39191. return;
  39192. }
  39193. //should a new body be created for this impostor?
  39194. if (impostor.isBodyInitRequired()) {
  39195. var shape = this._createShape(impostor);
  39196. //unregister events, if body is being changed
  39197. var oldBody = impostor.physicsBody;
  39198. if (oldBody) {
  39199. this.removePhysicsBody(impostor);
  39200. }
  39201. //create the body and material
  39202. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  39203. var bodyCreationObject = {
  39204. mass: impostor.getParam("mass"),
  39205. material: material
  39206. };
  39207. // A simple extend, in case native options were used.
  39208. var nativeOptions = impostor.getParam("nativeOptions");
  39209. for (var key in nativeOptions) {
  39210. if (nativeOptions.hasOwnProperty(key)) {
  39211. bodyCreationObject[key] = nativeOptions[key];
  39212. }
  39213. }
  39214. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  39215. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  39216. this.world.addEventListener("preStep", impostor.beforeStep);
  39217. this.world.addEventListener("postStep", impostor.afterStep);
  39218. impostor.physicsBody.addShape(shape);
  39219. this.world.add(impostor.physicsBody);
  39220. //try to keep the body moving in the right direction by taking old properties.
  39221. //Should be tested!
  39222. if (oldBody) {
  39223. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  39224. impostor.physicsBody[param].copy(oldBody[param]);
  39225. });
  39226. }
  39227. this._processChildMeshes(impostor);
  39228. }
  39229. //now update the body's transformation
  39230. this._updatePhysicsBodyTransformation(impostor);
  39231. };
  39232. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  39233. var _this = this;
  39234. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  39235. if (meshChildren.length) {
  39236. var processMesh = function (localPosition, mesh) {
  39237. var childImpostor = mesh.getPhysicsImpostor();
  39238. if (childImpostor) {
  39239. var parent = childImpostor.parent;
  39240. if (parent !== mainImpostor) {
  39241. var localPosition = mesh.position;
  39242. if (childImpostor.physicsBody) {
  39243. _this.removePhysicsBody(childImpostor);
  39244. childImpostor.physicsBody = null;
  39245. }
  39246. childImpostor.parent = mainImpostor;
  39247. childImpostor.resetUpdateFlags();
  39248. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  39249. //Add the mass of the children.
  39250. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  39251. }
  39252. }
  39253. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  39254. };
  39255. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  39256. }
  39257. };
  39258. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  39259. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  39260. this.world.removeEventListener("preStep", impostor.beforeStep);
  39261. this.world.removeEventListener("postStep", impostor.afterStep);
  39262. this.world.remove(impostor.physicsBody);
  39263. };
  39264. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  39265. var mainBody = impostorJoint.mainImpostor.physicsBody;
  39266. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  39267. if (!mainBody || !connectedBody) {
  39268. return;
  39269. }
  39270. var constraint;
  39271. var jointData = impostorJoint.joint.jointData;
  39272. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  39273. var constraintData = {
  39274. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  39275. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  39276. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  39277. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  39278. maxForce: jointData.nativeParams.maxForce,
  39279. collideConnected: !!jointData.collision
  39280. };
  39281. //Not needed, Cannon has a collideConnected flag
  39282. /*if (!jointData.collision) {
  39283. //add 1st body to a collision group of its own, if it is not in 1
  39284. if (mainBody.collisionFilterGroup === 1) {
  39285. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  39286. this._currentCollisionGroup <<= 1;
  39287. }
  39288. if (connectedBody.collisionFilterGroup === 1) {
  39289. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  39290. this._currentCollisionGroup <<= 1;
  39291. }
  39292. //add their mask to the collisionFilterMask of each other:
  39293. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  39294. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  39295. }*/
  39296. switch (impostorJoint.joint.type) {
  39297. case BABYLON.PhysicsJoint.HingeJoint:
  39298. case BABYLON.PhysicsJoint.Hinge2Joint:
  39299. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  39300. break;
  39301. case BABYLON.PhysicsJoint.DistanceJoint:
  39302. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  39303. break;
  39304. case BABYLON.PhysicsJoint.SpringJoint:
  39305. var springData = jointData;
  39306. constraint = new CANNON.Spring(mainBody, connectedBody, {
  39307. restLength: springData.length,
  39308. stiffness: springData.stiffness,
  39309. damping: springData.damping,
  39310. localAnchorA: constraintData.pivotA,
  39311. localAnchorB: constraintData.pivotB
  39312. });
  39313. break;
  39314. case BABYLON.PhysicsJoint.LockJoint:
  39315. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  39316. break;
  39317. case BABYLON.PhysicsJoint.PointToPointJoint:
  39318. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  39319. default:
  39320. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  39321. break;
  39322. }
  39323. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  39324. constraint.collideConnected = !!jointData.collision;
  39325. impostorJoint.joint.physicsJoint = constraint;
  39326. //don't add spring as constraint, as it is not one.
  39327. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  39328. this.world.addConstraint(constraint);
  39329. }
  39330. else {
  39331. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  39332. constraint.applyForce();
  39333. });
  39334. }
  39335. };
  39336. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  39337. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  39338. };
  39339. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  39340. var index;
  39341. var mat;
  39342. for (index = 0; index < this._physicsMaterials.length; index++) {
  39343. mat = this._physicsMaterials[index];
  39344. if (mat.friction === friction && mat.restitution === restitution) {
  39345. return mat;
  39346. }
  39347. }
  39348. var currentMat = new CANNON.Material(name);
  39349. currentMat.friction = friction;
  39350. currentMat.restitution = restitution;
  39351. this._physicsMaterials.push(currentMat);
  39352. return currentMat;
  39353. };
  39354. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  39355. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  39356. };
  39357. CannonJSPlugin.prototype._createShape = function (impostor) {
  39358. var object = impostor.object;
  39359. var returnValue;
  39360. var extendSize = impostor.getObjectExtendSize();
  39361. switch (impostor.type) {
  39362. case BABYLON.PhysicsEngine.SphereImpostor:
  39363. var radiusX = extendSize.x;
  39364. var radiusY = extendSize.y;
  39365. var radiusZ = extendSize.z;
  39366. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  39367. break;
  39368. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  39369. case BABYLON.PhysicsImpostor.CylinderImpostor:
  39370. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  39371. break;
  39372. case BABYLON.PhysicsImpostor.BoxImpostor:
  39373. var box = extendSize.scale(0.5);
  39374. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  39375. break;
  39376. case BABYLON.PhysicsImpostor.PlaneImpostor:
  39377. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  39378. returnValue = new CANNON.Plane();
  39379. break;
  39380. case BABYLON.PhysicsImpostor.MeshImpostor:
  39381. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  39382. var rawFaces = object.getIndices ? object.getIndices() : [];
  39383. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  39384. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  39385. break;
  39386. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  39387. returnValue = this._createHeightmap(object);
  39388. break;
  39389. case BABYLON.PhysicsImpostor.ParticleImpostor:
  39390. returnValue = new CANNON.Particle();
  39391. break;
  39392. }
  39393. return returnValue;
  39394. };
  39395. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  39396. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39397. var matrix = [];
  39398. //For now pointDepth will not be used and will be automatically calculated.
  39399. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  39400. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  39401. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  39402. var elementSize = dim * 2 / arraySize;
  39403. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  39404. for (var i = 0; i < pos.length; i = i + 3) {
  39405. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  39406. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  39407. var y = pos[i + 1] + minY;
  39408. if (!matrix[x]) {
  39409. matrix[x] = [];
  39410. }
  39411. if (!matrix[x][z]) {
  39412. matrix[x][z] = y;
  39413. }
  39414. matrix[x][z] = Math.max(y, matrix[x][z]);
  39415. }
  39416. for (var x = 0; x <= arraySize; ++x) {
  39417. if (!matrix[x]) {
  39418. var loc = 1;
  39419. while (!matrix[(x + loc) % arraySize]) {
  39420. loc++;
  39421. }
  39422. matrix[x] = matrix[(x + loc) % arraySize].slice();
  39423. }
  39424. for (var z = 0; z <= arraySize; ++z) {
  39425. if (!matrix[x][z]) {
  39426. var loc = 1;
  39427. var newValue;
  39428. while (newValue === undefined) {
  39429. newValue = matrix[x][(z + loc++) % arraySize];
  39430. }
  39431. matrix[x][z] = newValue;
  39432. }
  39433. }
  39434. }
  39435. var shape = new CANNON.Heightfield(matrix, {
  39436. elementSize: elementSize
  39437. });
  39438. //For future reference, needed for body transformation
  39439. shape.minY = minY;
  39440. return shape;
  39441. };
  39442. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  39443. var object = impostor.object;
  39444. //make sure it is updated...
  39445. object.computeWorldMatrix && object.computeWorldMatrix(true);
  39446. // The delta between the mesh position and the mesh bounding box center
  39447. var center = impostor.getObjectCenter();
  39448. var extendSize = impostor.getObjectExtendSize();
  39449. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  39450. this._tmpPosition.copyFrom(center);
  39451. var quaternion = object.rotationQuaternion;
  39452. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  39453. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  39454. //-90 DEG in X, precalculated
  39455. quaternion = quaternion.multiply(this._minus90X);
  39456. //Invert! (Precalculated, 90 deg in X)
  39457. //No need to clone. this will never change.
  39458. impostor.setDeltaRotation(this._plus90X);
  39459. }
  39460. //If it is a heightfield, if should be centered.
  39461. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  39462. var mesh = object;
  39463. //calculate the correct body position:
  39464. var rotationQuaternion = mesh.rotationQuaternion;
  39465. mesh.rotationQuaternion = this._tmpUnityRotation;
  39466. mesh.computeWorldMatrix(true);
  39467. //get original center with no rotation
  39468. var c = center.clone();
  39469. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  39470. //rotation is back
  39471. mesh.rotationQuaternion = rotationQuaternion;
  39472. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  39473. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  39474. mesh.setPivotMatrix(p);
  39475. mesh.computeWorldMatrix(true);
  39476. //calculate the translation
  39477. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  39478. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  39479. //add it inverted to the delta
  39480. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  39481. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  39482. mesh.setPivotMatrix(oldPivot);
  39483. mesh.computeWorldMatrix(true);
  39484. }
  39485. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  39486. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  39487. this._tmpPosition.copyFrom(object.position);
  39488. }
  39489. impostor.setDeltaPosition(this._tmpDeltaPosition);
  39490. //Now update the impostor object
  39491. impostor.physicsBody.position.copy(this._tmpPosition);
  39492. impostor.physicsBody.quaternion.copy(quaternion);
  39493. };
  39494. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  39495. impostor.object.position.copyFrom(impostor.physicsBody.position);
  39496. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  39497. };
  39498. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  39499. impostor.physicsBody.position.copy(newPosition);
  39500. impostor.physicsBody.quaternion.copy(newRotation);
  39501. };
  39502. CannonJSPlugin.prototype.isSupported = function () {
  39503. return window.CANNON !== undefined;
  39504. };
  39505. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  39506. impostor.physicsBody.velocity.copy(velocity);
  39507. };
  39508. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  39509. impostor.physicsBody.angularVelocity.copy(velocity);
  39510. };
  39511. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  39512. var v = impostor.physicsBody.velocity;
  39513. if (!v)
  39514. return null;
  39515. return new BABYLON.Vector3(v.x, v.y, v.z);
  39516. };
  39517. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  39518. var v = impostor.physicsBody.angularVelocity;
  39519. if (!v)
  39520. return null;
  39521. return new BABYLON.Vector3(v.x, v.y, v.z);
  39522. };
  39523. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  39524. impostor.physicsBody.mass = mass;
  39525. impostor.physicsBody.updateMassProperties();
  39526. };
  39527. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  39528. impostor.physicsBody.sleep();
  39529. };
  39530. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  39531. impostor.physicsBody.wakeUp();
  39532. };
  39533. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  39534. joint.physicsJoint.distance = maxDistance;
  39535. };
  39536. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  39537. if (!motorIndex) {
  39538. joint.physicsJoint.enableMotor();
  39539. }
  39540. };
  39541. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  39542. if (!motorIndex) {
  39543. joint.physicsJoint.disableMotor();
  39544. }
  39545. };
  39546. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  39547. if (!motorIndex) {
  39548. joint.physicsJoint.enableMotor();
  39549. joint.physicsJoint.setMotorSpeed(speed);
  39550. if (maxForce) {
  39551. this.setLimit(joint, maxForce);
  39552. }
  39553. }
  39554. };
  39555. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  39556. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  39557. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  39558. };
  39559. CannonJSPlugin.prototype.dispose = function () {
  39560. //nothing to do, actually.
  39561. };
  39562. return CannonJSPlugin;
  39563. }());
  39564. BABYLON.CannonJSPlugin = CannonJSPlugin;
  39565. })(BABYLON || (BABYLON = {}));
  39566. var BABYLON;
  39567. (function (BABYLON) {
  39568. var OimoJSPlugin = (function () {
  39569. function OimoJSPlugin(iterations) {
  39570. this.name = "OimoJSPlugin";
  39571. this._tmpImpostorsArray = [];
  39572. this._tmpPositionVector = BABYLON.Vector3.Zero();
  39573. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  39574. this.world.clear();
  39575. //making sure no stats are calculated
  39576. this.world.isNoStat = true;
  39577. }
  39578. OimoJSPlugin.prototype.setGravity = function (gravity) {
  39579. this.world.gravity.copy(gravity);
  39580. };
  39581. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  39582. this.world.timeStep = timeStep;
  39583. };
  39584. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  39585. var _this = this;
  39586. impostors.forEach(function (impostor) {
  39587. impostor.beforeStep();
  39588. });
  39589. this.world.step();
  39590. impostors.forEach(function (impostor) {
  39591. impostor.afterStep();
  39592. //update the ordered impostors array
  39593. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  39594. });
  39595. //check for collisions
  39596. var contact = this.world.contacts;
  39597. while (contact !== null) {
  39598. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  39599. contact = contact.next;
  39600. continue;
  39601. }
  39602. //is this body colliding with any other? get the impostor
  39603. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  39604. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  39605. if (!mainImpostor || !collidingImpostor) {
  39606. contact = contact.next;
  39607. continue;
  39608. }
  39609. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  39610. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  39611. contact = contact.next;
  39612. }
  39613. };
  39614. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  39615. var mass = impostor.physicsBody.massInfo.mass;
  39616. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  39617. };
  39618. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  39619. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  39620. this.applyImpulse(impostor, force, contactPoint);
  39621. };
  39622. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  39623. var _this = this;
  39624. //parent-child relationship. Does this impostor has a parent impostor?
  39625. if (impostor.parent) {
  39626. if (impostor.physicsBody) {
  39627. this.removePhysicsBody(impostor);
  39628. //TODO is that needed?
  39629. impostor.forceUpdate();
  39630. }
  39631. return;
  39632. }
  39633. if (impostor.isBodyInitRequired()) {
  39634. var bodyConfig = {
  39635. name: impostor.uniqueId,
  39636. //Oimo must have mass, also for static objects.
  39637. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  39638. size: [],
  39639. type: [],
  39640. pos: [],
  39641. rot: [],
  39642. move: impostor.getParam("mass") !== 0,
  39643. //Supporting older versions of Oimo
  39644. world: this.world
  39645. };
  39646. var impostors = [impostor];
  39647. var addToArray = function (parent) {
  39648. if (!parent.getChildMeshes)
  39649. return;
  39650. parent.getChildMeshes().forEach(function (m) {
  39651. if (m.physicsImpostor) {
  39652. impostors.push(m.physicsImpostor);
  39653. m.physicsImpostor._init();
  39654. }
  39655. });
  39656. };
  39657. addToArray(impostor.object);
  39658. var checkWithEpsilon_1 = function (value) {
  39659. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  39660. };
  39661. impostors.forEach(function (i) {
  39662. //get the correct bounding box
  39663. var oldQuaternion = i.object.rotationQuaternion;
  39664. var rot = new OIMO.Euler().setFromQuaternion({
  39665. x: impostor.object.rotationQuaternion.x,
  39666. y: impostor.object.rotationQuaternion.y,
  39667. z: impostor.object.rotationQuaternion.z,
  39668. s: impostor.object.rotationQuaternion.w
  39669. });
  39670. var extendSize = i.getObjectExtendSize();
  39671. if (i === impostor) {
  39672. var center = impostor.getObjectCenter();
  39673. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  39674. //Can also use Array.prototype.push.apply
  39675. bodyConfig.pos.push(center.x);
  39676. bodyConfig.pos.push(center.y);
  39677. bodyConfig.pos.push(center.z);
  39678. //tmp solution
  39679. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  39680. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  39681. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  39682. }
  39683. else {
  39684. bodyConfig.pos.push(i.object.position.x);
  39685. bodyConfig.pos.push(i.object.position.y);
  39686. bodyConfig.pos.push(i.object.position.z);
  39687. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  39688. bodyConfig.rot.push(0);
  39689. bodyConfig.rot.push(0);
  39690. bodyConfig.rot.push(0);
  39691. }
  39692. // register mesh
  39693. switch (i.type) {
  39694. case BABYLON.PhysicsImpostor.ParticleImpostor:
  39695. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  39696. case BABYLON.PhysicsImpostor.SphereImpostor:
  39697. var radiusX = extendSize.x;
  39698. var radiusY = extendSize.y;
  39699. var radiusZ = extendSize.z;
  39700. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  39701. bodyConfig.type.push('sphere');
  39702. //due to the way oimo works with compounds, add 3 times
  39703. bodyConfig.size.push(size);
  39704. bodyConfig.size.push(size);
  39705. bodyConfig.size.push(size);
  39706. break;
  39707. case BABYLON.PhysicsImpostor.CylinderImpostor:
  39708. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  39709. var sizeY = checkWithEpsilon_1(extendSize.y);
  39710. bodyConfig.type.push('cylinder');
  39711. bodyConfig.size.push(sizeX);
  39712. bodyConfig.size.push(sizeY);
  39713. //due to the way oimo works with compounds, add one more value.
  39714. bodyConfig.size.push(sizeY);
  39715. break;
  39716. case BABYLON.PhysicsImpostor.PlaneImpostor:
  39717. case BABYLON.PhysicsImpostor.BoxImpostor:
  39718. default:
  39719. var sizeX = checkWithEpsilon_1(extendSize.x);
  39720. var sizeY = checkWithEpsilon_1(extendSize.y);
  39721. var sizeZ = checkWithEpsilon_1(extendSize.z);
  39722. bodyConfig.type.push('box');
  39723. bodyConfig.size.push(sizeX);
  39724. bodyConfig.size.push(sizeY);
  39725. bodyConfig.size.push(sizeZ);
  39726. break;
  39727. }
  39728. //actually not needed, but hey...
  39729. i.object.rotationQuaternion = oldQuaternion;
  39730. });
  39731. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  39732. }
  39733. else {
  39734. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  39735. }
  39736. impostor.setDeltaPosition(this._tmpPositionVector);
  39737. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  39738. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  39739. };
  39740. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  39741. //impostor.physicsBody.dispose();
  39742. //Same as : (older oimo versions)
  39743. this.world.removeRigidBody(impostor.physicsBody);
  39744. };
  39745. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  39746. var mainBody = impostorJoint.mainImpostor.physicsBody;
  39747. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  39748. if (!mainBody || !connectedBody) {
  39749. return;
  39750. }
  39751. var jointData = impostorJoint.joint.jointData;
  39752. var options = jointData.nativeParams || {};
  39753. var type;
  39754. var nativeJointData = {
  39755. body1: mainBody,
  39756. body2: connectedBody,
  39757. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  39758. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  39759. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  39760. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  39761. min: options.min,
  39762. max: options.max,
  39763. collision: options.collision || jointData.collision,
  39764. spring: options.spring,
  39765. //supporting older version of Oimo
  39766. world: this.world
  39767. };
  39768. switch (impostorJoint.joint.type) {
  39769. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  39770. type = "jointBall";
  39771. break;
  39772. case BABYLON.PhysicsJoint.SpringJoint:
  39773. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  39774. var springData = jointData;
  39775. nativeJointData.min = springData.length || nativeJointData.min;
  39776. //Max should also be set, just make sure it is at least min
  39777. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  39778. case BABYLON.PhysicsJoint.DistanceJoint:
  39779. type = "jointDistance";
  39780. nativeJointData.max = jointData.maxDistance;
  39781. break;
  39782. case BABYLON.PhysicsJoint.PrismaticJoint:
  39783. type = "jointPrisme";
  39784. break;
  39785. case BABYLON.PhysicsJoint.SliderJoint:
  39786. type = "jointSlide";
  39787. break;
  39788. case BABYLON.PhysicsJoint.WheelJoint:
  39789. type = "jointWheel";
  39790. break;
  39791. case BABYLON.PhysicsJoint.HingeJoint:
  39792. default:
  39793. type = "jointHinge";
  39794. break;
  39795. }
  39796. nativeJointData.type = type;
  39797. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  39798. };
  39799. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  39800. //Bug in Oimo prevents us from disposing a joint in the playground
  39801. //joint.joint.physicsJoint.dispose();
  39802. //So we will bruteforce it!
  39803. try {
  39804. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  39805. }
  39806. catch (e) {
  39807. BABYLON.Tools.Warn(e);
  39808. }
  39809. };
  39810. OimoJSPlugin.prototype.isSupported = function () {
  39811. return OIMO !== undefined;
  39812. };
  39813. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  39814. if (!impostor.physicsBody.sleeping) {
  39815. //TODO check that
  39816. if (impostor.physicsBody.shapes.next) {
  39817. var parentShape = this._getLastShape(impostor.physicsBody);
  39818. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  39819. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  39820. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  39821. }
  39822. else {
  39823. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  39824. }
  39825. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  39826. impostor.object.rotationQuaternion.normalize();
  39827. }
  39828. };
  39829. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  39830. var body = impostor.physicsBody;
  39831. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  39832. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  39833. body.syncShapes();
  39834. body.awake();
  39835. };
  39836. OimoJSPlugin.prototype._getLastShape = function (body) {
  39837. var lastShape = body.shapes;
  39838. while (lastShape.next) {
  39839. lastShape = lastShape.next;
  39840. }
  39841. return lastShape;
  39842. };
  39843. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  39844. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  39845. };
  39846. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  39847. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  39848. };
  39849. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  39850. var v = impostor.physicsBody.linearVelocity;
  39851. if (!v)
  39852. return null;
  39853. return new BABYLON.Vector3(v.x, v.y, v.z);
  39854. };
  39855. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  39856. var v = impostor.physicsBody.angularVelocity;
  39857. if (!v)
  39858. return null;
  39859. return new BABYLON.Vector3(v.x, v.y, v.z);
  39860. };
  39861. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  39862. var staticBody = mass === 0;
  39863. //this will actually set the body's density and not its mass.
  39864. //But this is how oimo treats the mass variable.
  39865. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  39866. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  39867. };
  39868. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  39869. impostor.physicsBody.sleep();
  39870. };
  39871. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  39872. impostor.physicsBody.awake();
  39873. };
  39874. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  39875. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  39876. if (minDistance !== void 0) {
  39877. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  39878. }
  39879. };
  39880. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  39881. //TODO separate rotational and transational motors.
  39882. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  39883. if (motor) {
  39884. motor.setMotor(speed, maxForce);
  39885. }
  39886. };
  39887. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  39888. //TODO separate rotational and transational motors.
  39889. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  39890. if (motor) {
  39891. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  39892. }
  39893. };
  39894. OimoJSPlugin.prototype.dispose = function () {
  39895. this.world.clear();
  39896. };
  39897. return OimoJSPlugin;
  39898. }());
  39899. BABYLON.OimoJSPlugin = OimoJSPlugin;
  39900. })(BABYLON || (BABYLON = {}));
  39901. var BABYLON;
  39902. (function (BABYLON) {
  39903. var DisplayPassPostProcess = (function (_super) {
  39904. __extends(DisplayPassPostProcess, _super);
  39905. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  39906. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  39907. }
  39908. return DisplayPassPostProcess;
  39909. }(BABYLON.PostProcess));
  39910. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  39911. })(BABYLON || (BABYLON = {}));
  39912. var BABYLON;
  39913. (function (BABYLON) {
  39914. var SimplificationSettings = (function () {
  39915. function SimplificationSettings(quality, distance, optimizeMesh) {
  39916. this.quality = quality;
  39917. this.distance = distance;
  39918. this.optimizeMesh = optimizeMesh;
  39919. }
  39920. return SimplificationSettings;
  39921. }());
  39922. BABYLON.SimplificationSettings = SimplificationSettings;
  39923. var SimplificationQueue = (function () {
  39924. function SimplificationQueue() {
  39925. this.running = false;
  39926. this._simplificationArray = [];
  39927. }
  39928. SimplificationQueue.prototype.addTask = function (task) {
  39929. this._simplificationArray.push(task);
  39930. };
  39931. SimplificationQueue.prototype.executeNext = function () {
  39932. var task = this._simplificationArray.pop();
  39933. if (task) {
  39934. this.running = true;
  39935. this.runSimplification(task);
  39936. }
  39937. else {
  39938. this.running = false;
  39939. }
  39940. };
  39941. SimplificationQueue.prototype.runSimplification = function (task) {
  39942. var _this = this;
  39943. if (task.parallelProcessing) {
  39944. //parallel simplifier
  39945. task.settings.forEach(function (setting) {
  39946. var simplifier = _this.getSimplifier(task);
  39947. simplifier.simplify(setting, function (newMesh) {
  39948. task.mesh.addLODLevel(setting.distance, newMesh);
  39949. newMesh.isVisible = true;
  39950. //check if it is the last
  39951. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  39952. //all done, run the success callback.
  39953. task.successCallback();
  39954. }
  39955. _this.executeNext();
  39956. });
  39957. });
  39958. }
  39959. else {
  39960. //single simplifier.
  39961. var simplifier = this.getSimplifier(task);
  39962. var runDecimation = function (setting, callback) {
  39963. simplifier.simplify(setting, function (newMesh) {
  39964. task.mesh.addLODLevel(setting.distance, newMesh);
  39965. newMesh.isVisible = true;
  39966. //run the next quality level
  39967. callback();
  39968. });
  39969. };
  39970. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  39971. runDecimation(task.settings[loop.index], function () {
  39972. loop.executeNext();
  39973. });
  39974. }, function () {
  39975. //execution ended, run the success callback.
  39976. if (task.successCallback) {
  39977. task.successCallback();
  39978. }
  39979. _this.executeNext();
  39980. });
  39981. }
  39982. };
  39983. SimplificationQueue.prototype.getSimplifier = function (task) {
  39984. switch (task.simplificationType) {
  39985. case SimplificationType.QUADRATIC:
  39986. default:
  39987. return new QuadraticErrorSimplification(task.mesh);
  39988. }
  39989. };
  39990. return SimplificationQueue;
  39991. }());
  39992. BABYLON.SimplificationQueue = SimplificationQueue;
  39993. /**
  39994. * The implemented types of simplification.
  39995. * At the moment only Quadratic Error Decimation is implemented.
  39996. */
  39997. (function (SimplificationType) {
  39998. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  39999. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  40000. var SimplificationType = BABYLON.SimplificationType;
  40001. var DecimationTriangle = (function () {
  40002. function DecimationTriangle(vertices) {
  40003. this.vertices = vertices;
  40004. this.error = new Array(4);
  40005. this.deleted = false;
  40006. this.isDirty = false;
  40007. this.deletePending = false;
  40008. this.borderFactor = 0;
  40009. }
  40010. return DecimationTriangle;
  40011. }());
  40012. BABYLON.DecimationTriangle = DecimationTriangle;
  40013. var DecimationVertex = (function () {
  40014. function DecimationVertex(position, id) {
  40015. this.position = position;
  40016. this.id = id;
  40017. this.isBorder = true;
  40018. this.q = new QuadraticMatrix();
  40019. this.triangleCount = 0;
  40020. this.triangleStart = 0;
  40021. this.originalOffsets = [];
  40022. }
  40023. DecimationVertex.prototype.updatePosition = function (newPosition) {
  40024. this.position.copyFrom(newPosition);
  40025. };
  40026. return DecimationVertex;
  40027. }());
  40028. BABYLON.DecimationVertex = DecimationVertex;
  40029. var QuadraticMatrix = (function () {
  40030. function QuadraticMatrix(data) {
  40031. this.data = new Array(10);
  40032. for (var i = 0; i < 10; ++i) {
  40033. if (data && data[i]) {
  40034. this.data[i] = data[i];
  40035. }
  40036. else {
  40037. this.data[i] = 0;
  40038. }
  40039. }
  40040. }
  40041. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  40042. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  40043. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  40044. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  40045. return det;
  40046. };
  40047. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  40048. for (var i = 0; i < 10; ++i) {
  40049. this.data[i] += matrix.data[i];
  40050. }
  40051. };
  40052. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  40053. for (var i = 0; i < 10; ++i) {
  40054. this.data[i] += data[i];
  40055. }
  40056. };
  40057. QuadraticMatrix.prototype.add = function (matrix) {
  40058. var m = new QuadraticMatrix();
  40059. for (var i = 0; i < 10; ++i) {
  40060. m.data[i] = this.data[i] + matrix.data[i];
  40061. }
  40062. return m;
  40063. };
  40064. QuadraticMatrix.FromData = function (a, b, c, d) {
  40065. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  40066. };
  40067. //returning an array to avoid garbage collection
  40068. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  40069. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  40070. };
  40071. return QuadraticMatrix;
  40072. }());
  40073. BABYLON.QuadraticMatrix = QuadraticMatrix;
  40074. var Reference = (function () {
  40075. function Reference(vertexId, triangleId) {
  40076. this.vertexId = vertexId;
  40077. this.triangleId = triangleId;
  40078. }
  40079. return Reference;
  40080. }());
  40081. BABYLON.Reference = Reference;
  40082. /**
  40083. * An implementation of the Quadratic Error simplification algorithm.
  40084. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  40085. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  40086. * @author RaananW
  40087. */
  40088. var QuadraticErrorSimplification = (function () {
  40089. function QuadraticErrorSimplification(_mesh) {
  40090. this._mesh = _mesh;
  40091. this.initialized = false;
  40092. this.syncIterations = 5000;
  40093. this.aggressiveness = 7;
  40094. this.decimationIterations = 100;
  40095. this.boundingBoxEpsilon = BABYLON.Epsilon;
  40096. }
  40097. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  40098. var _this = this;
  40099. this.initDecimatedMesh();
  40100. //iterating through the submeshes array, one after the other.
  40101. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  40102. _this.initWithMesh(loop.index, function () {
  40103. _this.runDecimation(settings, loop.index, function () {
  40104. loop.executeNext();
  40105. });
  40106. }, settings.optimizeMesh);
  40107. }, function () {
  40108. setTimeout(function () {
  40109. successCallback(_this._reconstructedMesh);
  40110. }, 0);
  40111. });
  40112. };
  40113. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  40114. var _this = this;
  40115. var gCount = 0;
  40116. triangle.vertices.forEach(function (vertex) {
  40117. var count = 0;
  40118. var vPos = vertex.position;
  40119. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  40120. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  40121. ++count;
  40122. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  40123. ++count;
  40124. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  40125. ++count;
  40126. if (count > 1) {
  40127. ++gCount;
  40128. }
  40129. ;
  40130. });
  40131. if (gCount > 1) {
  40132. console.log(triangle, gCount);
  40133. }
  40134. return gCount > 1;
  40135. };
  40136. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  40137. var _this = this;
  40138. var targetCount = ~~(this.triangles.length * settings.quality);
  40139. var deletedTriangles = 0;
  40140. var triangleCount = this.triangles.length;
  40141. var iterationFunction = function (iteration, callback) {
  40142. setTimeout(function () {
  40143. if (iteration % 5 === 0) {
  40144. _this.updateMesh(iteration === 0);
  40145. }
  40146. for (var i = 0; i < _this.triangles.length; ++i) {
  40147. _this.triangles[i].isDirty = false;
  40148. }
  40149. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  40150. var trianglesIterator = function (i) {
  40151. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  40152. var t = _this.triangles[tIdx];
  40153. if (!t)
  40154. return;
  40155. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  40156. return;
  40157. }
  40158. for (var j = 0; j < 3; ++j) {
  40159. if (t.error[j] < threshold) {
  40160. var deleted0 = [];
  40161. var deleted1 = [];
  40162. var v0 = t.vertices[j];
  40163. var v1 = t.vertices[(j + 1) % 3];
  40164. if (v0.isBorder || v1.isBorder)
  40165. continue;
  40166. var p = BABYLON.Vector3.Zero();
  40167. var n = BABYLON.Vector3.Zero();
  40168. var uv = BABYLON.Vector2.Zero();
  40169. var color = new BABYLON.Color4(0, 0, 0, 1);
  40170. _this.calculateError(v0, v1, p, n, uv, color);
  40171. var delTr = [];
  40172. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  40173. continue;
  40174. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  40175. continue;
  40176. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  40177. continue;
  40178. var uniqueArray = [];
  40179. delTr.forEach(function (deletedT) {
  40180. if (uniqueArray.indexOf(deletedT) === -1) {
  40181. deletedT.deletePending = true;
  40182. uniqueArray.push(deletedT);
  40183. }
  40184. });
  40185. if (uniqueArray.length % 2 !== 0) {
  40186. continue;
  40187. }
  40188. v0.q = v1.q.add(v0.q);
  40189. v0.updatePosition(p);
  40190. var tStart = _this.references.length;
  40191. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  40192. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  40193. var tCount = _this.references.length - tStart;
  40194. if (tCount <= v0.triangleCount) {
  40195. if (tCount) {
  40196. for (var c = 0; c < tCount; c++) {
  40197. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  40198. }
  40199. }
  40200. }
  40201. else {
  40202. v0.triangleStart = tStart;
  40203. }
  40204. v0.triangleCount = tCount;
  40205. break;
  40206. }
  40207. }
  40208. };
  40209. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  40210. }, 0);
  40211. };
  40212. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  40213. if (triangleCount - deletedTriangles <= targetCount)
  40214. loop.breakLoop();
  40215. else {
  40216. iterationFunction(loop.index, function () {
  40217. loop.executeNext();
  40218. });
  40219. }
  40220. }, function () {
  40221. setTimeout(function () {
  40222. //reconstruct this part of the mesh
  40223. _this.reconstructMesh(submeshIndex);
  40224. successCallback();
  40225. }, 0);
  40226. });
  40227. };
  40228. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  40229. var _this = this;
  40230. this.vertices = [];
  40231. this.triangles = [];
  40232. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40233. var indices = this._mesh.getIndices();
  40234. var submesh = this._mesh.subMeshes[submeshIndex];
  40235. var findInVertices = function (positionToSearch) {
  40236. if (optimizeMesh) {
  40237. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  40238. if (_this.vertices[ii].position.equals(positionToSearch)) {
  40239. return _this.vertices[ii];
  40240. }
  40241. }
  40242. }
  40243. return null;
  40244. };
  40245. var vertexReferences = [];
  40246. var vertexInit = function (i) {
  40247. var offset = i + submesh.verticesStart;
  40248. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  40249. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  40250. vertex.originalOffsets.push(offset);
  40251. if (vertex.id === _this.vertices.length) {
  40252. _this.vertices.push(vertex);
  40253. }
  40254. vertexReferences.push(vertex.id);
  40255. };
  40256. //var totalVertices = mesh.getTotalVertices();
  40257. var totalVertices = submesh.verticesCount;
  40258. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  40259. var indicesInit = function (i) {
  40260. var offset = (submesh.indexStart / 3) + i;
  40261. var pos = (offset * 3);
  40262. var i0 = indices[pos + 0];
  40263. var i1 = indices[pos + 1];
  40264. var i2 = indices[pos + 2];
  40265. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  40266. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  40267. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  40268. var triangle = new DecimationTriangle([v0, v1, v2]);
  40269. triangle.originalOffset = pos;
  40270. _this.triangles.push(triangle);
  40271. };
  40272. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  40273. _this.init(callback);
  40274. });
  40275. });
  40276. };
  40277. QuadraticErrorSimplification.prototype.init = function (callback) {
  40278. var _this = this;
  40279. var triangleInit1 = function (i) {
  40280. var t = _this.triangles[i];
  40281. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  40282. for (var j = 0; j < 3; j++) {
  40283. 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))));
  40284. }
  40285. };
  40286. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  40287. var triangleInit2 = function (i) {
  40288. var t = _this.triangles[i];
  40289. for (var j = 0; j < 3; ++j) {
  40290. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  40291. }
  40292. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  40293. };
  40294. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  40295. _this.initialized = true;
  40296. callback();
  40297. });
  40298. });
  40299. };
  40300. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  40301. var newTriangles = [];
  40302. var i;
  40303. for (i = 0; i < this.vertices.length; ++i) {
  40304. this.vertices[i].triangleCount = 0;
  40305. }
  40306. var t;
  40307. var j;
  40308. for (i = 0; i < this.triangles.length; ++i) {
  40309. if (!this.triangles[i].deleted) {
  40310. t = this.triangles[i];
  40311. for (j = 0; j < 3; ++j) {
  40312. t.vertices[j].triangleCount = 1;
  40313. }
  40314. newTriangles.push(t);
  40315. }
  40316. }
  40317. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  40318. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  40319. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  40320. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  40321. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40322. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40323. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40324. var vertexCount = 0;
  40325. for (i = 0; i < this.vertices.length; ++i) {
  40326. var vertex = this.vertices[i];
  40327. vertex.id = vertexCount;
  40328. if (vertex.triangleCount) {
  40329. vertex.originalOffsets.forEach(function (originalOffset) {
  40330. newPositionData.push(vertex.position.x);
  40331. newPositionData.push(vertex.position.y);
  40332. newPositionData.push(vertex.position.z);
  40333. newNormalData.push(normalData[originalOffset * 3]);
  40334. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  40335. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  40336. if (uvs && uvs.length) {
  40337. newUVsData.push(uvs[(originalOffset * 2)]);
  40338. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  40339. }
  40340. else if (colorsData && colorsData.length) {
  40341. newColorsData.push(colorsData[(originalOffset * 4)]);
  40342. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  40343. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  40344. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  40345. }
  40346. ++vertexCount;
  40347. });
  40348. }
  40349. }
  40350. var startingIndex = this._reconstructedMesh.getTotalIndices();
  40351. var startingVertex = this._reconstructedMesh.getTotalVertices();
  40352. var submeshesArray = this._reconstructedMesh.subMeshes;
  40353. this._reconstructedMesh.subMeshes = [];
  40354. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  40355. var originalIndices = this._mesh.getIndices();
  40356. for (i = 0; i < newTriangles.length; ++i) {
  40357. t = newTriangles[i]; //now get the new referencing point for each vertex
  40358. [0, 1, 2].forEach(function (idx) {
  40359. var id = originalIndices[t.originalOffset + idx];
  40360. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  40361. if (offset < 0)
  40362. offset = 0;
  40363. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  40364. });
  40365. }
  40366. //overwriting the old vertex buffers and indices.
  40367. this._reconstructedMesh.setIndices(newIndicesArray);
  40368. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  40369. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  40370. if (newUVsData.length > 0)
  40371. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  40372. if (newColorsData.length > 0)
  40373. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  40374. //create submesh
  40375. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  40376. if (submeshIndex > 0) {
  40377. this._reconstructedMesh.subMeshes = [];
  40378. submeshesArray.forEach(function (submesh) {
  40379. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  40380. });
  40381. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  40382. }
  40383. };
  40384. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  40385. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  40386. this._reconstructedMesh.material = this._mesh.material;
  40387. this._reconstructedMesh.parent = this._mesh.parent;
  40388. this._reconstructedMesh.isVisible = false;
  40389. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  40390. };
  40391. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  40392. for (var i = 0; i < vertex1.triangleCount; ++i) {
  40393. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  40394. if (t.deleted)
  40395. continue;
  40396. var s = this.references[vertex1.triangleStart + i].vertexId;
  40397. var v1 = t.vertices[(s + 1) % 3];
  40398. var v2 = t.vertices[(s + 2) % 3];
  40399. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  40400. deletedArray[i] = true;
  40401. delTr.push(t);
  40402. continue;
  40403. }
  40404. var d1 = v1.position.subtract(point);
  40405. d1 = d1.normalize();
  40406. var d2 = v2.position.subtract(point);
  40407. d2 = d2.normalize();
  40408. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  40409. return true;
  40410. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  40411. deletedArray[i] = false;
  40412. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  40413. return true;
  40414. }
  40415. return false;
  40416. };
  40417. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  40418. var newDeleted = deletedTriangles;
  40419. for (var i = 0; i < vertex.triangleCount; ++i) {
  40420. var ref = this.references[vertex.triangleStart + i];
  40421. var t = this.triangles[ref.triangleId];
  40422. if (t.deleted)
  40423. continue;
  40424. if (deletedArray[i] && t.deletePending) {
  40425. t.deleted = true;
  40426. newDeleted++;
  40427. continue;
  40428. }
  40429. t.vertices[ref.vertexId] = origVertex;
  40430. t.isDirty = true;
  40431. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  40432. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  40433. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  40434. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  40435. this.references.push(ref);
  40436. }
  40437. return newDeleted;
  40438. };
  40439. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  40440. for (var i = 0; i < this.vertices.length; ++i) {
  40441. var vCount = [];
  40442. var vId = [];
  40443. var v = this.vertices[i];
  40444. var j;
  40445. for (j = 0; j < v.triangleCount; ++j) {
  40446. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  40447. for (var ii = 0; ii < 3; ii++) {
  40448. var ofs = 0;
  40449. var vv = triangle.vertices[ii];
  40450. while (ofs < vCount.length) {
  40451. if (vId[ofs] === vv.id)
  40452. break;
  40453. ++ofs;
  40454. }
  40455. if (ofs === vCount.length) {
  40456. vCount.push(1);
  40457. vId.push(vv.id);
  40458. }
  40459. else {
  40460. vCount[ofs]++;
  40461. }
  40462. }
  40463. }
  40464. for (j = 0; j < vCount.length; ++j) {
  40465. if (vCount[j] === 1) {
  40466. this.vertices[vId[j]].isBorder = true;
  40467. }
  40468. else {
  40469. this.vertices[vId[j]].isBorder = false;
  40470. }
  40471. }
  40472. }
  40473. };
  40474. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  40475. if (identifyBorders === void 0) { identifyBorders = false; }
  40476. var i;
  40477. if (!identifyBorders) {
  40478. var newTrianglesVector = [];
  40479. for (i = 0; i < this.triangles.length; ++i) {
  40480. if (!this.triangles[i].deleted) {
  40481. newTrianglesVector.push(this.triangles[i]);
  40482. }
  40483. }
  40484. this.triangles = newTrianglesVector;
  40485. }
  40486. for (i = 0; i < this.vertices.length; ++i) {
  40487. this.vertices[i].triangleCount = 0;
  40488. this.vertices[i].triangleStart = 0;
  40489. }
  40490. var t;
  40491. var j;
  40492. var v;
  40493. for (i = 0; i < this.triangles.length; ++i) {
  40494. t = this.triangles[i];
  40495. for (j = 0; j < 3; ++j) {
  40496. v = t.vertices[j];
  40497. v.triangleCount++;
  40498. }
  40499. }
  40500. var tStart = 0;
  40501. for (i = 0; i < this.vertices.length; ++i) {
  40502. this.vertices[i].triangleStart = tStart;
  40503. tStart += this.vertices[i].triangleCount;
  40504. this.vertices[i].triangleCount = 0;
  40505. }
  40506. var newReferences = new Array(this.triangles.length * 3);
  40507. for (i = 0; i < this.triangles.length; ++i) {
  40508. t = this.triangles[i];
  40509. for (j = 0; j < 3; ++j) {
  40510. v = t.vertices[j];
  40511. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  40512. v.triangleCount++;
  40513. }
  40514. }
  40515. this.references = newReferences;
  40516. if (identifyBorders) {
  40517. this.identifyBorder();
  40518. }
  40519. };
  40520. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  40521. var x = point.x;
  40522. var y = point.y;
  40523. var z = point.z;
  40524. 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
  40525. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  40526. };
  40527. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  40528. var q = vertex1.q.add(vertex2.q);
  40529. var border = vertex1.isBorder && vertex2.isBorder;
  40530. var error = 0;
  40531. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  40532. if (qDet !== 0 && !border) {
  40533. if (!pointResult) {
  40534. pointResult = BABYLON.Vector3.Zero();
  40535. }
  40536. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  40537. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  40538. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  40539. error = this.vertexError(q, pointResult);
  40540. }
  40541. else {
  40542. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  40543. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  40544. var error1 = this.vertexError(q, vertex1.position);
  40545. var error2 = this.vertexError(q, vertex2.position);
  40546. var error3 = this.vertexError(q, p3);
  40547. error = Math.min(error1, error2, error3);
  40548. if (error === error1) {
  40549. if (pointResult) {
  40550. pointResult.copyFrom(vertex1.position);
  40551. }
  40552. }
  40553. else if (error === error2) {
  40554. if (pointResult) {
  40555. pointResult.copyFrom(vertex2.position);
  40556. }
  40557. }
  40558. else {
  40559. if (pointResult) {
  40560. pointResult.copyFrom(p3);
  40561. }
  40562. }
  40563. }
  40564. return error;
  40565. };
  40566. return QuadraticErrorSimplification;
  40567. }());
  40568. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  40569. })(BABYLON || (BABYLON = {}));
  40570. var BABYLON;
  40571. (function (BABYLON) {
  40572. var serializedGeometries = [];
  40573. var serializeGeometry = function (geometry, serializationGeometries) {
  40574. if (serializedGeometries[geometry.id]) {
  40575. return;
  40576. }
  40577. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  40578. serializationGeometries.boxes.push(geometry.serialize());
  40579. }
  40580. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  40581. serializationGeometries.spheres.push(geometry.serialize());
  40582. }
  40583. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  40584. serializationGeometries.cylinders.push(geometry.serialize());
  40585. }
  40586. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  40587. serializationGeometries.toruses.push(geometry.serialize());
  40588. }
  40589. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  40590. serializationGeometries.grounds.push(geometry.serialize());
  40591. }
  40592. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  40593. serializationGeometries.planes.push(geometry.serialize());
  40594. }
  40595. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  40596. serializationGeometries.torusKnots.push(geometry.serialize());
  40597. }
  40598. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  40599. throw new Error("Unknown primitive type");
  40600. }
  40601. else {
  40602. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  40603. }
  40604. serializedGeometries[geometry.id] = true;
  40605. };
  40606. var serializeMesh = function (mesh, serializationScene) {
  40607. var serializationObject = {};
  40608. serializationObject.name = mesh.name;
  40609. serializationObject.id = mesh.id;
  40610. if (BABYLON.Tags.HasTags(mesh)) {
  40611. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  40612. }
  40613. serializationObject.position = mesh.position.asArray();
  40614. if (mesh.rotationQuaternion) {
  40615. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  40616. }
  40617. else if (mesh.rotation) {
  40618. serializationObject.rotation = mesh.rotation.asArray();
  40619. }
  40620. serializationObject.scaling = mesh.scaling.asArray();
  40621. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  40622. serializationObject.isEnabled = mesh.isEnabled();
  40623. serializationObject.isVisible = mesh.isVisible;
  40624. serializationObject.infiniteDistance = mesh.infiniteDistance;
  40625. serializationObject.pickable = mesh.isPickable;
  40626. serializationObject.receiveShadows = mesh.receiveShadows;
  40627. serializationObject.billboardMode = mesh.billboardMode;
  40628. serializationObject.visibility = mesh.visibility;
  40629. serializationObject.checkCollisions = mesh.checkCollisions;
  40630. // Parent
  40631. if (mesh.parent) {
  40632. serializationObject.parentId = mesh.parent.id;
  40633. }
  40634. // Geometry
  40635. var geometry = mesh._geometry;
  40636. if (geometry) {
  40637. var geometryId = geometry.id;
  40638. serializationObject.geometryId = geometryId;
  40639. if (!mesh.getScene().getGeometryByID(geometryId)) {
  40640. // 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
  40641. serializeGeometry(geometry, serializationScene.geometries);
  40642. }
  40643. // SubMeshes
  40644. serializationObject.subMeshes = [];
  40645. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40646. var subMesh = mesh.subMeshes[subIndex];
  40647. serializationObject.subMeshes.push({
  40648. materialIndex: subMesh.materialIndex,
  40649. verticesStart: subMesh.verticesStart,
  40650. verticesCount: subMesh.verticesCount,
  40651. indexStart: subMesh.indexStart,
  40652. indexCount: subMesh.indexCount
  40653. });
  40654. }
  40655. }
  40656. // Material
  40657. if (mesh.material) {
  40658. serializationObject.materialId = mesh.material.id;
  40659. }
  40660. else {
  40661. mesh.material = null;
  40662. }
  40663. // Skeleton
  40664. if (mesh.skeleton) {
  40665. serializationObject.skeletonId = mesh.skeleton.id;
  40666. }
  40667. // Physics
  40668. //TODO implement correct serialization for physics impostors.
  40669. if (mesh.getPhysicsImpostor()) {
  40670. serializationObject.physicsMass = mesh.getPhysicsMass();
  40671. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  40672. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  40673. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  40674. }
  40675. // Instances
  40676. serializationObject.instances = [];
  40677. for (var index = 0; index < mesh.instances.length; index++) {
  40678. var instance = mesh.instances[index];
  40679. var serializationInstance = {
  40680. name: instance.name,
  40681. position: instance.position.asArray(),
  40682. scaling: instance.scaling.asArray()
  40683. };
  40684. if (instance.rotationQuaternion) {
  40685. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  40686. }
  40687. else if (instance.rotation) {
  40688. serializationInstance.rotation = instance.rotation.asArray();
  40689. }
  40690. serializationObject.instances.push(serializationInstance);
  40691. // Animations
  40692. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  40693. serializationInstance.ranges = instance.serializeAnimationRanges();
  40694. }
  40695. // Animations
  40696. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  40697. serializationObject.ranges = mesh.serializeAnimationRanges();
  40698. // Layer mask
  40699. serializationObject.layerMask = mesh.layerMask;
  40700. // Action Manager
  40701. if (mesh.actionManager) {
  40702. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  40703. }
  40704. return serializationObject;
  40705. };
  40706. var finalizeSingleMesh = function (mesh, serializationObject) {
  40707. //only works if the mesh is already loaded
  40708. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  40709. //serialize material
  40710. if (mesh.material) {
  40711. if (mesh.material instanceof BABYLON.StandardMaterial) {
  40712. serializationObject.materials = serializationObject.materials || [];
  40713. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  40714. serializationObject.materials.push(mesh.material.serialize());
  40715. }
  40716. }
  40717. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  40718. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  40719. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  40720. serializationObject.multiMaterials.push(mesh.material.serialize());
  40721. }
  40722. }
  40723. }
  40724. //serialize geometry
  40725. var geometry = mesh._geometry;
  40726. if (geometry) {
  40727. if (!serializationObject.geometries) {
  40728. serializationObject.geometries = {};
  40729. serializationObject.geometries.boxes = [];
  40730. serializationObject.geometries.spheres = [];
  40731. serializationObject.geometries.cylinders = [];
  40732. serializationObject.geometries.toruses = [];
  40733. serializationObject.geometries.grounds = [];
  40734. serializationObject.geometries.planes = [];
  40735. serializationObject.geometries.torusKnots = [];
  40736. serializationObject.geometries.vertexData = [];
  40737. }
  40738. serializeGeometry(geometry, serializationObject.geometries);
  40739. }
  40740. // Skeletons
  40741. if (mesh.skeleton) {
  40742. serializationObject.skeletons = serializationObject.skeletons || [];
  40743. serializationObject.skeletons.push(mesh.skeleton.serialize());
  40744. }
  40745. //serialize the actual mesh
  40746. serializationObject.meshes = serializationObject.meshes || [];
  40747. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  40748. }
  40749. };
  40750. var SceneSerializer = (function () {
  40751. function SceneSerializer() {
  40752. }
  40753. SceneSerializer.ClearCache = function () {
  40754. serializedGeometries = [];
  40755. };
  40756. SceneSerializer.Serialize = function (scene) {
  40757. var serializationObject = {};
  40758. // Scene
  40759. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  40760. serializationObject.autoClear = scene.autoClear;
  40761. serializationObject.clearColor = scene.clearColor.asArray();
  40762. serializationObject.ambientColor = scene.ambientColor.asArray();
  40763. serializationObject.gravity = scene.gravity.asArray();
  40764. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  40765. serializationObject.workerCollisions = scene.workerCollisions;
  40766. // Fog
  40767. if (scene.fogMode && scene.fogMode !== 0) {
  40768. serializationObject.fogMode = scene.fogMode;
  40769. serializationObject.fogColor = scene.fogColor.asArray();
  40770. serializationObject.fogStart = scene.fogStart;
  40771. serializationObject.fogEnd = scene.fogEnd;
  40772. serializationObject.fogDensity = scene.fogDensity;
  40773. }
  40774. //Physics
  40775. if (scene.isPhysicsEnabled()) {
  40776. serializationObject.physicsEnabled = true;
  40777. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  40778. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  40779. }
  40780. // Lights
  40781. serializationObject.lights = [];
  40782. var index;
  40783. var light;
  40784. for (index = 0; index < scene.lights.length; index++) {
  40785. light = scene.lights[index];
  40786. serializationObject.lights.push(light.serialize());
  40787. }
  40788. // Cameras
  40789. serializationObject.cameras = [];
  40790. for (index = 0; index < scene.cameras.length; index++) {
  40791. var camera = scene.cameras[index];
  40792. serializationObject.cameras.push(camera.serialize());
  40793. }
  40794. if (scene.activeCamera) {
  40795. serializationObject.activeCameraID = scene.activeCamera.id;
  40796. }
  40797. // Animations
  40798. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  40799. // Materials
  40800. serializationObject.materials = [];
  40801. serializationObject.multiMaterials = [];
  40802. var material;
  40803. for (index = 0; index < scene.materials.length; index++) {
  40804. material = scene.materials[index];
  40805. serializationObject.materials.push(material.serialize());
  40806. }
  40807. // MultiMaterials
  40808. serializationObject.multiMaterials = [];
  40809. for (index = 0; index < scene.multiMaterials.length; index++) {
  40810. var multiMaterial = scene.multiMaterials[index];
  40811. serializationObject.multiMaterials.push(multiMaterial.serialize());
  40812. }
  40813. // Skeletons
  40814. serializationObject.skeletons = [];
  40815. for (index = 0; index < scene.skeletons.length; index++) {
  40816. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  40817. }
  40818. // Geometries
  40819. serializationObject.geometries = {};
  40820. serializationObject.geometries.boxes = [];
  40821. serializationObject.geometries.spheres = [];
  40822. serializationObject.geometries.cylinders = [];
  40823. serializationObject.geometries.toruses = [];
  40824. serializationObject.geometries.grounds = [];
  40825. serializationObject.geometries.planes = [];
  40826. serializationObject.geometries.torusKnots = [];
  40827. serializationObject.geometries.vertexData = [];
  40828. serializedGeometries = [];
  40829. var geometries = scene.getGeometries();
  40830. for (index = 0; index < geometries.length; index++) {
  40831. var geometry = geometries[index];
  40832. if (geometry.isReady()) {
  40833. serializeGeometry(geometry, serializationObject.geometries);
  40834. }
  40835. }
  40836. // Meshes
  40837. serializationObject.meshes = [];
  40838. for (index = 0; index < scene.meshes.length; index++) {
  40839. var abstractMesh = scene.meshes[index];
  40840. if (abstractMesh instanceof BABYLON.Mesh) {
  40841. var mesh = abstractMesh;
  40842. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  40843. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  40844. }
  40845. }
  40846. }
  40847. // Particles Systems
  40848. serializationObject.particleSystems = [];
  40849. for (index = 0; index < scene.particleSystems.length; index++) {
  40850. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  40851. }
  40852. // Lens flares
  40853. serializationObject.lensFlareSystems = [];
  40854. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  40855. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  40856. }
  40857. // Shadows
  40858. serializationObject.shadowGenerators = [];
  40859. for (index = 0; index < scene.lights.length; index++) {
  40860. light = scene.lights[index];
  40861. var shadowGenerator = light.getShadowGenerator();
  40862. // Only support serialization for official generator so far.
  40863. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  40864. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  40865. }
  40866. }
  40867. // Action Manager
  40868. if (scene.actionManager) {
  40869. serializationObject.actions = scene.actionManager.serialize("scene");
  40870. }
  40871. // Audio
  40872. serializationObject.sounds = [];
  40873. for (index = 0; index < scene.soundTracks.length; index++) {
  40874. var soundtrack = scene.soundTracks[index];
  40875. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  40876. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  40877. }
  40878. }
  40879. return serializationObject;
  40880. };
  40881. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  40882. if (withParents === void 0) { withParents = false; }
  40883. if (withChildren === void 0) { withChildren = false; }
  40884. var serializationObject = {};
  40885. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  40886. if (withParents || withChildren) {
  40887. //deliberate for loop! not for each, appended should be processed as well.
  40888. for (var i = 0; i < toSerialize.length; ++i) {
  40889. if (withChildren) {
  40890. toSerialize[i].getDescendants().forEach(function (node) {
  40891. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  40892. toSerialize.push(node);
  40893. }
  40894. });
  40895. }
  40896. //make sure the array doesn't contain the object already
  40897. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  40898. toSerialize.push(toSerialize[i].parent);
  40899. }
  40900. }
  40901. }
  40902. toSerialize.forEach(function (mesh) {
  40903. finalizeSingleMesh(mesh, serializationObject);
  40904. });
  40905. return serializationObject;
  40906. };
  40907. return SceneSerializer;
  40908. }());
  40909. BABYLON.SceneSerializer = SceneSerializer;
  40910. })(BABYLON || (BABYLON = {}));
  40911. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  40912. // Huge respect for a such great lib.
  40913. // Earcut license:
  40914. // Copyright (c) 2016, Mapbox
  40915. //
  40916. // Permission to use, copy, modify, and/or distribute this software for any purpose
  40917. // with or without fee is hereby granted, provided that the above copyright notice
  40918. // and this permission notice appear in all copies.
  40919. //
  40920. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  40921. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  40922. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  40923. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  40924. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  40925. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  40926. // THIS SOFTWARE.
  40927. var Earcut;
  40928. (function (Earcut) {
  40929. /**
  40930. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  40931. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  40932. * @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).
  40933. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  40934. */
  40935. function earcut(data, holeIndices, dim) {
  40936. dim = dim || 2;
  40937. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  40938. if (!outerNode)
  40939. return triangles;
  40940. var minX, minY, maxX, maxY, x, y, size;
  40941. if (hasHoles)
  40942. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  40943. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  40944. if (data.length > 80 * dim) {
  40945. minX = maxX = data[0];
  40946. minY = maxY = data[1];
  40947. for (var i = dim; i < outerLen; i += dim) {
  40948. x = data[i];
  40949. y = data[i + 1];
  40950. if (x < minX)
  40951. minX = x;
  40952. if (y < minY)
  40953. minY = y;
  40954. if (x > maxX)
  40955. maxX = x;
  40956. if (y > maxY)
  40957. maxY = y;
  40958. }
  40959. // minX, minY and size are later used to transform coords into integers for z-order calculation
  40960. size = Math.max(maxX - minX, maxY - minY);
  40961. }
  40962. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  40963. return triangles;
  40964. }
  40965. Earcut.earcut = earcut;
  40966. // create a circular doubly linked list from polygon points in the specified winding order
  40967. function linkedList(data, start, end, dim, clockwise) {
  40968. var i, last;
  40969. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  40970. for (i = start; i < end; i += dim)
  40971. last = insertNode(i, data[i], data[i + 1], last);
  40972. }
  40973. else {
  40974. for (i = end - dim; i >= start; i -= dim)
  40975. last = insertNode(i, data[i], data[i + 1], last);
  40976. }
  40977. if (last && equals(last, last.next)) {
  40978. removeNode(last);
  40979. last = last.next;
  40980. }
  40981. return last;
  40982. }
  40983. // eliminate colinear or duplicate points
  40984. function filterPoints(start, end) {
  40985. if (!start)
  40986. return start;
  40987. if (!end)
  40988. end = start;
  40989. var p = start, again;
  40990. do {
  40991. again = false;
  40992. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  40993. removeNode(p);
  40994. p = end = p.prev;
  40995. if (p === p.next)
  40996. return null;
  40997. again = true;
  40998. }
  40999. else {
  41000. p = p.next;
  41001. }
  41002. } while (again || p !== end);
  41003. return end;
  41004. }
  41005. // main ear slicing loop which triangulates a polygon (given as a linked list)
  41006. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  41007. if (!ear)
  41008. return;
  41009. // interlink polygon nodes in z-order
  41010. if (!pass && size)
  41011. indexCurve(ear, minX, minY, size);
  41012. var stop = ear, prev, next;
  41013. // iterate through ears, slicing them one by one
  41014. while (ear.prev !== ear.next) {
  41015. prev = ear.prev;
  41016. next = ear.next;
  41017. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  41018. // cut off the triangle
  41019. triangles.push(prev.i / dim);
  41020. triangles.push(ear.i / dim);
  41021. triangles.push(next.i / dim);
  41022. removeNode(ear);
  41023. // skipping the next vertice leads to less sliver triangles
  41024. ear = next.next;
  41025. stop = next.next;
  41026. continue;
  41027. }
  41028. ear = next;
  41029. // if we looped through the whole remaining polygon and can't find any more ears
  41030. if (ear === stop) {
  41031. // try filtering points and slicing again
  41032. if (!pass) {
  41033. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  41034. }
  41035. else if (pass === 1) {
  41036. ear = cureLocalIntersections(ear, triangles, dim);
  41037. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  41038. }
  41039. else if (pass === 2) {
  41040. splitEarcut(ear, triangles, dim, minX, minY, size);
  41041. }
  41042. break;
  41043. }
  41044. }
  41045. }
  41046. // check whether a polygon node forms a valid ear with adjacent nodes
  41047. function isEar(ear) {
  41048. var a = ear.prev, b = ear, c = ear.next;
  41049. if (area(a, b, c) >= 0)
  41050. return false; // reflex, can't be an ear
  41051. // now make sure we don't have other points inside the potential ear
  41052. var p = ear.next.next;
  41053. while (p !== ear.prev) {
  41054. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41055. area(p.prev, p, p.next) >= 0)
  41056. return false;
  41057. p = p.next;
  41058. }
  41059. return true;
  41060. }
  41061. function isEarHashed(ear, minX, minY, size) {
  41062. var a = ear.prev, b = ear, c = ear.next;
  41063. if (area(a, b, c) >= 0)
  41064. return false; // reflex, can't be an ear
  41065. // triangle bbox; min & max are calculated like this for speed
  41066. 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);
  41067. // z-order range for the current triangle bbox;
  41068. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  41069. // first look for points inside the triangle in increasing z-order
  41070. var p = ear.nextZ;
  41071. while (p && p.z <= maxZ) {
  41072. if (p !== ear.prev &&
  41073. p !== ear.next &&
  41074. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41075. area(p.prev, p, p.next) >= 0)
  41076. return false;
  41077. p = p.nextZ;
  41078. }
  41079. // then look for points in decreasing z-order
  41080. p = ear.prevZ;
  41081. while (p && p.z >= minZ) {
  41082. if (p !== ear.prev &&
  41083. p !== ear.next &&
  41084. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41085. area(p.prev, p, p.next) >= 0)
  41086. return false;
  41087. p = p.prevZ;
  41088. }
  41089. return true;
  41090. }
  41091. // go through all polygon nodes and cure small local self-intersections
  41092. function cureLocalIntersections(start, triangles, dim) {
  41093. var p = start;
  41094. do {
  41095. var a = p.prev, b = p.next.next;
  41096. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  41097. triangles.push(a.i / dim);
  41098. triangles.push(p.i / dim);
  41099. triangles.push(b.i / dim);
  41100. // remove two nodes involved
  41101. removeNode(p);
  41102. removeNode(p.next);
  41103. p = start = b;
  41104. }
  41105. p = p.next;
  41106. } while (p !== start);
  41107. return p;
  41108. }
  41109. // try splitting polygon into two and triangulate them independently
  41110. function splitEarcut(start, triangles, dim, minX, minY, size) {
  41111. // look for a valid diagonal that divides the polygon into two
  41112. var a = start;
  41113. do {
  41114. var b = a.next.next;
  41115. while (b !== a.prev) {
  41116. if (a.i !== b.i && isValidDiagonal(a, b)) {
  41117. // split the polygon in two by the diagonal
  41118. var c = splitPolygon(a, b);
  41119. // filter colinear points around the cuts
  41120. a = filterPoints(a, a.next);
  41121. c = filterPoints(c, c.next);
  41122. // run earcut on each half
  41123. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  41124. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  41125. return;
  41126. }
  41127. b = b.next;
  41128. }
  41129. a = a.next;
  41130. } while (a !== start);
  41131. }
  41132. // link every hole into the outer loop, producing a single-ring polygon without holes
  41133. function eliminateHoles(data, holeIndices, outerNode, dim) {
  41134. var queue = [], i, len, start, end, list;
  41135. for (i = 0, len = holeIndices.length; i < len; i++) {
  41136. start = holeIndices[i] * dim;
  41137. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  41138. list = linkedList(data, start, end, dim, false);
  41139. if (list === list.next)
  41140. list.steiner = true;
  41141. queue.push(getLeftmost(list));
  41142. }
  41143. queue.sort(compareX);
  41144. // process holes from left to right
  41145. for (i = 0; i < queue.length; i++) {
  41146. eliminateHole(queue[i], outerNode);
  41147. outerNode = filterPoints(outerNode, outerNode.next);
  41148. }
  41149. return outerNode;
  41150. }
  41151. function compareX(a, b) {
  41152. return a.x - b.x;
  41153. }
  41154. // find a bridge between vertices that connects hole with an outer ring and and link it
  41155. function eliminateHole(hole, outerNode) {
  41156. outerNode = findHoleBridge(hole, outerNode);
  41157. if (outerNode) {
  41158. var b = splitPolygon(outerNode, hole);
  41159. filterPoints(b, b.next);
  41160. }
  41161. }
  41162. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  41163. function findHoleBridge(hole, outerNode) {
  41164. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  41165. // find a segment intersected by a ray from the hole's leftmost point to the left;
  41166. // segment's endpoint with lesser x will be potential connection point
  41167. do {
  41168. if (hy <= p.y && hy >= p.next.y) {
  41169. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  41170. if (x <= hx && x > qx) {
  41171. qx = x;
  41172. if (x === hx) {
  41173. if (hy === p.y)
  41174. return p;
  41175. if (hy === p.next.y)
  41176. return p.next;
  41177. }
  41178. m = p.x < p.next.x ? p : p.next;
  41179. }
  41180. }
  41181. p = p.next;
  41182. } while (p !== outerNode);
  41183. if (!m)
  41184. return null;
  41185. if (hx === qx)
  41186. return m.prev; // hole touches outer segment; pick lower endpoint
  41187. // look for points inside the triangle of hole point, segment intersection and endpoint;
  41188. // if there are no points found, we have a valid connection;
  41189. // otherwise choose the point of the minimum angle with the ray as connection point
  41190. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  41191. p = m.next;
  41192. while (p !== stop) {
  41193. if (hx >= p.x &&
  41194. p.x >= mx &&
  41195. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  41196. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  41197. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  41198. m = p;
  41199. tanMin = tan;
  41200. }
  41201. }
  41202. p = p.next;
  41203. }
  41204. return m;
  41205. }
  41206. // interlink polygon nodes in z-order
  41207. function indexCurve(start, minX, minY, size) {
  41208. var p = start;
  41209. do {
  41210. if (p.z === null)
  41211. p.z = zOrder(p.x, p.y, minX, minY, size);
  41212. p.prevZ = p.prev;
  41213. p.nextZ = p.next;
  41214. p = p.next;
  41215. } while (p !== start);
  41216. p.prevZ.nextZ = null;
  41217. p.prevZ = null;
  41218. sortLinked(p);
  41219. }
  41220. // Simon Tatham's linked list merge sort algorithm
  41221. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  41222. function sortLinked(list) {
  41223. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  41224. do {
  41225. p = list;
  41226. list = null;
  41227. tail = null;
  41228. numMerges = 0;
  41229. while (p) {
  41230. numMerges++;
  41231. q = p;
  41232. pSize = 0;
  41233. for (i = 0; i < inSize; i++) {
  41234. pSize++;
  41235. q = q.nextZ;
  41236. if (!q)
  41237. break;
  41238. }
  41239. qSize = inSize;
  41240. while (pSize > 0 || (qSize > 0 && q)) {
  41241. if (pSize === 0) {
  41242. e = q;
  41243. q = q.nextZ;
  41244. qSize--;
  41245. }
  41246. else if (qSize === 0 || !q) {
  41247. e = p;
  41248. p = p.nextZ;
  41249. pSize--;
  41250. }
  41251. else if (p.z <= q.z) {
  41252. e = p;
  41253. p = p.nextZ;
  41254. pSize--;
  41255. }
  41256. else {
  41257. e = q;
  41258. q = q.nextZ;
  41259. qSize--;
  41260. }
  41261. if (tail)
  41262. tail.nextZ = e;
  41263. else
  41264. list = e;
  41265. e.prevZ = tail;
  41266. tail = e;
  41267. }
  41268. p = q;
  41269. }
  41270. tail.nextZ = null;
  41271. inSize *= 2;
  41272. } while (numMerges > 1);
  41273. return list;
  41274. }
  41275. // z-order of a point given coords and size of the data bounding box
  41276. function zOrder(x, y, minX, minY, size) {
  41277. // coords are transformed into non-negative 15-bit integer range
  41278. x = 32767 * (x - minX) / size;
  41279. y = 32767 * (y - minY) / size;
  41280. x = (x | (x << 8)) & 0x00FF00FF;
  41281. x = (x | (x << 4)) & 0x0F0F0F0F;
  41282. x = (x | (x << 2)) & 0x33333333;
  41283. x = (x | (x << 1)) & 0x55555555;
  41284. y = (y | (y << 8)) & 0x00FF00FF;
  41285. y = (y | (y << 4)) & 0x0F0F0F0F;
  41286. y = (y | (y << 2)) & 0x33333333;
  41287. y = (y | (y << 1)) & 0x55555555;
  41288. return x | (y << 1);
  41289. }
  41290. // find the leftmost node of a polygon ring
  41291. function getLeftmost(start) {
  41292. var p = start, leftmost = start;
  41293. do {
  41294. if (p.x < leftmost.x)
  41295. leftmost = p;
  41296. p = p.next;
  41297. } while (p !== start);
  41298. return leftmost;
  41299. }
  41300. // check if a point lies within a convex triangle
  41301. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  41302. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  41303. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  41304. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  41305. }
  41306. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  41307. function isValidDiagonal(a, b) {
  41308. return a.next.i !== b.i &&
  41309. a.prev.i !== b.i &&
  41310. !intersectsPolygon(a, b) &&
  41311. locallyInside(a, b) &&
  41312. locallyInside(b, a) &&
  41313. middleInside(a, b);
  41314. }
  41315. // signed area of a triangle
  41316. function area(p, q, r) {
  41317. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  41318. }
  41319. // check if two points are equal
  41320. function equals(p1, p2) {
  41321. return p1.x === p2.x && p1.y === p2.y;
  41322. }
  41323. // check if two segments intersect
  41324. function intersects(p1, q1, p2, q2) {
  41325. if ((equals(p1, q1) && equals(p2, q2)) ||
  41326. (equals(p1, q2) && equals(p2, q1)))
  41327. return true;
  41328. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  41329. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  41330. }
  41331. // check if a polygon diagonal intersects any polygon segments
  41332. function intersectsPolygon(a, b) {
  41333. var p = a;
  41334. do {
  41335. if (p.i !== a.i &&
  41336. p.next.i !== a.i &&
  41337. p.i !== b.i &&
  41338. p.next.i !== b.i &&
  41339. intersects(p, p.next, a, b))
  41340. return true;
  41341. p = p.next;
  41342. } while (p !== a);
  41343. return false;
  41344. }
  41345. // check if a polygon diagonal is locally inside the polygon
  41346. function locallyInside(a, b) {
  41347. return area(a.prev, a, a.next) < 0
  41348. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  41349. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  41350. }
  41351. // check if the middle point of a polygon diagonal is inside the polygon
  41352. function middleInside(a, b) {
  41353. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  41354. do {
  41355. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  41356. inside = !inside;
  41357. p = p.next;
  41358. } while (p !== a);
  41359. return inside;
  41360. }
  41361. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  41362. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  41363. function splitPolygon(a, b) {
  41364. 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;
  41365. a.next = b;
  41366. b.prev = a;
  41367. a2.next = an;
  41368. an.prev = a2;
  41369. b2.next = a2;
  41370. a2.prev = b2;
  41371. bp.next = b2;
  41372. b2.prev = bp;
  41373. return b2;
  41374. }
  41375. // create a node and optionally link it with previous one (in a circular doubly linked list)
  41376. function insertNode(i, x, y, last) {
  41377. var p = new Node(i, x, y);
  41378. if (!last) {
  41379. p.prev = p;
  41380. p.next = p;
  41381. }
  41382. else {
  41383. p.next = last.next;
  41384. p.prev = last;
  41385. last.next.prev = p;
  41386. last.next = p;
  41387. }
  41388. return p;
  41389. }
  41390. function removeNode(p) {
  41391. p.next.prev = p.prev;
  41392. p.prev.next = p.next;
  41393. if (p.prevZ)
  41394. p.prevZ.nextZ = p.nextZ;
  41395. if (p.nextZ)
  41396. p.nextZ.prevZ = p.prevZ;
  41397. }
  41398. function Node(i, x, y) {
  41399. // vertice index in coordinates array
  41400. this.i = i;
  41401. // vertex coordinates
  41402. this.x = x;
  41403. this.y = y;
  41404. // previous and next vertice nodes in a polygon ring
  41405. this.prev = null;
  41406. this.next = null;
  41407. // z-order curve value
  41408. this.z = null;
  41409. // previous and next nodes in z-order
  41410. this.prevZ = null;
  41411. this.nextZ = null;
  41412. // indicates whether this is a steiner point
  41413. this.steiner = false;
  41414. }
  41415. /**
  41416. * return a percentage difference between the polygon area and its triangulation area;
  41417. * used to verify correctness of triangulation
  41418. */
  41419. function deviation(data, holeIndices, dim, triangles) {
  41420. var hasHoles = holeIndices && holeIndices.length;
  41421. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  41422. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  41423. if (hasHoles) {
  41424. for (var i = 0, len = holeIndices.length; i < len; i++) {
  41425. var start = holeIndices[i] * dim;
  41426. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  41427. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  41428. }
  41429. }
  41430. var trianglesArea = 0;
  41431. for (i = 0; i < triangles.length; i += 3) {
  41432. var a = triangles[i] * dim;
  41433. var b = triangles[i + 1] * dim;
  41434. var c = triangles[i + 2] * dim;
  41435. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  41436. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  41437. }
  41438. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  41439. }
  41440. Earcut.deviation = deviation;
  41441. ;
  41442. function signedArea(data, start, end, dim) {
  41443. var sum = 0;
  41444. for (var i = start, j = end - dim; i < end; i += dim) {
  41445. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  41446. j = i;
  41447. }
  41448. return sum;
  41449. }
  41450. /**
  41451. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  41452. */
  41453. function flatten(data) {
  41454. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  41455. for (var i = 0; i < data.length; i++) {
  41456. for (var j = 0; j < data[i].length; j++) {
  41457. for (var d = 0; d < dim; d++)
  41458. result.vertices.push(data[i][j][d]);
  41459. }
  41460. if (i > 0) {
  41461. holeIndex += data[i - 1].length;
  41462. result.holes.push(holeIndex);
  41463. }
  41464. }
  41465. return result;
  41466. }
  41467. Earcut.flatten = flatten;
  41468. ;
  41469. })(Earcut || (Earcut = {}));
  41470. var BABYLON;
  41471. (function (BABYLON) {
  41472. // Unique ID when we import meshes from Babylon to CSG
  41473. var currentCSGMeshId = 0;
  41474. // # class Vertex
  41475. // Represents a vertex of a polygon. Use your own vertex class instead of this
  41476. // one to provide additional features like texture coordinates and vertex
  41477. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  41478. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  41479. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  41480. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  41481. // is not used anywhere else.
  41482. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  41483. var Vertex = (function () {
  41484. function Vertex(pos, normal, uv) {
  41485. this.pos = pos;
  41486. this.normal = normal;
  41487. this.uv = uv;
  41488. }
  41489. Vertex.prototype.clone = function () {
  41490. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  41491. };
  41492. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  41493. // orientation of a polygon is flipped.
  41494. Vertex.prototype.flip = function () {
  41495. this.normal = this.normal.scale(-1);
  41496. };
  41497. // Create a new vertex between this vertex and `other` by linearly
  41498. // interpolating all properties using a parameter of `t`. Subclasses should
  41499. // override this to interpolate additional properties.
  41500. Vertex.prototype.interpolate = function (other, t) {
  41501. 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));
  41502. };
  41503. return Vertex;
  41504. }());
  41505. // # class Plane
  41506. // Represents a plane in 3D space.
  41507. var Plane = (function () {
  41508. function Plane(normal, w) {
  41509. this.normal = normal;
  41510. this.w = w;
  41511. }
  41512. Plane.FromPoints = function (a, b, c) {
  41513. var v0 = c.subtract(a);
  41514. var v1 = b.subtract(a);
  41515. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  41516. return null;
  41517. }
  41518. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  41519. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  41520. };
  41521. Plane.prototype.clone = function () {
  41522. return new Plane(this.normal.clone(), this.w);
  41523. };
  41524. Plane.prototype.flip = function () {
  41525. this.normal.scaleInPlace(-1);
  41526. this.w = -this.w;
  41527. };
  41528. // Split `polygon` by this plane if needed, then put the polygon or polygon
  41529. // fragments in the appropriate lists. Coplanar polygons go into either
  41530. // `coplanarFront` or `coplanarBack` depending on their orientation with
  41531. // respect to this plane. Polygons in front or in back of this plane go into
  41532. // either `front` or `back`.
  41533. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  41534. var COPLANAR = 0;
  41535. var FRONT = 1;
  41536. var BACK = 2;
  41537. var SPANNING = 3;
  41538. // Classify each point as well as the entire polygon into one of the above
  41539. // four classes.
  41540. var polygonType = 0;
  41541. var types = [];
  41542. var i;
  41543. var t;
  41544. for (i = 0; i < polygon.vertices.length; i++) {
  41545. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  41546. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  41547. polygonType |= type;
  41548. types.push(type);
  41549. }
  41550. // Put the polygon in the correct list, splitting it when necessary.
  41551. switch (polygonType) {
  41552. case COPLANAR:
  41553. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  41554. break;
  41555. case FRONT:
  41556. front.push(polygon);
  41557. break;
  41558. case BACK:
  41559. back.push(polygon);
  41560. break;
  41561. case SPANNING:
  41562. var f = [], b = [];
  41563. for (i = 0; i < polygon.vertices.length; i++) {
  41564. var j = (i + 1) % polygon.vertices.length;
  41565. var ti = types[i], tj = types[j];
  41566. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  41567. if (ti !== BACK)
  41568. f.push(vi);
  41569. if (ti !== FRONT)
  41570. b.push(ti !== BACK ? vi.clone() : vi);
  41571. if ((ti | tj) === SPANNING) {
  41572. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  41573. var v = vi.interpolate(vj, t);
  41574. f.push(v);
  41575. b.push(v.clone());
  41576. }
  41577. }
  41578. var poly;
  41579. if (f.length >= 3) {
  41580. poly = new Polygon(f, polygon.shared);
  41581. if (poly.plane)
  41582. front.push(poly);
  41583. }
  41584. if (b.length >= 3) {
  41585. poly = new Polygon(b, polygon.shared);
  41586. if (poly.plane)
  41587. back.push(poly);
  41588. }
  41589. break;
  41590. }
  41591. };
  41592. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  41593. // point is on the plane.
  41594. Plane.EPSILON = 1e-5;
  41595. return Plane;
  41596. }());
  41597. // # class Polygon
  41598. // Represents a convex polygon. The vertices used to initialize a polygon must
  41599. // be coplanar and form a convex loop.
  41600. //
  41601. // Each convex polygon has a `shared` property, which is shared between all
  41602. // polygons that are clones of each other or were split from the same polygon.
  41603. // This can be used to define per-polygon properties (such as surface color).
  41604. var Polygon = (function () {
  41605. function Polygon(vertices, shared) {
  41606. this.vertices = vertices;
  41607. this.shared = shared;
  41608. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  41609. }
  41610. Polygon.prototype.clone = function () {
  41611. var vertices = this.vertices.map(function (v) { return v.clone(); });
  41612. return new Polygon(vertices, this.shared);
  41613. };
  41614. Polygon.prototype.flip = function () {
  41615. this.vertices.reverse().map(function (v) { v.flip(); });
  41616. this.plane.flip();
  41617. };
  41618. return Polygon;
  41619. }());
  41620. // # class Node
  41621. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  41622. // by picking a polygon to split along. That polygon (and all other coplanar
  41623. // polygons) are added directly to that node and the other polygons are added to
  41624. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  41625. // no distinction between internal and leaf nodes.
  41626. var Node = (function () {
  41627. function Node(polygons) {
  41628. this.plane = null;
  41629. this.front = null;
  41630. this.back = null;
  41631. this.polygons = [];
  41632. if (polygons) {
  41633. this.build(polygons);
  41634. }
  41635. }
  41636. Node.prototype.clone = function () {
  41637. var node = new Node();
  41638. node.plane = this.plane && this.plane.clone();
  41639. node.front = this.front && this.front.clone();
  41640. node.back = this.back && this.back.clone();
  41641. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  41642. return node;
  41643. };
  41644. // Convert solid space to empty space and empty space to solid space.
  41645. Node.prototype.invert = function () {
  41646. for (var i = 0; i < this.polygons.length; i++) {
  41647. this.polygons[i].flip();
  41648. }
  41649. if (this.plane) {
  41650. this.plane.flip();
  41651. }
  41652. if (this.front) {
  41653. this.front.invert();
  41654. }
  41655. if (this.back) {
  41656. this.back.invert();
  41657. }
  41658. var temp = this.front;
  41659. this.front = this.back;
  41660. this.back = temp;
  41661. };
  41662. // Recursively remove all polygons in `polygons` that are inside this BSP
  41663. // tree.
  41664. Node.prototype.clipPolygons = function (polygons) {
  41665. if (!this.plane)
  41666. return polygons.slice();
  41667. var front = [], back = [];
  41668. for (var i = 0; i < polygons.length; i++) {
  41669. this.plane.splitPolygon(polygons[i], front, back, front, back);
  41670. }
  41671. if (this.front) {
  41672. front = this.front.clipPolygons(front);
  41673. }
  41674. if (this.back) {
  41675. back = this.back.clipPolygons(back);
  41676. }
  41677. else {
  41678. back = [];
  41679. }
  41680. return front.concat(back);
  41681. };
  41682. // Remove all polygons in this BSP tree that are inside the other BSP tree
  41683. // `bsp`.
  41684. Node.prototype.clipTo = function (bsp) {
  41685. this.polygons = bsp.clipPolygons(this.polygons);
  41686. if (this.front)
  41687. this.front.clipTo(bsp);
  41688. if (this.back)
  41689. this.back.clipTo(bsp);
  41690. };
  41691. // Return a list of all polygons in this BSP tree.
  41692. Node.prototype.allPolygons = function () {
  41693. var polygons = this.polygons.slice();
  41694. if (this.front)
  41695. polygons = polygons.concat(this.front.allPolygons());
  41696. if (this.back)
  41697. polygons = polygons.concat(this.back.allPolygons());
  41698. return polygons;
  41699. };
  41700. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  41701. // new polygons are filtered down to the bottom of the tree and become new
  41702. // nodes there. Each set of polygons is partitioned using the first polygon
  41703. // (no heuristic is used to pick a good split).
  41704. Node.prototype.build = function (polygons) {
  41705. if (!polygons.length)
  41706. return;
  41707. if (!this.plane)
  41708. this.plane = polygons[0].plane.clone();
  41709. var front = [], back = [];
  41710. for (var i = 0; i < polygons.length; i++) {
  41711. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  41712. }
  41713. if (front.length) {
  41714. if (!this.front)
  41715. this.front = new Node();
  41716. this.front.build(front);
  41717. }
  41718. if (back.length) {
  41719. if (!this.back)
  41720. this.back = new Node();
  41721. this.back.build(back);
  41722. }
  41723. };
  41724. return Node;
  41725. }());
  41726. var CSG = (function () {
  41727. function CSG() {
  41728. this.polygons = new Array();
  41729. }
  41730. // Convert BABYLON.Mesh to BABYLON.CSG
  41731. CSG.FromMesh = function (mesh) {
  41732. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  41733. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  41734. if (mesh instanceof BABYLON.Mesh) {
  41735. mesh.computeWorldMatrix(true);
  41736. matrix = mesh.getWorldMatrix();
  41737. meshPosition = mesh.position.clone();
  41738. meshRotation = mesh.rotation.clone();
  41739. if (mesh.rotationQuaternion) {
  41740. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  41741. }
  41742. meshScaling = mesh.scaling.clone();
  41743. }
  41744. else {
  41745. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  41746. }
  41747. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41748. var subMeshes = mesh.subMeshes;
  41749. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  41750. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  41751. vertices = [];
  41752. for (var j = 0; j < 3; j++) {
  41753. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  41754. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  41755. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  41756. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  41757. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  41758. vertex = new Vertex(position, normal, uv);
  41759. vertices.push(vertex);
  41760. }
  41761. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  41762. // To handle the case of degenerated triangle
  41763. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  41764. if (polygon.plane)
  41765. polygons.push(polygon);
  41766. }
  41767. }
  41768. var csg = CSG.FromPolygons(polygons);
  41769. csg.matrix = matrix;
  41770. csg.position = meshPosition;
  41771. csg.rotation = meshRotation;
  41772. csg.scaling = meshScaling;
  41773. csg.rotationQuaternion = meshRotationQuaternion;
  41774. currentCSGMeshId++;
  41775. return csg;
  41776. };
  41777. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  41778. CSG.FromPolygons = function (polygons) {
  41779. var csg = new CSG();
  41780. csg.polygons = polygons;
  41781. return csg;
  41782. };
  41783. CSG.prototype.clone = function () {
  41784. var csg = new CSG();
  41785. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  41786. csg.copyTransformAttributes(this);
  41787. return csg;
  41788. };
  41789. CSG.prototype.toPolygons = function () {
  41790. return this.polygons;
  41791. };
  41792. CSG.prototype.union = function (csg) {
  41793. var a = new Node(this.clone().polygons);
  41794. var b = new Node(csg.clone().polygons);
  41795. a.clipTo(b);
  41796. b.clipTo(a);
  41797. b.invert();
  41798. b.clipTo(a);
  41799. b.invert();
  41800. a.build(b.allPolygons());
  41801. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  41802. };
  41803. CSG.prototype.unionInPlace = function (csg) {
  41804. var a = new Node(this.polygons);
  41805. var b = new Node(csg.polygons);
  41806. a.clipTo(b);
  41807. b.clipTo(a);
  41808. b.invert();
  41809. b.clipTo(a);
  41810. b.invert();
  41811. a.build(b.allPolygons());
  41812. this.polygons = a.allPolygons();
  41813. };
  41814. CSG.prototype.subtract = function (csg) {
  41815. var a = new Node(this.clone().polygons);
  41816. var b = new Node(csg.clone().polygons);
  41817. a.invert();
  41818. a.clipTo(b);
  41819. b.clipTo(a);
  41820. b.invert();
  41821. b.clipTo(a);
  41822. b.invert();
  41823. a.build(b.allPolygons());
  41824. a.invert();
  41825. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  41826. };
  41827. CSG.prototype.subtractInPlace = function (csg) {
  41828. var a = new Node(this.polygons);
  41829. var b = new Node(csg.polygons);
  41830. a.invert();
  41831. a.clipTo(b);
  41832. b.clipTo(a);
  41833. b.invert();
  41834. b.clipTo(a);
  41835. b.invert();
  41836. a.build(b.allPolygons());
  41837. a.invert();
  41838. this.polygons = a.allPolygons();
  41839. };
  41840. CSG.prototype.intersect = function (csg) {
  41841. var a = new Node(this.clone().polygons);
  41842. var b = new Node(csg.clone().polygons);
  41843. a.invert();
  41844. b.clipTo(a);
  41845. b.invert();
  41846. a.clipTo(b);
  41847. b.clipTo(a);
  41848. a.build(b.allPolygons());
  41849. a.invert();
  41850. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  41851. };
  41852. CSG.prototype.intersectInPlace = function (csg) {
  41853. var a = new Node(this.polygons);
  41854. var b = new Node(csg.polygons);
  41855. a.invert();
  41856. b.clipTo(a);
  41857. b.invert();
  41858. a.clipTo(b);
  41859. b.clipTo(a);
  41860. a.build(b.allPolygons());
  41861. a.invert();
  41862. this.polygons = a.allPolygons();
  41863. };
  41864. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  41865. // not modified.
  41866. CSG.prototype.inverse = function () {
  41867. var csg = this.clone();
  41868. csg.inverseInPlace();
  41869. return csg;
  41870. };
  41871. CSG.prototype.inverseInPlace = function () {
  41872. this.polygons.map(function (p) { p.flip(); });
  41873. };
  41874. // This is used to keep meshes transformations so they can be restored
  41875. // when we build back a Babylon Mesh
  41876. // NB : All CSG operations are performed in world coordinates
  41877. CSG.prototype.copyTransformAttributes = function (csg) {
  41878. this.matrix = csg.matrix;
  41879. this.position = csg.position;
  41880. this.rotation = csg.rotation;
  41881. this.scaling = csg.scaling;
  41882. this.rotationQuaternion = csg.rotationQuaternion;
  41883. return this;
  41884. };
  41885. // Build Raw mesh from CSG
  41886. // Coordinates here are in world space
  41887. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  41888. var matrix = this.matrix.clone();
  41889. matrix.invert();
  41890. 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;
  41891. if (keepSubMeshes) {
  41892. // Sort Polygons, since subMeshes are indices range
  41893. polygons.sort(function (a, b) {
  41894. if (a.shared.meshId === b.shared.meshId) {
  41895. return a.shared.subMeshId - b.shared.subMeshId;
  41896. }
  41897. else {
  41898. return a.shared.meshId - b.shared.meshId;
  41899. }
  41900. });
  41901. }
  41902. for (var i = 0, il = polygons.length; i < il; i++) {
  41903. polygon = polygons[i];
  41904. // Building SubMeshes
  41905. if (!subMesh_dict[polygon.shared.meshId]) {
  41906. subMesh_dict[polygon.shared.meshId] = {};
  41907. }
  41908. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  41909. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  41910. indexStart: +Infinity,
  41911. indexEnd: -Infinity,
  41912. materialIndex: polygon.shared.materialIndex
  41913. };
  41914. }
  41915. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  41916. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  41917. polygonIndices[0] = 0;
  41918. polygonIndices[1] = j - 1;
  41919. polygonIndices[2] = j;
  41920. for (var k = 0; k < 3; k++) {
  41921. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  41922. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  41923. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  41924. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  41925. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  41926. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  41927. // Check if 2 points can be merged
  41928. if (!(typeof vertex_idx !== 'undefined' &&
  41929. normals[vertex_idx * 3] === localNormal.x &&
  41930. normals[vertex_idx * 3 + 1] === localNormal.y &&
  41931. normals[vertex_idx * 3 + 2] === localNormal.z &&
  41932. uvs[vertex_idx * 2] === uv.x &&
  41933. uvs[vertex_idx * 2 + 1] === uv.y)) {
  41934. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  41935. uvs.push(uv.x, uv.y);
  41936. normals.push(normal.x, normal.y, normal.z);
  41937. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  41938. }
  41939. indices.push(vertex_idx);
  41940. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  41941. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  41942. currentIndex++;
  41943. }
  41944. }
  41945. }
  41946. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  41947. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  41948. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  41949. mesh.setIndices(indices);
  41950. if (keepSubMeshes) {
  41951. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  41952. var materialIndexOffset = 0, materialMaxIndex;
  41953. mesh.subMeshes = new Array();
  41954. for (var m in subMesh_dict) {
  41955. materialMaxIndex = -1;
  41956. for (var sm in subMesh_dict[m]) {
  41957. subMesh_obj = subMesh_dict[m][sm];
  41958. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  41959. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  41960. }
  41961. materialIndexOffset += ++materialMaxIndex;
  41962. }
  41963. }
  41964. return mesh;
  41965. };
  41966. // Build Mesh from CSG taking material and transforms into account
  41967. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  41968. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  41969. mesh.material = material;
  41970. mesh.position.copyFrom(this.position);
  41971. mesh.rotation.copyFrom(this.rotation);
  41972. if (this.rotationQuaternion) {
  41973. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  41974. }
  41975. mesh.scaling.copyFrom(this.scaling);
  41976. mesh.computeWorldMatrix(true);
  41977. return mesh;
  41978. };
  41979. return CSG;
  41980. }());
  41981. BABYLON.CSG = CSG;
  41982. })(BABYLON || (BABYLON = {}));
  41983. var BABYLON;
  41984. (function (BABYLON) {
  41985. var VRDistortionCorrectionPostProcess = (function (_super) {
  41986. __extends(VRDistortionCorrectionPostProcess, _super);
  41987. //ANY
  41988. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  41989. var _this = this;
  41990. _super.call(this, name, "vrDistortionCorrection", [
  41991. 'LensCenter',
  41992. 'Scale',
  41993. 'ScaleIn',
  41994. 'HmdWarpParam'
  41995. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  41996. this._isRightEye = isRightEye;
  41997. this._distortionFactors = vrMetrics.distortionK;
  41998. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  41999. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  42000. this.onSizeChangedObservable.add(function () {
  42001. _this.aspectRatio = _this.width * .5 / _this.height;
  42002. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  42003. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  42004. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  42005. });
  42006. this.onApplyObservable.add(function (effect) {
  42007. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  42008. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  42009. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  42010. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  42011. });
  42012. }
  42013. return VRDistortionCorrectionPostProcess;
  42014. }(BABYLON.PostProcess));
  42015. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  42016. })(BABYLON || (BABYLON = {}));
  42017. // Mainly based on these 2 articles :
  42018. // 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
  42019. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  42020. var BABYLON;
  42021. (function (BABYLON) {
  42022. (function (JoystickAxis) {
  42023. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  42024. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  42025. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  42026. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  42027. var JoystickAxis = BABYLON.JoystickAxis;
  42028. var VirtualJoystick = (function () {
  42029. function VirtualJoystick(leftJoystick) {
  42030. var _this = this;
  42031. if (leftJoystick) {
  42032. this._leftJoystick = true;
  42033. }
  42034. else {
  42035. this._leftJoystick = false;
  42036. }
  42037. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  42038. VirtualJoystick._globalJoystickIndex++;
  42039. // By default left & right arrow keys are moving the X
  42040. // and up & down keys are moving the Y
  42041. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42042. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42043. this.reverseLeftRight = false;
  42044. this.reverseUpDown = false;
  42045. // collections of pointers
  42046. this._touches = new BABYLON.StringDictionary();
  42047. this.deltaPosition = BABYLON.Vector3.Zero();
  42048. this._joystickSensibility = 25;
  42049. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42050. this._rotationSpeed = 25;
  42051. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  42052. this._rotateOnAxisRelativeToMesh = false;
  42053. this._onResize = function (evt) {
  42054. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42055. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42056. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  42057. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  42058. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  42059. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  42060. };
  42061. // injecting a canvas element on top of the canvas 3D game
  42062. if (!VirtualJoystick.vjCanvas) {
  42063. window.addEventListener("resize", this._onResize, false);
  42064. VirtualJoystick.vjCanvas = document.createElement("canvas");
  42065. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42066. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42067. VirtualJoystick.vjCanvas.width = window.innerWidth;
  42068. VirtualJoystick.vjCanvas.height = window.innerHeight;
  42069. VirtualJoystick.vjCanvas.style.width = "100%";
  42070. VirtualJoystick.vjCanvas.style.height = "100%";
  42071. VirtualJoystick.vjCanvas.style.position = "absolute";
  42072. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  42073. VirtualJoystick.vjCanvas.style.top = "0px";
  42074. VirtualJoystick.vjCanvas.style.left = "0px";
  42075. VirtualJoystick.vjCanvas.style.zIndex = "5";
  42076. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  42077. // Support for jQuery PEP polyfill
  42078. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  42079. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  42080. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  42081. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42082. document.body.appendChild(VirtualJoystick.vjCanvas);
  42083. }
  42084. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  42085. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  42086. this.pressed = false;
  42087. // default joystick color
  42088. this._joystickColor = "cyan";
  42089. this._joystickPointerID = -1;
  42090. // current joystick position
  42091. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  42092. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  42093. // origin joystick position
  42094. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  42095. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  42096. this._onPointerDownHandlerRef = function (evt) {
  42097. _this._onPointerDown(evt);
  42098. };
  42099. this._onPointerMoveHandlerRef = function (evt) {
  42100. _this._onPointerMove(evt);
  42101. };
  42102. this._onPointerOutHandlerRef = function (evt) {
  42103. _this._onPointerUp(evt);
  42104. };
  42105. this._onPointerUpHandlerRef = function (evt) {
  42106. _this._onPointerUp(evt);
  42107. };
  42108. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  42109. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  42110. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  42111. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  42112. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  42113. evt.preventDefault(); // Disables system menu
  42114. }, false);
  42115. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42116. }
  42117. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  42118. this._joystickSensibility = newJoystickSensibility;
  42119. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42120. };
  42121. VirtualJoystick.prototype._onPointerDown = function (e) {
  42122. var positionOnScreenCondition;
  42123. e.preventDefault();
  42124. if (this._leftJoystick === true) {
  42125. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  42126. }
  42127. else {
  42128. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  42129. }
  42130. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  42131. // First contact will be dedicated to the virtual joystick
  42132. this._joystickPointerID = e.pointerId;
  42133. this._joystickPointerStartPos.x = e.clientX;
  42134. this._joystickPointerStartPos.y = e.clientY;
  42135. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  42136. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  42137. this._deltaJoystickVector.x = 0;
  42138. this._deltaJoystickVector.y = 0;
  42139. this.pressed = true;
  42140. this._touches.add(e.pointerId.toString(), e);
  42141. }
  42142. else {
  42143. // You can only trigger the action buttons with a joystick declared
  42144. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  42145. this._action();
  42146. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  42147. }
  42148. }
  42149. };
  42150. VirtualJoystick.prototype._onPointerMove = function (e) {
  42151. // If the current pointer is the one associated to the joystick (first touch contact)
  42152. if (this._joystickPointerID == e.pointerId) {
  42153. this._joystickPointerPos.x = e.clientX;
  42154. this._joystickPointerPos.y = e.clientY;
  42155. this._deltaJoystickVector = this._joystickPointerPos.clone();
  42156. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  42157. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  42158. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  42159. switch (this._axisTargetedByLeftAndRight) {
  42160. case JoystickAxis.X:
  42161. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  42162. break;
  42163. case JoystickAxis.Y:
  42164. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  42165. break;
  42166. case JoystickAxis.Z:
  42167. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  42168. break;
  42169. }
  42170. var directionUpDown = this.reverseUpDown ? 1 : -1;
  42171. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  42172. switch (this._axisTargetedByUpAndDown) {
  42173. case JoystickAxis.X:
  42174. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  42175. break;
  42176. case JoystickAxis.Y:
  42177. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  42178. break;
  42179. case JoystickAxis.Z:
  42180. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  42181. break;
  42182. }
  42183. }
  42184. else {
  42185. var data = this._touches.get(e.pointerId.toString());
  42186. if (data) {
  42187. data.x = e.clientX;
  42188. data.y = e.clientY;
  42189. }
  42190. }
  42191. };
  42192. VirtualJoystick.prototype._onPointerUp = function (e) {
  42193. if (this._joystickPointerID == e.pointerId) {
  42194. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  42195. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  42196. this._joystickPointerID = -1;
  42197. this.pressed = false;
  42198. }
  42199. else {
  42200. var touch = this._touches.get(e.pointerId.toString());
  42201. if (touch) {
  42202. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  42203. }
  42204. }
  42205. this._deltaJoystickVector.x = 0;
  42206. this._deltaJoystickVector.y = 0;
  42207. this._touches.remove(e.pointerId.toString());
  42208. };
  42209. /**
  42210. * Change the color of the virtual joystick
  42211. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  42212. */
  42213. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  42214. this._joystickColor = newColor;
  42215. };
  42216. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  42217. this._action = action;
  42218. };
  42219. // Define which axis you'd like to control for left & right
  42220. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  42221. switch (axis) {
  42222. case JoystickAxis.X:
  42223. case JoystickAxis.Y:
  42224. case JoystickAxis.Z:
  42225. this._axisTargetedByLeftAndRight = axis;
  42226. break;
  42227. default:
  42228. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42229. break;
  42230. }
  42231. };
  42232. // Define which axis you'd like to control for up & down
  42233. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  42234. switch (axis) {
  42235. case JoystickAxis.X:
  42236. case JoystickAxis.Y:
  42237. case JoystickAxis.Z:
  42238. this._axisTargetedByUpAndDown = axis;
  42239. break;
  42240. default:
  42241. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42242. break;
  42243. }
  42244. };
  42245. VirtualJoystick.prototype._clearCanvas = function () {
  42246. if (this._leftJoystick) {
  42247. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  42248. }
  42249. else {
  42250. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  42251. }
  42252. };
  42253. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  42254. var _this = this;
  42255. if (this.pressed) {
  42256. this._touches.forEach(function (touch) {
  42257. if (touch.pointerId === _this._joystickPointerID) {
  42258. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  42259. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  42260. VirtualJoystick.vjCanvasContext.beginPath();
  42261. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  42262. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42263. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  42264. VirtualJoystick.vjCanvasContext.stroke();
  42265. VirtualJoystick.vjCanvasContext.closePath();
  42266. VirtualJoystick.vjCanvasContext.beginPath();
  42267. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42268. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42269. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  42270. VirtualJoystick.vjCanvasContext.stroke();
  42271. VirtualJoystick.vjCanvasContext.closePath();
  42272. VirtualJoystick.vjCanvasContext.beginPath();
  42273. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42274. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  42275. VirtualJoystick.vjCanvasContext.stroke();
  42276. VirtualJoystick.vjCanvasContext.closePath();
  42277. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  42278. }
  42279. else {
  42280. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  42281. VirtualJoystick.vjCanvasContext.beginPath();
  42282. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  42283. VirtualJoystick.vjCanvasContext.beginPath();
  42284. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  42285. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  42286. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  42287. VirtualJoystick.vjCanvasContext.stroke();
  42288. VirtualJoystick.vjCanvasContext.closePath();
  42289. touch.prevX = touch.x;
  42290. touch.prevY = touch.y;
  42291. }
  42292. ;
  42293. });
  42294. }
  42295. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42296. };
  42297. VirtualJoystick.prototype.releaseCanvas = function () {
  42298. if (VirtualJoystick.vjCanvas) {
  42299. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  42300. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  42301. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  42302. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  42303. window.removeEventListener("resize", this._onResize);
  42304. document.body.removeChild(VirtualJoystick.vjCanvas);
  42305. VirtualJoystick.vjCanvas = null;
  42306. }
  42307. };
  42308. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  42309. VirtualJoystick._globalJoystickIndex = 0;
  42310. return VirtualJoystick;
  42311. }());
  42312. BABYLON.VirtualJoystick = VirtualJoystick;
  42313. })(BABYLON || (BABYLON = {}));
  42314. var BABYLON;
  42315. (function (BABYLON) {
  42316. // We're mainly based on the logic defined into the FreeCamera code
  42317. var VirtualJoysticksCamera = (function (_super) {
  42318. __extends(VirtualJoysticksCamera, _super);
  42319. function VirtualJoysticksCamera(name, position, scene) {
  42320. _super.call(this, name, position, scene);
  42321. this.inputs.addVirtualJoystick();
  42322. }
  42323. return VirtualJoysticksCamera;
  42324. }(BABYLON.FreeCamera));
  42325. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  42326. })(BABYLON || (BABYLON = {}));
  42327. var BABYLON;
  42328. (function (BABYLON) {
  42329. var FreeCameraVirtualJoystickInput = (function () {
  42330. function FreeCameraVirtualJoystickInput() {
  42331. }
  42332. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  42333. return this._leftjoystick;
  42334. };
  42335. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  42336. return this._rightjoystick;
  42337. };
  42338. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  42339. if (this._leftjoystick) {
  42340. var camera = this.camera;
  42341. var speed = camera._computeLocalCameraSpeed() * 50;
  42342. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  42343. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  42344. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  42345. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  42346. if (!this._leftjoystick.pressed) {
  42347. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  42348. }
  42349. if (!this._rightjoystick.pressed) {
  42350. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  42351. }
  42352. }
  42353. };
  42354. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  42355. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  42356. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  42357. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  42358. this._leftjoystick.setJoystickSensibility(0.15);
  42359. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  42360. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  42361. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  42362. this._rightjoystick.reverseUpDown = true;
  42363. this._rightjoystick.setJoystickSensibility(0.05);
  42364. this._rightjoystick.setJoystickColor("yellow");
  42365. };
  42366. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  42367. this._leftjoystick.releaseCanvas();
  42368. this._rightjoystick.releaseCanvas();
  42369. };
  42370. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  42371. return "FreeCameraVirtualJoystickInput";
  42372. };
  42373. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  42374. return "virtualJoystick";
  42375. };
  42376. return FreeCameraVirtualJoystickInput;
  42377. }());
  42378. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  42379. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  42380. })(BABYLON || (BABYLON = {}));
  42381. var BABYLON;
  42382. (function (BABYLON) {
  42383. var AnaglyphPostProcess = (function (_super) {
  42384. __extends(AnaglyphPostProcess, _super);
  42385. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  42386. var _this = this;
  42387. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  42388. this._passedProcess = rigCameras[0]._rigPostProcess;
  42389. this.onApplyObservable.add(function (effect) {
  42390. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  42391. });
  42392. }
  42393. return AnaglyphPostProcess;
  42394. }(BABYLON.PostProcess));
  42395. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  42396. })(BABYLON || (BABYLON = {}));
  42397. var BABYLON;
  42398. (function (BABYLON) {
  42399. var OutlineRenderer = (function () {
  42400. function OutlineRenderer(scene) {
  42401. this._scene = scene;
  42402. }
  42403. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  42404. var _this = this;
  42405. if (useOverlay === void 0) { useOverlay = false; }
  42406. var scene = this._scene;
  42407. var engine = this._scene.getEngine();
  42408. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  42409. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  42410. return;
  42411. }
  42412. var mesh = subMesh.getRenderingMesh();
  42413. var material = subMesh.getMaterial();
  42414. engine.enableEffect(this._effect);
  42415. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  42416. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  42417. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  42418. // Bones
  42419. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42420. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  42421. }
  42422. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  42423. // Alpha test
  42424. if (material && material.needAlphaTesting()) {
  42425. var alphaTexture = material.getAlphaTestTexture();
  42426. this._effect.setTexture("diffuseSampler", alphaTexture);
  42427. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  42428. }
  42429. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  42430. };
  42431. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  42432. var defines = [];
  42433. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  42434. var mesh = subMesh.getMesh();
  42435. var material = subMesh.getMaterial();
  42436. // Alpha test
  42437. if (material && material.needAlphaTesting()) {
  42438. defines.push("#define ALPHATEST");
  42439. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42440. attribs.push(BABYLON.VertexBuffer.UVKind);
  42441. defines.push("#define UV1");
  42442. }
  42443. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  42444. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42445. defines.push("#define UV2");
  42446. }
  42447. }
  42448. // Bones
  42449. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42450. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42451. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42452. if (mesh.numBoneInfluencers > 4) {
  42453. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42454. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42455. }
  42456. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42457. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42458. }
  42459. else {
  42460. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42461. }
  42462. // Instances
  42463. if (useInstances) {
  42464. defines.push("#define INSTANCES");
  42465. attribs.push("world0");
  42466. attribs.push("world1");
  42467. attribs.push("world2");
  42468. attribs.push("world3");
  42469. }
  42470. // Get correct effect
  42471. var join = defines.join("\n");
  42472. if (this._cachedDefines !== join) {
  42473. this._cachedDefines = join;
  42474. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  42475. }
  42476. return this._effect.isReady();
  42477. };
  42478. return OutlineRenderer;
  42479. }());
  42480. BABYLON.OutlineRenderer = OutlineRenderer;
  42481. })(BABYLON || (BABYLON = {}));
  42482. var BABYLON;
  42483. (function (BABYLON) {
  42484. var MeshAssetTask = (function () {
  42485. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  42486. this.name = name;
  42487. this.meshesNames = meshesNames;
  42488. this.rootUrl = rootUrl;
  42489. this.sceneFilename = sceneFilename;
  42490. this.isCompleted = false;
  42491. }
  42492. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42493. var _this = this;
  42494. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  42495. _this.loadedMeshes = meshes;
  42496. _this.loadedParticleSystems = particleSystems;
  42497. _this.loadedSkeletons = skeletons;
  42498. _this.isCompleted = true;
  42499. if (_this.onSuccess) {
  42500. _this.onSuccess(_this);
  42501. }
  42502. onSuccess();
  42503. }, null, function () {
  42504. if (_this.onError) {
  42505. _this.onError(_this);
  42506. }
  42507. onError();
  42508. });
  42509. };
  42510. return MeshAssetTask;
  42511. }());
  42512. BABYLON.MeshAssetTask = MeshAssetTask;
  42513. var TextFileAssetTask = (function () {
  42514. function TextFileAssetTask(name, url) {
  42515. this.name = name;
  42516. this.url = url;
  42517. this.isCompleted = false;
  42518. }
  42519. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42520. var _this = this;
  42521. BABYLON.Tools.LoadFile(this.url, function (data) {
  42522. _this.text = data;
  42523. _this.isCompleted = true;
  42524. if (_this.onSuccess) {
  42525. _this.onSuccess(_this);
  42526. }
  42527. onSuccess();
  42528. }, null, scene.database, false, function () {
  42529. if (_this.onError) {
  42530. _this.onError(_this);
  42531. }
  42532. onError();
  42533. });
  42534. };
  42535. return TextFileAssetTask;
  42536. }());
  42537. BABYLON.TextFileAssetTask = TextFileAssetTask;
  42538. var BinaryFileAssetTask = (function () {
  42539. function BinaryFileAssetTask(name, url) {
  42540. this.name = name;
  42541. this.url = url;
  42542. this.isCompleted = false;
  42543. }
  42544. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42545. var _this = this;
  42546. BABYLON.Tools.LoadFile(this.url, function (data) {
  42547. _this.data = data;
  42548. _this.isCompleted = true;
  42549. if (_this.onSuccess) {
  42550. _this.onSuccess(_this);
  42551. }
  42552. onSuccess();
  42553. }, null, scene.database, true, function () {
  42554. if (_this.onError) {
  42555. _this.onError(_this);
  42556. }
  42557. onError();
  42558. });
  42559. };
  42560. return BinaryFileAssetTask;
  42561. }());
  42562. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  42563. var ImageAssetTask = (function () {
  42564. function ImageAssetTask(name, url) {
  42565. this.name = name;
  42566. this.url = url;
  42567. this.isCompleted = false;
  42568. }
  42569. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42570. var _this = this;
  42571. var img = new Image();
  42572. BABYLON.Tools.SetCorsBehavior(this.url, img);
  42573. img.onload = function () {
  42574. _this.image = img;
  42575. _this.isCompleted = true;
  42576. if (_this.onSuccess) {
  42577. _this.onSuccess(_this);
  42578. }
  42579. onSuccess();
  42580. };
  42581. img.onerror = function () {
  42582. if (_this.onError) {
  42583. _this.onError(_this);
  42584. }
  42585. onError();
  42586. };
  42587. img.src = this.url;
  42588. };
  42589. return ImageAssetTask;
  42590. }());
  42591. BABYLON.ImageAssetTask = ImageAssetTask;
  42592. var TextureAssetTask = (function () {
  42593. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  42594. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42595. this.name = name;
  42596. this.url = url;
  42597. this.noMipmap = noMipmap;
  42598. this.invertY = invertY;
  42599. this.samplingMode = samplingMode;
  42600. this.isCompleted = false;
  42601. }
  42602. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42603. var _this = this;
  42604. var onload = function () {
  42605. _this.isCompleted = true;
  42606. if (_this.onSuccess) {
  42607. _this.onSuccess(_this);
  42608. }
  42609. onSuccess();
  42610. };
  42611. var onerror = function () {
  42612. if (_this.onError) {
  42613. _this.onError(_this);
  42614. }
  42615. onError();
  42616. };
  42617. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  42618. };
  42619. return TextureAssetTask;
  42620. }());
  42621. BABYLON.TextureAssetTask = TextureAssetTask;
  42622. var CubeTextureAssetTask = (function () {
  42623. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  42624. this.name = name;
  42625. this.url = url;
  42626. this.extensions = extensions;
  42627. this.noMipmap = noMipmap;
  42628. this.files = files;
  42629. this.isCompleted = false;
  42630. }
  42631. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  42632. var _this = this;
  42633. var onload = function () {
  42634. _this.isCompleted = true;
  42635. if (_this.onSuccess) {
  42636. _this.onSuccess(_this);
  42637. }
  42638. onSuccess();
  42639. };
  42640. var onerror = function () {
  42641. if (_this.onError) {
  42642. _this.onError(_this);
  42643. }
  42644. onError();
  42645. };
  42646. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  42647. };
  42648. return CubeTextureAssetTask;
  42649. }());
  42650. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  42651. var AssetsManager = (function () {
  42652. function AssetsManager(scene) {
  42653. this.tasks = new Array();
  42654. this.waitingTasksCount = 0;
  42655. this.useDefaultLoadingScreen = true;
  42656. this._scene = scene;
  42657. }
  42658. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  42659. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  42660. this.tasks.push(task);
  42661. return task;
  42662. };
  42663. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  42664. var task = new TextFileAssetTask(taskName, url);
  42665. this.tasks.push(task);
  42666. return task;
  42667. };
  42668. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  42669. var task = new BinaryFileAssetTask(taskName, url);
  42670. this.tasks.push(task);
  42671. return task;
  42672. };
  42673. AssetsManager.prototype.addImageTask = function (taskName, url) {
  42674. var task = new ImageAssetTask(taskName, url);
  42675. this.tasks.push(task);
  42676. return task;
  42677. };
  42678. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  42679. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42680. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  42681. this.tasks.push(task);
  42682. return task;
  42683. };
  42684. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  42685. this.waitingTasksCount--;
  42686. if (this.waitingTasksCount === 0) {
  42687. if (this.onFinish) {
  42688. this.onFinish(this.tasks);
  42689. }
  42690. this._scene.getEngine().hideLoadingUI();
  42691. }
  42692. };
  42693. AssetsManager.prototype._runTask = function (task) {
  42694. var _this = this;
  42695. task.run(this._scene, function () {
  42696. if (_this.onTaskSuccess) {
  42697. _this.onTaskSuccess(task);
  42698. }
  42699. _this._decreaseWaitingTasksCount();
  42700. }, function () {
  42701. if (_this.onTaskError) {
  42702. _this.onTaskError(task);
  42703. }
  42704. _this._decreaseWaitingTasksCount();
  42705. });
  42706. };
  42707. AssetsManager.prototype.reset = function () {
  42708. this.tasks = new Array();
  42709. return this;
  42710. };
  42711. AssetsManager.prototype.load = function () {
  42712. this.waitingTasksCount = this.tasks.length;
  42713. if (this.waitingTasksCount === 0) {
  42714. if (this.onFinish) {
  42715. this.onFinish(this.tasks);
  42716. }
  42717. return this;
  42718. }
  42719. if (this.useDefaultLoadingScreen) {
  42720. this._scene.getEngine().displayLoadingUI();
  42721. }
  42722. for (var index = 0; index < this.tasks.length; index++) {
  42723. var task = this.tasks[index];
  42724. this._runTask(task);
  42725. }
  42726. return this;
  42727. };
  42728. return AssetsManager;
  42729. }());
  42730. BABYLON.AssetsManager = AssetsManager;
  42731. })(BABYLON || (BABYLON = {}));
  42732. var BABYLON;
  42733. (function (BABYLON) {
  42734. var VRCameraMetrics = (function () {
  42735. function VRCameraMetrics() {
  42736. this.compensateDistortion = true;
  42737. }
  42738. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  42739. get: function () {
  42740. return this.hResolution / (2 * this.vResolution);
  42741. },
  42742. enumerable: true,
  42743. configurable: true
  42744. });
  42745. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  42746. get: function () {
  42747. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  42748. },
  42749. enumerable: true,
  42750. configurable: true
  42751. });
  42752. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  42753. get: function () {
  42754. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  42755. var h = (4 * meters) / this.hScreenSize;
  42756. return BABYLON.Matrix.Translation(h, 0, 0);
  42757. },
  42758. enumerable: true,
  42759. configurable: true
  42760. });
  42761. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  42762. get: function () {
  42763. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  42764. var h = (4 * meters) / this.hScreenSize;
  42765. return BABYLON.Matrix.Translation(-h, 0, 0);
  42766. },
  42767. enumerable: true,
  42768. configurable: true
  42769. });
  42770. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  42771. get: function () {
  42772. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  42773. },
  42774. enumerable: true,
  42775. configurable: true
  42776. });
  42777. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  42778. get: function () {
  42779. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  42780. },
  42781. enumerable: true,
  42782. configurable: true
  42783. });
  42784. VRCameraMetrics.GetDefault = function () {
  42785. var result = new VRCameraMetrics();
  42786. result.hResolution = 1280;
  42787. result.vResolution = 800;
  42788. result.hScreenSize = 0.149759993;
  42789. result.vScreenSize = 0.0935999975;
  42790. result.vScreenCenter = 0.0467999987,
  42791. result.eyeToScreenDistance = 0.0410000011;
  42792. result.lensSeparationDistance = 0.0635000020;
  42793. result.interpupillaryDistance = 0.0640000030;
  42794. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  42795. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  42796. result.postProcessScaleFactor = 1.714605507808412;
  42797. result.lensCenterOffset = 0.151976421;
  42798. return result;
  42799. };
  42800. return VRCameraMetrics;
  42801. }());
  42802. BABYLON.VRCameraMetrics = VRCameraMetrics;
  42803. })(BABYLON || (BABYLON = {}));
  42804. var BABYLON;
  42805. (function (BABYLON) {
  42806. var WebVRFreeCamera = (function (_super) {
  42807. __extends(WebVRFreeCamera, _super);
  42808. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  42809. var _this = this;
  42810. if (compensateDistortion === void 0) { compensateDistortion = false; }
  42811. if (webVROptions === void 0) { webVROptions = {}; }
  42812. _super.call(this, name, position, scene);
  42813. this.webVROptions = webVROptions;
  42814. this._vrDevice = null;
  42815. this._cacheState = null;
  42816. this._vrEnabled = false;
  42817. //enable VR
  42818. this.getEngine().initWebVR();
  42819. if (!this.getEngine().vrDisplaysPromise) {
  42820. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  42821. }
  42822. else {
  42823. //TODO get the metrics updated using the device's eye parameters!
  42824. //TODO also check that the device has the right capabilities!
  42825. this.getEngine().vrDisplaysPromise.then(function (devices) {
  42826. if (devices.length > 0) {
  42827. _this._vrEnabled = true;
  42828. if (_this.webVROptions.displayName) {
  42829. var found = devices.some(function (device) {
  42830. if (device.displayName === _this.webVROptions.displayName) {
  42831. _this._vrDevice = device;
  42832. return true;
  42833. }
  42834. else {
  42835. return false;
  42836. }
  42837. });
  42838. if (!found) {
  42839. _this._vrDevice = devices[0];
  42840. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  42841. }
  42842. }
  42843. else {
  42844. //choose the first one
  42845. _this._vrDevice = devices[0];
  42846. }
  42847. //reset the rig parameters.
  42848. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice });
  42849. }
  42850. else {
  42851. BABYLON.Tools.Error("No WebVR devices found!");
  42852. }
  42853. });
  42854. }
  42855. this.rotationQuaternion = new BABYLON.Quaternion();
  42856. this._quaternionCache = new BABYLON.Quaternion();
  42857. }
  42858. WebVRFreeCamera.prototype._checkInputs = function () {
  42859. if (this._vrEnabled) {
  42860. var currentPost = this._vrDevice.getPose();
  42861. //make sure we have data
  42862. if (currentPost && currentPost.orientation) {
  42863. this._cacheState = currentPost;
  42864. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], this._cacheState.orientation[2], this._cacheState.orientation[3]);
  42865. if (this.webVROptions.trackPosition && this._cacheState.position) {
  42866. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  42867. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  42868. }
  42869. //Flip in XY plane
  42870. this.rotationQuaternion.z *= -1;
  42871. this.rotationQuaternion.w *= -1;
  42872. }
  42873. }
  42874. _super.prototype._checkInputs.call(this);
  42875. };
  42876. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  42877. _super.prototype.attachControl.call(this, element, noPreventDefault);
  42878. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42879. if (this._vrEnabled) {
  42880. this.getEngine().enableVR(this._vrDevice);
  42881. }
  42882. };
  42883. WebVRFreeCamera.prototype.detachControl = function (element) {
  42884. _super.prototype.detachControl.call(this, element);
  42885. this._vrEnabled = false;
  42886. this.getEngine().disableVR();
  42887. };
  42888. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  42889. //Backwards comp.
  42890. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  42891. //this.getEngine().switchFullscreen(requestPointerlock);
  42892. };
  42893. WebVRFreeCamera.prototype.getTypeName = function () {
  42894. return "WebVRFreeCamera";
  42895. };
  42896. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  42897. //uses the vrDisplay's "resetPose()".
  42898. //pitch and roll won't be affected.
  42899. this._vrDevice.resetPose();
  42900. };
  42901. return WebVRFreeCamera;
  42902. }(BABYLON.FreeCamera));
  42903. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  42904. })(BABYLON || (BABYLON = {}));
  42905. var BABYLON;
  42906. (function (BABYLON) {
  42907. // Standard optimizations
  42908. var SceneOptimization = (function () {
  42909. function SceneOptimization(priority) {
  42910. if (priority === void 0) { priority = 0; }
  42911. this.priority = priority;
  42912. this.apply = function (scene) {
  42913. return true; // Return true if everything that can be done was applied
  42914. };
  42915. }
  42916. return SceneOptimization;
  42917. }());
  42918. BABYLON.SceneOptimization = SceneOptimization;
  42919. var TextureOptimization = (function (_super) {
  42920. __extends(TextureOptimization, _super);
  42921. function TextureOptimization(priority, maximumSize) {
  42922. var _this = this;
  42923. if (priority === void 0) { priority = 0; }
  42924. if (maximumSize === void 0) { maximumSize = 1024; }
  42925. _super.call(this, priority);
  42926. this.priority = priority;
  42927. this.maximumSize = maximumSize;
  42928. this.apply = function (scene) {
  42929. var allDone = true;
  42930. for (var index = 0; index < scene.textures.length; index++) {
  42931. var texture = scene.textures[index];
  42932. if (!texture.canRescale) {
  42933. continue;
  42934. }
  42935. var currentSize = texture.getSize();
  42936. var maxDimension = Math.max(currentSize.width, currentSize.height);
  42937. if (maxDimension > _this.maximumSize) {
  42938. texture.scale(0.5);
  42939. allDone = false;
  42940. }
  42941. }
  42942. return allDone;
  42943. };
  42944. }
  42945. return TextureOptimization;
  42946. }(SceneOptimization));
  42947. BABYLON.TextureOptimization = TextureOptimization;
  42948. var HardwareScalingOptimization = (function (_super) {
  42949. __extends(HardwareScalingOptimization, _super);
  42950. function HardwareScalingOptimization(priority, maximumScale) {
  42951. var _this = this;
  42952. if (priority === void 0) { priority = 0; }
  42953. if (maximumScale === void 0) { maximumScale = 2; }
  42954. _super.call(this, priority);
  42955. this.priority = priority;
  42956. this.maximumScale = maximumScale;
  42957. this._currentScale = 1;
  42958. this.apply = function (scene) {
  42959. _this._currentScale++;
  42960. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  42961. return _this._currentScale >= _this.maximumScale;
  42962. };
  42963. }
  42964. return HardwareScalingOptimization;
  42965. }(SceneOptimization));
  42966. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  42967. var ShadowsOptimization = (function (_super) {
  42968. __extends(ShadowsOptimization, _super);
  42969. function ShadowsOptimization() {
  42970. _super.apply(this, arguments);
  42971. this.apply = function (scene) {
  42972. scene.shadowsEnabled = false;
  42973. return true;
  42974. };
  42975. }
  42976. return ShadowsOptimization;
  42977. }(SceneOptimization));
  42978. BABYLON.ShadowsOptimization = ShadowsOptimization;
  42979. var PostProcessesOptimization = (function (_super) {
  42980. __extends(PostProcessesOptimization, _super);
  42981. function PostProcessesOptimization() {
  42982. _super.apply(this, arguments);
  42983. this.apply = function (scene) {
  42984. scene.postProcessesEnabled = false;
  42985. return true;
  42986. };
  42987. }
  42988. return PostProcessesOptimization;
  42989. }(SceneOptimization));
  42990. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  42991. var LensFlaresOptimization = (function (_super) {
  42992. __extends(LensFlaresOptimization, _super);
  42993. function LensFlaresOptimization() {
  42994. _super.apply(this, arguments);
  42995. this.apply = function (scene) {
  42996. scene.lensFlaresEnabled = false;
  42997. return true;
  42998. };
  42999. }
  43000. return LensFlaresOptimization;
  43001. }(SceneOptimization));
  43002. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  43003. var ParticlesOptimization = (function (_super) {
  43004. __extends(ParticlesOptimization, _super);
  43005. function ParticlesOptimization() {
  43006. _super.apply(this, arguments);
  43007. this.apply = function (scene) {
  43008. scene.particlesEnabled = false;
  43009. return true;
  43010. };
  43011. }
  43012. return ParticlesOptimization;
  43013. }(SceneOptimization));
  43014. BABYLON.ParticlesOptimization = ParticlesOptimization;
  43015. var RenderTargetsOptimization = (function (_super) {
  43016. __extends(RenderTargetsOptimization, _super);
  43017. function RenderTargetsOptimization() {
  43018. _super.apply(this, arguments);
  43019. this.apply = function (scene) {
  43020. scene.renderTargetsEnabled = false;
  43021. return true;
  43022. };
  43023. }
  43024. return RenderTargetsOptimization;
  43025. }(SceneOptimization));
  43026. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  43027. var MergeMeshesOptimization = (function (_super) {
  43028. __extends(MergeMeshesOptimization, _super);
  43029. function MergeMeshesOptimization() {
  43030. var _this = this;
  43031. _super.apply(this, arguments);
  43032. this._canBeMerged = function (abstractMesh) {
  43033. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  43034. return false;
  43035. }
  43036. var mesh = abstractMesh;
  43037. if (!mesh.isVisible || !mesh.isEnabled()) {
  43038. return false;
  43039. }
  43040. if (mesh.instances.length > 0) {
  43041. return false;
  43042. }
  43043. if (mesh.skeleton || mesh.hasLODLevels) {
  43044. return false;
  43045. }
  43046. if (mesh.parent) {
  43047. return false;
  43048. }
  43049. return true;
  43050. };
  43051. this.apply = function (scene, updateSelectionTree) {
  43052. var globalPool = scene.meshes.slice(0);
  43053. var globalLength = globalPool.length;
  43054. for (var index = 0; index < globalLength; index++) {
  43055. var currentPool = new Array();
  43056. var current = globalPool[index];
  43057. // Checks
  43058. if (!_this._canBeMerged(current)) {
  43059. continue;
  43060. }
  43061. currentPool.push(current);
  43062. // Find compatible meshes
  43063. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  43064. var otherMesh = globalPool[subIndex];
  43065. if (!_this._canBeMerged(otherMesh)) {
  43066. continue;
  43067. }
  43068. if (otherMesh.material !== current.material) {
  43069. continue;
  43070. }
  43071. if (otherMesh.checkCollisions !== current.checkCollisions) {
  43072. continue;
  43073. }
  43074. currentPool.push(otherMesh);
  43075. globalLength--;
  43076. globalPool.splice(subIndex, 1);
  43077. subIndex--;
  43078. }
  43079. if (currentPool.length < 2) {
  43080. continue;
  43081. }
  43082. // Merge meshes
  43083. BABYLON.Mesh.MergeMeshes(currentPool);
  43084. }
  43085. if (updateSelectionTree != undefined) {
  43086. if (updateSelectionTree) {
  43087. scene.createOrUpdateSelectionOctree();
  43088. }
  43089. }
  43090. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  43091. scene.createOrUpdateSelectionOctree();
  43092. }
  43093. return true;
  43094. };
  43095. }
  43096. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  43097. get: function () {
  43098. return MergeMeshesOptimization._UpdateSelectionTree;
  43099. },
  43100. set: function (value) {
  43101. MergeMeshesOptimization._UpdateSelectionTree = value;
  43102. },
  43103. enumerable: true,
  43104. configurable: true
  43105. });
  43106. MergeMeshesOptimization._UpdateSelectionTree = false;
  43107. return MergeMeshesOptimization;
  43108. }(SceneOptimization));
  43109. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  43110. // Options
  43111. var SceneOptimizerOptions = (function () {
  43112. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  43113. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  43114. if (trackerDuration === void 0) { trackerDuration = 2000; }
  43115. this.targetFrameRate = targetFrameRate;
  43116. this.trackerDuration = trackerDuration;
  43117. this.optimizations = new Array();
  43118. }
  43119. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  43120. var result = new SceneOptimizerOptions(targetFrameRate);
  43121. var priority = 0;
  43122. result.optimizations.push(new MergeMeshesOptimization(priority));
  43123. result.optimizations.push(new ShadowsOptimization(priority));
  43124. result.optimizations.push(new LensFlaresOptimization(priority));
  43125. // Next priority
  43126. priority++;
  43127. result.optimizations.push(new PostProcessesOptimization(priority));
  43128. result.optimizations.push(new ParticlesOptimization(priority));
  43129. // Next priority
  43130. priority++;
  43131. result.optimizations.push(new TextureOptimization(priority, 1024));
  43132. return result;
  43133. };
  43134. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  43135. var result = new SceneOptimizerOptions(targetFrameRate);
  43136. var priority = 0;
  43137. result.optimizations.push(new MergeMeshesOptimization(priority));
  43138. result.optimizations.push(new ShadowsOptimization(priority));
  43139. result.optimizations.push(new LensFlaresOptimization(priority));
  43140. // Next priority
  43141. priority++;
  43142. result.optimizations.push(new PostProcessesOptimization(priority));
  43143. result.optimizations.push(new ParticlesOptimization(priority));
  43144. // Next priority
  43145. priority++;
  43146. result.optimizations.push(new TextureOptimization(priority, 512));
  43147. // Next priority
  43148. priority++;
  43149. result.optimizations.push(new RenderTargetsOptimization(priority));
  43150. // Next priority
  43151. priority++;
  43152. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  43153. return result;
  43154. };
  43155. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  43156. var result = new SceneOptimizerOptions(targetFrameRate);
  43157. var priority = 0;
  43158. result.optimizations.push(new MergeMeshesOptimization(priority));
  43159. result.optimizations.push(new ShadowsOptimization(priority));
  43160. result.optimizations.push(new LensFlaresOptimization(priority));
  43161. // Next priority
  43162. priority++;
  43163. result.optimizations.push(new PostProcessesOptimization(priority));
  43164. result.optimizations.push(new ParticlesOptimization(priority));
  43165. // Next priority
  43166. priority++;
  43167. result.optimizations.push(new TextureOptimization(priority, 256));
  43168. // Next priority
  43169. priority++;
  43170. result.optimizations.push(new RenderTargetsOptimization(priority));
  43171. // Next priority
  43172. priority++;
  43173. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  43174. return result;
  43175. };
  43176. return SceneOptimizerOptions;
  43177. }());
  43178. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  43179. // Scene optimizer tool
  43180. var SceneOptimizer = (function () {
  43181. function SceneOptimizer() {
  43182. }
  43183. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  43184. // TODO: add an epsilon
  43185. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  43186. if (onSuccess) {
  43187. onSuccess();
  43188. }
  43189. return;
  43190. }
  43191. // Apply current level of optimizations
  43192. var allDone = true;
  43193. var noOptimizationApplied = true;
  43194. for (var index = 0; index < options.optimizations.length; index++) {
  43195. var optimization = options.optimizations[index];
  43196. if (optimization.priority === currentPriorityLevel) {
  43197. noOptimizationApplied = false;
  43198. allDone = allDone && optimization.apply(scene);
  43199. }
  43200. }
  43201. // If no optimization was applied, this is a failure :(
  43202. if (noOptimizationApplied) {
  43203. if (onFailure) {
  43204. onFailure();
  43205. }
  43206. return;
  43207. }
  43208. // If all optimizations were done, move to next level
  43209. if (allDone) {
  43210. currentPriorityLevel++;
  43211. }
  43212. // Let's the system running for a specific amount of time before checking FPS
  43213. scene.executeWhenReady(function () {
  43214. setTimeout(function () {
  43215. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  43216. }, options.trackerDuration);
  43217. });
  43218. };
  43219. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  43220. if (!options) {
  43221. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  43222. }
  43223. // Let's the system running for a specific amount of time before checking FPS
  43224. scene.executeWhenReady(function () {
  43225. setTimeout(function () {
  43226. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  43227. }, options.trackerDuration);
  43228. });
  43229. };
  43230. return SceneOptimizer;
  43231. }());
  43232. BABYLON.SceneOptimizer = SceneOptimizer;
  43233. })(BABYLON || (BABYLON = {}));
  43234. var BABYLON;
  43235. (function (BABYLON) {
  43236. var Internals;
  43237. (function (Internals) {
  43238. var MeshLODLevel = (function () {
  43239. function MeshLODLevel(distance, mesh) {
  43240. this.distance = distance;
  43241. this.mesh = mesh;
  43242. }
  43243. return MeshLODLevel;
  43244. }());
  43245. Internals.MeshLODLevel = MeshLODLevel;
  43246. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43247. })(BABYLON || (BABYLON = {}));
  43248. var BABYLON;
  43249. (function (BABYLON) {
  43250. var RawTexture = (function (_super) {
  43251. __extends(RawTexture, _super);
  43252. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  43253. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43254. if (invertY === void 0) { invertY = false; }
  43255. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43256. _super.call(this, null, scene, !generateMipMaps, invertY);
  43257. this.format = format;
  43258. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  43259. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43260. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43261. }
  43262. RawTexture.prototype.update = function (data) {
  43263. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  43264. };
  43265. // Statics
  43266. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43267. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43268. if (invertY === void 0) { invertY = false; }
  43269. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43270. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  43271. };
  43272. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43273. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43274. if (invertY === void 0) { invertY = false; }
  43275. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43276. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43277. };
  43278. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43279. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43280. if (invertY === void 0) { invertY = false; }
  43281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43282. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43283. };
  43284. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43285. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43286. if (invertY === void 0) { invertY = false; }
  43287. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43288. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  43289. };
  43290. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43291. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43292. if (invertY === void 0) { invertY = false; }
  43293. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43294. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  43295. };
  43296. return RawTexture;
  43297. }(BABYLON.Texture));
  43298. BABYLON.RawTexture = RawTexture;
  43299. })(BABYLON || (BABYLON = {}));
  43300. var BABYLON;
  43301. (function (BABYLON) {
  43302. var IndexedVector2 = (function (_super) {
  43303. __extends(IndexedVector2, _super);
  43304. function IndexedVector2(original, index) {
  43305. _super.call(this, original.x, original.y);
  43306. this.index = index;
  43307. }
  43308. return IndexedVector2;
  43309. }(BABYLON.Vector2));
  43310. var PolygonPoints = (function () {
  43311. function PolygonPoints() {
  43312. this.elements = new Array();
  43313. }
  43314. PolygonPoints.prototype.add = function (originalPoints) {
  43315. var _this = this;
  43316. var result = new Array();
  43317. originalPoints.forEach(function (point) {
  43318. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  43319. var newPoint = new IndexedVector2(point, _this.elements.length);
  43320. result.push(newPoint);
  43321. _this.elements.push(newPoint);
  43322. }
  43323. });
  43324. return result;
  43325. };
  43326. PolygonPoints.prototype.computeBounds = function () {
  43327. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  43328. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  43329. this.elements.forEach(function (point) {
  43330. // x
  43331. if (point.x < lmin.x) {
  43332. lmin.x = point.x;
  43333. }
  43334. else if (point.x > lmax.x) {
  43335. lmax.x = point.x;
  43336. }
  43337. // y
  43338. if (point.y < lmin.y) {
  43339. lmin.y = point.y;
  43340. }
  43341. else if (point.y > lmax.y) {
  43342. lmax.y = point.y;
  43343. }
  43344. });
  43345. return {
  43346. min: lmin,
  43347. max: lmax,
  43348. width: lmax.x - lmin.x,
  43349. height: lmax.y - lmin.y
  43350. };
  43351. };
  43352. return PolygonPoints;
  43353. }());
  43354. var Polygon = (function () {
  43355. function Polygon() {
  43356. }
  43357. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  43358. return [
  43359. new BABYLON.Vector2(xmin, ymin),
  43360. new BABYLON.Vector2(xmax, ymin),
  43361. new BABYLON.Vector2(xmax, ymax),
  43362. new BABYLON.Vector2(xmin, ymax)
  43363. ];
  43364. };
  43365. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  43366. if (cx === void 0) { cx = 0; }
  43367. if (cy === void 0) { cy = 0; }
  43368. if (numberOfSides === void 0) { numberOfSides = 32; }
  43369. var result = new Array();
  43370. var angle = 0;
  43371. var increment = (Math.PI * 2) / numberOfSides;
  43372. for (var i = 0; i < numberOfSides; i++) {
  43373. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  43374. angle -= increment;
  43375. }
  43376. return result;
  43377. };
  43378. Polygon.Parse = function (input) {
  43379. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  43380. var i, result = [];
  43381. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  43382. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  43383. }
  43384. return result;
  43385. };
  43386. Polygon.StartingAt = function (x, y) {
  43387. return BABYLON.Path2.StartingAt(x, y);
  43388. };
  43389. return Polygon;
  43390. }());
  43391. BABYLON.Polygon = Polygon;
  43392. var PolygonMeshBuilder = (function () {
  43393. function PolygonMeshBuilder(name, contours, scene) {
  43394. this._points = new PolygonPoints();
  43395. this._outlinepoints = new PolygonPoints();
  43396. this._holes = [];
  43397. this._epoints = new Array();
  43398. this._eholes = new Array();
  43399. this._name = name;
  43400. this._scene = scene;
  43401. var points;
  43402. if (contours instanceof BABYLON.Path2) {
  43403. points = contours.getPoints();
  43404. }
  43405. else {
  43406. points = contours;
  43407. }
  43408. this._addToepoint(points);
  43409. this._points.add(points);
  43410. this._outlinepoints.add(points);
  43411. }
  43412. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  43413. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  43414. var p = points_1[_i];
  43415. this._epoints.push(p.x, p.y);
  43416. }
  43417. };
  43418. PolygonMeshBuilder.prototype.addHole = function (hole) {
  43419. this._points.add(hole);
  43420. var holepoints = new PolygonPoints();
  43421. holepoints.add(hole);
  43422. this._holes.push(holepoints);
  43423. this._eholes.push(this._epoints.length / 2);
  43424. this._addToepoint(hole);
  43425. return this;
  43426. };
  43427. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  43428. var _this = this;
  43429. if (updatable === void 0) { updatable = false; }
  43430. var result = new BABYLON.Mesh(this._name, this._scene);
  43431. var normals = [];
  43432. var positions = [];
  43433. var uvs = [];
  43434. var bounds = this._points.computeBounds();
  43435. this._points.elements.forEach(function (p) {
  43436. normals.push(0, 1.0, 0);
  43437. positions.push(p.x, 0, p.y);
  43438. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  43439. });
  43440. var indices = [];
  43441. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  43442. for (var i = 0; i < res.length; i++) {
  43443. indices.push(res[i]);
  43444. }
  43445. if (depth > 0) {
  43446. var positionscount = (positions.length / 3); //get the current pointcount
  43447. this._points.elements.forEach(function (p) {
  43448. normals.push(0, -1.0, 0);
  43449. positions.push(p.x, -depth, p.y);
  43450. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  43451. });
  43452. var totalCount = indices.length;
  43453. for (var i = 0; i < totalCount; i += 3) {
  43454. var i0 = indices[i + 0];
  43455. var i1 = indices[i + 1];
  43456. var i2 = indices[i + 2];
  43457. indices.push(i2 + positionscount);
  43458. indices.push(i1 + positionscount);
  43459. indices.push(i0 + positionscount);
  43460. }
  43461. //Add the sides
  43462. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  43463. this._holes.forEach(function (hole) {
  43464. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  43465. });
  43466. }
  43467. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  43468. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  43469. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  43470. result.setIndices(indices);
  43471. return result;
  43472. };
  43473. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  43474. var StartIndex = positions.length / 3;
  43475. var ulength = 0;
  43476. for (var i = 0; i < points.elements.length; i++) {
  43477. var p = points.elements[i];
  43478. var p1;
  43479. if ((i + 1) > points.elements.length - 1) {
  43480. p1 = points.elements[0];
  43481. }
  43482. else {
  43483. p1 = points.elements[i + 1];
  43484. }
  43485. positions.push(p.x, 0, p.y);
  43486. positions.push(p.x, -depth, p.y);
  43487. positions.push(p1.x, 0, p1.y);
  43488. positions.push(p1.x, -depth, p1.y);
  43489. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  43490. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  43491. var v3 = v2.subtract(v1);
  43492. var v4 = new BABYLON.Vector3(0, 1, 0);
  43493. var vn = BABYLON.Vector3.Cross(v3, v4);
  43494. vn = vn.normalize();
  43495. uvs.push(ulength / bounds.width, 0);
  43496. uvs.push(ulength / bounds.width, 1);
  43497. ulength += v3.length();
  43498. uvs.push((ulength / bounds.width), 0);
  43499. uvs.push((ulength / bounds.width), 1);
  43500. if (!flip) {
  43501. normals.push(-vn.x, -vn.y, -vn.z);
  43502. normals.push(-vn.x, -vn.y, -vn.z);
  43503. normals.push(-vn.x, -vn.y, -vn.z);
  43504. normals.push(-vn.x, -vn.y, -vn.z);
  43505. indices.push(StartIndex);
  43506. indices.push(StartIndex + 1);
  43507. indices.push(StartIndex + 2);
  43508. indices.push(StartIndex + 1);
  43509. indices.push(StartIndex + 3);
  43510. indices.push(StartIndex + 2);
  43511. }
  43512. else {
  43513. normals.push(vn.x, vn.y, vn.z);
  43514. normals.push(vn.x, vn.y, vn.z);
  43515. normals.push(vn.x, vn.y, vn.z);
  43516. normals.push(vn.x, vn.y, vn.z);
  43517. indices.push(StartIndex);
  43518. indices.push(StartIndex + 2);
  43519. indices.push(StartIndex + 1);
  43520. indices.push(StartIndex + 1);
  43521. indices.push(StartIndex + 2);
  43522. indices.push(StartIndex + 3);
  43523. }
  43524. StartIndex += 4;
  43525. }
  43526. ;
  43527. };
  43528. return PolygonMeshBuilder;
  43529. }());
  43530. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  43531. })(BABYLON || (BABYLON = {}));
  43532. var BABYLON;
  43533. (function (BABYLON) {
  43534. var Octree = (function () {
  43535. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  43536. if (maxDepth === void 0) { maxDepth = 2; }
  43537. this.maxDepth = maxDepth;
  43538. this.dynamicContent = new Array();
  43539. this._maxBlockCapacity = maxBlockCapacity || 64;
  43540. this._selectionContent = new BABYLON.SmartArray(1024);
  43541. this._creationFunc = creationFunc;
  43542. }
  43543. // Methods
  43544. Octree.prototype.update = function (worldMin, worldMax, entries) {
  43545. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  43546. };
  43547. Octree.prototype.addMesh = function (entry) {
  43548. for (var index = 0; index < this.blocks.length; index++) {
  43549. var block = this.blocks[index];
  43550. block.addEntry(entry);
  43551. }
  43552. };
  43553. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  43554. this._selectionContent.reset();
  43555. for (var index = 0; index < this.blocks.length; index++) {
  43556. var block = this.blocks[index];
  43557. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  43558. }
  43559. if (allowDuplicate) {
  43560. this._selectionContent.concat(this.dynamicContent);
  43561. }
  43562. else {
  43563. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  43564. }
  43565. return this._selectionContent;
  43566. };
  43567. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  43568. this._selectionContent.reset();
  43569. for (var index = 0; index < this.blocks.length; index++) {
  43570. var block = this.blocks[index];
  43571. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  43572. }
  43573. if (allowDuplicate) {
  43574. this._selectionContent.concat(this.dynamicContent);
  43575. }
  43576. else {
  43577. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  43578. }
  43579. return this._selectionContent;
  43580. };
  43581. Octree.prototype.intersectsRay = function (ray) {
  43582. this._selectionContent.reset();
  43583. for (var index = 0; index < this.blocks.length; index++) {
  43584. var block = this.blocks[index];
  43585. block.intersectsRay(ray, this._selectionContent);
  43586. }
  43587. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  43588. return this._selectionContent;
  43589. };
  43590. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  43591. target.blocks = new Array();
  43592. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  43593. // Segmenting space
  43594. for (var x = 0; x < 2; x++) {
  43595. for (var y = 0; y < 2; y++) {
  43596. for (var z = 0; z < 2; z++) {
  43597. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  43598. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  43599. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  43600. block.addEntries(entries);
  43601. target.blocks.push(block);
  43602. }
  43603. }
  43604. }
  43605. };
  43606. Octree.CreationFuncForMeshes = function (entry, block) {
  43607. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  43608. block.entries.push(entry);
  43609. }
  43610. };
  43611. Octree.CreationFuncForSubMeshes = function (entry, block) {
  43612. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  43613. block.entries.push(entry);
  43614. }
  43615. };
  43616. return Octree;
  43617. }());
  43618. BABYLON.Octree = Octree;
  43619. })(BABYLON || (BABYLON = {}));
  43620. var BABYLON;
  43621. (function (BABYLON) {
  43622. var OctreeBlock = (function () {
  43623. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  43624. this.entries = new Array();
  43625. this._boundingVectors = new Array();
  43626. this._capacity = capacity;
  43627. this._depth = depth;
  43628. this._maxDepth = maxDepth;
  43629. this._creationFunc = creationFunc;
  43630. this._minPoint = minPoint;
  43631. this._maxPoint = maxPoint;
  43632. this._boundingVectors.push(minPoint.clone());
  43633. this._boundingVectors.push(maxPoint.clone());
  43634. this._boundingVectors.push(minPoint.clone());
  43635. this._boundingVectors[2].x = maxPoint.x;
  43636. this._boundingVectors.push(minPoint.clone());
  43637. this._boundingVectors[3].y = maxPoint.y;
  43638. this._boundingVectors.push(minPoint.clone());
  43639. this._boundingVectors[4].z = maxPoint.z;
  43640. this._boundingVectors.push(maxPoint.clone());
  43641. this._boundingVectors[5].z = minPoint.z;
  43642. this._boundingVectors.push(maxPoint.clone());
  43643. this._boundingVectors[6].x = minPoint.x;
  43644. this._boundingVectors.push(maxPoint.clone());
  43645. this._boundingVectors[7].y = minPoint.y;
  43646. }
  43647. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  43648. // Property
  43649. get: function () {
  43650. return this._capacity;
  43651. },
  43652. enumerable: true,
  43653. configurable: true
  43654. });
  43655. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  43656. get: function () {
  43657. return this._minPoint;
  43658. },
  43659. enumerable: true,
  43660. configurable: true
  43661. });
  43662. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  43663. get: function () {
  43664. return this._maxPoint;
  43665. },
  43666. enumerable: true,
  43667. configurable: true
  43668. });
  43669. // Methods
  43670. OctreeBlock.prototype.addEntry = function (entry) {
  43671. if (this.blocks) {
  43672. for (var index = 0; index < this.blocks.length; index++) {
  43673. var block = this.blocks[index];
  43674. block.addEntry(entry);
  43675. }
  43676. return;
  43677. }
  43678. this._creationFunc(entry, this);
  43679. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  43680. this.createInnerBlocks();
  43681. }
  43682. };
  43683. OctreeBlock.prototype.addEntries = function (entries) {
  43684. for (var index = 0; index < entries.length; index++) {
  43685. var mesh = entries[index];
  43686. this.addEntry(mesh);
  43687. }
  43688. };
  43689. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  43690. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  43691. if (this.blocks) {
  43692. for (var index = 0; index < this.blocks.length; index++) {
  43693. var block = this.blocks[index];
  43694. block.select(frustumPlanes, selection, allowDuplicate);
  43695. }
  43696. return;
  43697. }
  43698. if (allowDuplicate) {
  43699. selection.concat(this.entries);
  43700. }
  43701. else {
  43702. selection.concatWithNoDuplicate(this.entries);
  43703. }
  43704. }
  43705. };
  43706. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  43707. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  43708. if (this.blocks) {
  43709. for (var index = 0; index < this.blocks.length; index++) {
  43710. var block = this.blocks[index];
  43711. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  43712. }
  43713. return;
  43714. }
  43715. if (allowDuplicate) {
  43716. selection.concat(this.entries);
  43717. }
  43718. else {
  43719. selection.concatWithNoDuplicate(this.entries);
  43720. }
  43721. }
  43722. };
  43723. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  43724. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  43725. if (this.blocks) {
  43726. for (var index = 0; index < this.blocks.length; index++) {
  43727. var block = this.blocks[index];
  43728. block.intersectsRay(ray, selection);
  43729. }
  43730. return;
  43731. }
  43732. selection.concatWithNoDuplicate(this.entries);
  43733. }
  43734. };
  43735. OctreeBlock.prototype.createInnerBlocks = function () {
  43736. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  43737. };
  43738. return OctreeBlock;
  43739. }());
  43740. BABYLON.OctreeBlock = OctreeBlock;
  43741. })(BABYLON || (BABYLON = {}));
  43742. var BABYLON;
  43743. (function (BABYLON) {
  43744. var BlurPostProcess = (function (_super) {
  43745. __extends(BlurPostProcess, _super);
  43746. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  43747. var _this = this;
  43748. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43749. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  43750. this.direction = direction;
  43751. this.blurWidth = blurWidth;
  43752. this.onApplyObservable.add(function (effect) {
  43753. effect.setFloat2("screenSize", _this.width, _this.height);
  43754. effect.setVector2("direction", _this.direction);
  43755. effect.setFloat("blurWidth", _this.blurWidth);
  43756. });
  43757. }
  43758. return BlurPostProcess;
  43759. }(BABYLON.PostProcess));
  43760. BABYLON.BlurPostProcess = BlurPostProcess;
  43761. })(BABYLON || (BABYLON = {}));
  43762. var BABYLON;
  43763. (function (BABYLON) {
  43764. var RefractionPostProcess = (function (_super) {
  43765. __extends(RefractionPostProcess, _super);
  43766. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  43767. var _this = this;
  43768. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  43769. this.color = color;
  43770. this.depth = depth;
  43771. this.colorLevel = colorLevel;
  43772. this.onActivateObservable.add(function (cam) {
  43773. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  43774. });
  43775. this.onApplyObservable.add(function (effect) {
  43776. effect.setColor3("baseColor", _this.color);
  43777. effect.setFloat("depth", _this.depth);
  43778. effect.setFloat("colorLevel", _this.colorLevel);
  43779. effect.setTexture("refractionSampler", _this._refRexture);
  43780. });
  43781. }
  43782. // Methods
  43783. RefractionPostProcess.prototype.dispose = function (camera) {
  43784. if (this._refRexture) {
  43785. this._refRexture.dispose();
  43786. }
  43787. _super.prototype.dispose.call(this, camera);
  43788. };
  43789. return RefractionPostProcess;
  43790. }(BABYLON.PostProcess));
  43791. BABYLON.RefractionPostProcess = RefractionPostProcess;
  43792. })(BABYLON || (BABYLON = {}));
  43793. var BABYLON;
  43794. (function (BABYLON) {
  43795. var BlackAndWhitePostProcess = (function (_super) {
  43796. __extends(BlackAndWhitePostProcess, _super);
  43797. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  43798. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  43799. }
  43800. return BlackAndWhitePostProcess;
  43801. }(BABYLON.PostProcess));
  43802. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  43803. })(BABYLON || (BABYLON = {}));
  43804. var BABYLON;
  43805. (function (BABYLON) {
  43806. var ConvolutionPostProcess = (function (_super) {
  43807. __extends(ConvolutionPostProcess, _super);
  43808. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  43809. var _this = this;
  43810. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  43811. this.kernel = kernel;
  43812. this.onApply = function (effect) {
  43813. effect.setFloat2("screenSize", _this.width, _this.height);
  43814. effect.setArray("kernel", _this.kernel);
  43815. };
  43816. }
  43817. // Statics
  43818. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  43819. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  43820. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  43821. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  43822. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  43823. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  43824. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  43825. return ConvolutionPostProcess;
  43826. }(BABYLON.PostProcess));
  43827. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  43828. })(BABYLON || (BABYLON = {}));
  43829. var BABYLON;
  43830. (function (BABYLON) {
  43831. var FilterPostProcess = (function (_super) {
  43832. __extends(FilterPostProcess, _super);
  43833. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  43834. var _this = this;
  43835. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  43836. this.kernelMatrix = kernelMatrix;
  43837. this.onApply = function (effect) {
  43838. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  43839. };
  43840. }
  43841. return FilterPostProcess;
  43842. }(BABYLON.PostProcess));
  43843. BABYLON.FilterPostProcess = FilterPostProcess;
  43844. })(BABYLON || (BABYLON = {}));
  43845. var BABYLON;
  43846. (function (BABYLON) {
  43847. var FxaaPostProcess = (function (_super) {
  43848. __extends(FxaaPostProcess, _super);
  43849. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  43850. var _this = this;
  43851. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  43852. this.onSizeChangedObservable.add(function () {
  43853. _this.texelWidth = 1.0 / _this.width;
  43854. _this.texelHeight = 1.0 / _this.height;
  43855. });
  43856. this.onApplyObservable.add(function (effect) {
  43857. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  43858. });
  43859. }
  43860. return FxaaPostProcess;
  43861. }(BABYLON.PostProcess));
  43862. BABYLON.FxaaPostProcess = FxaaPostProcess;
  43863. })(BABYLON || (BABYLON = {}));
  43864. var BABYLON;
  43865. (function (BABYLON) {
  43866. var StereoscopicInterlacePostProcess = (function (_super) {
  43867. __extends(StereoscopicInterlacePostProcess, _super);
  43868. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  43869. var _this = this;
  43870. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  43871. this._passedProcess = rigCameras[0]._rigPostProcess;
  43872. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  43873. this.onSizeChangedObservable.add(function () {
  43874. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  43875. });
  43876. this.onApplyObservable.add(function (effect) {
  43877. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  43878. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  43879. });
  43880. }
  43881. return StereoscopicInterlacePostProcess;
  43882. }(BABYLON.PostProcess));
  43883. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  43884. })(BABYLON || (BABYLON = {}));
  43885. var BABYLON;
  43886. (function (BABYLON) {
  43887. var LensFlare = (function () {
  43888. function LensFlare(size, position, color, imgUrl, system) {
  43889. this.size = size;
  43890. this.position = position;
  43891. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  43892. this.dispose = function () {
  43893. if (this.texture) {
  43894. this.texture.dispose();
  43895. }
  43896. // Remove from scene
  43897. var index = this._system.lensFlares.indexOf(this);
  43898. this._system.lensFlares.splice(index, 1);
  43899. };
  43900. this.color = color || new BABYLON.Color3(1, 1, 1);
  43901. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  43902. this._system = system;
  43903. system.lensFlares.push(this);
  43904. }
  43905. return LensFlare;
  43906. }());
  43907. BABYLON.LensFlare = LensFlare;
  43908. })(BABYLON || (BABYLON = {}));
  43909. var BABYLON;
  43910. (function (BABYLON) {
  43911. var LensFlareSystem = (function () {
  43912. function LensFlareSystem(name, emitter, scene) {
  43913. this.name = name;
  43914. this.lensFlares = new Array();
  43915. this.borderLimit = 300;
  43916. this.viewportBorder = 0;
  43917. this.layerMask = 0x0FFFFFFF;
  43918. this._vertexBuffers = {};
  43919. this._isEnabled = true;
  43920. this._scene = scene;
  43921. this._emitter = emitter;
  43922. this.id = name;
  43923. scene.lensFlareSystems.push(this);
  43924. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  43925. var engine = scene.getEngine();
  43926. // VBO
  43927. var vertices = [];
  43928. vertices.push(1, 1);
  43929. vertices.push(-1, 1);
  43930. vertices.push(-1, -1);
  43931. vertices.push(1, -1);
  43932. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  43933. // Indices
  43934. var indices = [];
  43935. indices.push(0);
  43936. indices.push(1);
  43937. indices.push(2);
  43938. indices.push(0);
  43939. indices.push(2);
  43940. indices.push(3);
  43941. this._indexBuffer = engine.createIndexBuffer(indices);
  43942. // Effects
  43943. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  43944. }
  43945. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  43946. get: function () {
  43947. return this._isEnabled;
  43948. },
  43949. set: function (value) {
  43950. this._isEnabled = value;
  43951. },
  43952. enumerable: true,
  43953. configurable: true
  43954. });
  43955. LensFlareSystem.prototype.getScene = function () {
  43956. return this._scene;
  43957. };
  43958. LensFlareSystem.prototype.getEmitter = function () {
  43959. return this._emitter;
  43960. };
  43961. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  43962. this._emitter = newEmitter;
  43963. };
  43964. LensFlareSystem.prototype.getEmitterPosition = function () {
  43965. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  43966. };
  43967. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  43968. var position = this.getEmitterPosition();
  43969. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  43970. this._positionX = position.x;
  43971. this._positionY = position.y;
  43972. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  43973. if (this.viewportBorder > 0) {
  43974. globalViewport.x -= this.viewportBorder;
  43975. globalViewport.y -= this.viewportBorder;
  43976. globalViewport.width += this.viewportBorder * 2;
  43977. globalViewport.height += this.viewportBorder * 2;
  43978. position.x += this.viewportBorder;
  43979. position.y += this.viewportBorder;
  43980. this._positionX += this.viewportBorder;
  43981. this._positionY += this.viewportBorder;
  43982. }
  43983. if (position.z > 0) {
  43984. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  43985. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  43986. return true;
  43987. }
  43988. return true;
  43989. }
  43990. return false;
  43991. };
  43992. LensFlareSystem.prototype._isVisible = function () {
  43993. if (!this._isEnabled) {
  43994. return false;
  43995. }
  43996. var emitterPosition = this.getEmitterPosition();
  43997. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  43998. var distance = direction.length();
  43999. direction.normalize();
  44000. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  44001. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  44002. return !pickInfo.hit || pickInfo.distance > distance;
  44003. };
  44004. LensFlareSystem.prototype.render = function () {
  44005. if (!this._effect.isReady())
  44006. return false;
  44007. var engine = this._scene.getEngine();
  44008. var viewport = this._scene.activeCamera.viewport;
  44009. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  44010. // Position
  44011. if (!this.computeEffectivePosition(globalViewport)) {
  44012. return false;
  44013. }
  44014. // Visibility
  44015. if (!this._isVisible()) {
  44016. return false;
  44017. }
  44018. // Intensity
  44019. var awayX;
  44020. var awayY;
  44021. if (this._positionX < this.borderLimit + globalViewport.x) {
  44022. awayX = this.borderLimit + globalViewport.x - this._positionX;
  44023. }
  44024. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  44025. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  44026. }
  44027. else {
  44028. awayX = 0;
  44029. }
  44030. if (this._positionY < this.borderLimit + globalViewport.y) {
  44031. awayY = this.borderLimit + globalViewport.y - this._positionY;
  44032. }
  44033. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  44034. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  44035. }
  44036. else {
  44037. awayY = 0;
  44038. }
  44039. var away = (awayX > awayY) ? awayX : awayY;
  44040. away -= this.viewportBorder;
  44041. if (away > this.borderLimit) {
  44042. away = this.borderLimit;
  44043. }
  44044. var intensity = 1.0 - (away / this.borderLimit);
  44045. if (intensity < 0) {
  44046. return false;
  44047. }
  44048. if (intensity > 1.0) {
  44049. intensity = 1.0;
  44050. }
  44051. if (this.viewportBorder > 0) {
  44052. globalViewport.x += this.viewportBorder;
  44053. globalViewport.y += this.viewportBorder;
  44054. globalViewport.width -= this.viewportBorder * 2;
  44055. globalViewport.height -= this.viewportBorder * 2;
  44056. this._positionX -= this.viewportBorder;
  44057. this._positionY -= this.viewportBorder;
  44058. }
  44059. // Position
  44060. var centerX = globalViewport.x + globalViewport.width / 2;
  44061. var centerY = globalViewport.y + globalViewport.height / 2;
  44062. var distX = centerX - this._positionX;
  44063. var distY = centerY - this._positionY;
  44064. // Effects
  44065. engine.enableEffect(this._effect);
  44066. engine.setState(false);
  44067. engine.setDepthBuffer(false);
  44068. // VBOs
  44069. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44070. // Flares
  44071. for (var index = 0; index < this.lensFlares.length; index++) {
  44072. var flare = this.lensFlares[index];
  44073. engine.setAlphaMode(flare.alphaMode);
  44074. var x = centerX - (distX * flare.position);
  44075. var y = centerY - (distY * flare.position);
  44076. var cw = flare.size;
  44077. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  44078. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  44079. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  44080. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  44081. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  44082. // Texture
  44083. this._effect.setTexture("textureSampler", flare.texture);
  44084. // Color
  44085. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  44086. // Draw order
  44087. engine.draw(true, 0, 6);
  44088. }
  44089. engine.setDepthBuffer(true);
  44090. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44091. return true;
  44092. };
  44093. LensFlareSystem.prototype.dispose = function () {
  44094. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  44095. if (vertexBuffer) {
  44096. vertexBuffer.dispose();
  44097. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  44098. }
  44099. if (this._indexBuffer) {
  44100. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44101. this._indexBuffer = null;
  44102. }
  44103. while (this.lensFlares.length) {
  44104. this.lensFlares[0].dispose();
  44105. }
  44106. // Remove from scene
  44107. var index = this._scene.lensFlareSystems.indexOf(this);
  44108. this._scene.lensFlareSystems.splice(index, 1);
  44109. };
  44110. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  44111. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  44112. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  44113. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  44114. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  44115. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  44116. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  44117. var parsedFlare = parsedLensFlareSystem.flares[index];
  44118. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  44119. }
  44120. return lensFlareSystem;
  44121. };
  44122. LensFlareSystem.prototype.serialize = function () {
  44123. var serializationObject = {};
  44124. serializationObject.id = this.id;
  44125. serializationObject.name = this.name;
  44126. serializationObject.emitterId = this.getEmitter().id;
  44127. serializationObject.borderLimit = this.borderLimit;
  44128. serializationObject.flares = [];
  44129. for (var index = 0; index < this.lensFlares.length; index++) {
  44130. var flare = this.lensFlares[index];
  44131. serializationObject.flares.push({
  44132. size: flare.size,
  44133. position: flare.position,
  44134. color: flare.color.asArray(),
  44135. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  44136. });
  44137. }
  44138. return serializationObject;
  44139. };
  44140. return LensFlareSystem;
  44141. }());
  44142. BABYLON.LensFlareSystem = LensFlareSystem;
  44143. })(BABYLON || (BABYLON = {}));
  44144. var BABYLON;
  44145. (function (BABYLON) {
  44146. // We're mainly based on the logic defined into the FreeCamera code
  44147. var DeviceOrientationCamera = (function (_super) {
  44148. __extends(DeviceOrientationCamera, _super);
  44149. function DeviceOrientationCamera(name, position, scene) {
  44150. _super.call(this, name, position, scene);
  44151. this._quaternionCache = new BABYLON.Quaternion();
  44152. this.inputs.addDeviceOrientation();
  44153. }
  44154. DeviceOrientationCamera.prototype.getTypeName = function () {
  44155. return "DeviceOrientationCamera";
  44156. };
  44157. DeviceOrientationCamera.prototype._checkInputs = function () {
  44158. _super.prototype._checkInputs.call(this);
  44159. this._quaternionCache.copyFrom(this.rotationQuaternion);
  44160. if (this._initialQuaternion) {
  44161. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  44162. }
  44163. };
  44164. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  44165. var _this = this;
  44166. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  44167. //can only work if this camera has a rotation quaternion already.
  44168. if (!this.rotationQuaternion)
  44169. return;
  44170. if (!this._initialQuaternion) {
  44171. this._initialQuaternion = new BABYLON.Quaternion();
  44172. }
  44173. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  44174. ['x', 'y', 'z'].forEach(function (axisName) {
  44175. if (!axis[axisName]) {
  44176. _this._initialQuaternion[axisName] = 0;
  44177. }
  44178. else {
  44179. _this._initialQuaternion[axisName] *= -1;
  44180. }
  44181. });
  44182. this._initialQuaternion.normalize();
  44183. //force rotation update
  44184. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  44185. };
  44186. return DeviceOrientationCamera;
  44187. }(BABYLON.FreeCamera));
  44188. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  44189. })(BABYLON || (BABYLON = {}));
  44190. var BABYLON;
  44191. (function (BABYLON) {
  44192. var VRDeviceOrientationFreeCamera = (function (_super) {
  44193. __extends(VRDeviceOrientationFreeCamera, _super);
  44194. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  44195. if (compensateDistortion === void 0) { compensateDistortion = true; }
  44196. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  44197. _super.call(this, name, position, scene);
  44198. vrCameraMetrics.compensateDistortion = compensateDistortion;
  44199. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  44200. }
  44201. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  44202. return "VRDeviceOrientationFreeCamera";
  44203. };
  44204. return VRDeviceOrientationFreeCamera;
  44205. }(BABYLON.DeviceOrientationCamera));
  44206. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  44207. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  44208. __extends(VRDeviceOrientationArcRotateCamera, _super);
  44209. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  44210. if (compensateDistortion === void 0) { compensateDistortion = true; }
  44211. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  44212. _super.call(this, name, alpha, beta, radius, target, scene);
  44213. vrCameraMetrics.compensateDistortion = compensateDistortion;
  44214. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  44215. this.inputs.addVRDeviceOrientation();
  44216. }
  44217. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  44218. return "VRDeviceOrientationArcRotateCamera";
  44219. };
  44220. return VRDeviceOrientationArcRotateCamera;
  44221. }(BABYLON.ArcRotateCamera));
  44222. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  44223. })(BABYLON || (BABYLON = {}));
  44224. var BABYLON;
  44225. (function (BABYLON) {
  44226. // We're mainly based on the logic defined into the FreeCamera code
  44227. var UniversalCamera = (function (_super) {
  44228. __extends(UniversalCamera, _super);
  44229. //-- end properties for backward compatibility for inputs
  44230. function UniversalCamera(name, position, scene) {
  44231. _super.call(this, name, position, scene);
  44232. this.inputs.addGamepad();
  44233. }
  44234. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  44235. //-- Begin properties for backward compatibility for inputs
  44236. get: function () {
  44237. var gamepad = this.inputs.attached["gamepad"];
  44238. if (gamepad)
  44239. return gamepad.gamepadAngularSensibility;
  44240. },
  44241. set: function (value) {
  44242. var gamepad = this.inputs.attached["gamepad"];
  44243. if (gamepad)
  44244. gamepad.gamepadAngularSensibility = value;
  44245. },
  44246. enumerable: true,
  44247. configurable: true
  44248. });
  44249. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  44250. get: function () {
  44251. var gamepad = this.inputs.attached["gamepad"];
  44252. if (gamepad)
  44253. return gamepad.gamepadMoveSensibility;
  44254. },
  44255. set: function (value) {
  44256. var gamepad = this.inputs.attached["gamepad"];
  44257. if (gamepad)
  44258. gamepad.gamepadMoveSensibility = value;
  44259. },
  44260. enumerable: true,
  44261. configurable: true
  44262. });
  44263. UniversalCamera.prototype.getTypeName = function () {
  44264. return "UniversalCamera";
  44265. };
  44266. return UniversalCamera;
  44267. }(BABYLON.TouchCamera));
  44268. BABYLON.UniversalCamera = UniversalCamera;
  44269. })(BABYLON || (BABYLON = {}));
  44270. var BABYLON;
  44271. (function (BABYLON) {
  44272. var Gamepads = (function () {
  44273. function Gamepads(ongamedpadconnected) {
  44274. var _this = this;
  44275. this.babylonGamepads = [];
  44276. this.oneGamepadConnected = false;
  44277. this.isMonitoring = false;
  44278. this.gamepadEventSupported = 'GamepadEvent' in window;
  44279. this.gamepadSupportAvailable = (navigator.getGamepads ||
  44280. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  44281. this._callbackGamepadConnected = ongamedpadconnected;
  44282. if (this.gamepadSupportAvailable) {
  44283. // Checking if the gamepad connected event is supported (like in Firefox)
  44284. if (this.gamepadEventSupported) {
  44285. this._onGamepadConnectedEvent = function (evt) {
  44286. _this._onGamepadConnected(evt);
  44287. };
  44288. this._onGamepadDisonnectedEvent = function (evt) {
  44289. _this._onGamepadDisconnected(evt);
  44290. };
  44291. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44292. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44293. }
  44294. else {
  44295. this._startMonitoringGamepads();
  44296. }
  44297. }
  44298. }
  44299. Gamepads.prototype.dispose = function () {
  44300. if (Gamepads.gamepadDOMInfo) {
  44301. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44302. }
  44303. if (this._onGamepadConnectedEvent) {
  44304. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44305. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44306. this._onGamepadConnectedEvent = null;
  44307. this._onGamepadDisonnectedEvent = null;
  44308. }
  44309. };
  44310. Gamepads.prototype._onGamepadConnected = function (evt) {
  44311. var newGamepad = this._addNewGamepad(evt.gamepad);
  44312. if (this._callbackGamepadConnected)
  44313. this._callbackGamepadConnected(newGamepad);
  44314. this._startMonitoringGamepads();
  44315. };
  44316. Gamepads.prototype._addNewGamepad = function (gamepad) {
  44317. if (!this.oneGamepadConnected) {
  44318. this.oneGamepadConnected = true;
  44319. if (Gamepads.gamepadDOMInfo) {
  44320. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44321. Gamepads.gamepadDOMInfo = null;
  44322. }
  44323. }
  44324. var newGamepad;
  44325. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  44326. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  44327. }
  44328. else {
  44329. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  44330. }
  44331. this.babylonGamepads.push(newGamepad);
  44332. return newGamepad;
  44333. };
  44334. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  44335. // Remove the gamepad from the list of gamepads to monitor.
  44336. for (var i in this.babylonGamepads) {
  44337. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  44338. this.babylonGamepads.splice(+i, 1);
  44339. break;
  44340. }
  44341. }
  44342. // If no gamepads are left, stop the polling loop.
  44343. if (this.babylonGamepads.length == 0) {
  44344. this._stopMonitoringGamepads();
  44345. }
  44346. };
  44347. Gamepads.prototype._startMonitoringGamepads = function () {
  44348. if (!this.isMonitoring) {
  44349. this.isMonitoring = true;
  44350. this._checkGamepadsStatus();
  44351. }
  44352. };
  44353. Gamepads.prototype._stopMonitoringGamepads = function () {
  44354. this.isMonitoring = false;
  44355. };
  44356. Gamepads.prototype._checkGamepadsStatus = function () {
  44357. var _this = this;
  44358. // updating gamepad objects
  44359. this._updateGamepadObjects();
  44360. for (var i in this.babylonGamepads) {
  44361. this.babylonGamepads[i].update();
  44362. }
  44363. if (this.isMonitoring) {
  44364. if (window.requestAnimationFrame) {
  44365. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44366. }
  44367. else if (window.mozRequestAnimationFrame) {
  44368. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44369. }
  44370. else if (window.webkitRequestAnimationFrame) {
  44371. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44372. }
  44373. }
  44374. };
  44375. // This function is called only on Chrome, which does not yet support
  44376. // connection/disconnection events, but requires you to monitor
  44377. // an array for changes.
  44378. Gamepads.prototype._updateGamepadObjects = function () {
  44379. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  44380. for (var i = 0; i < gamepads.length; i++) {
  44381. if (gamepads[i]) {
  44382. if (!(gamepads[i].index in this.babylonGamepads)) {
  44383. var newGamepad = this._addNewGamepad(gamepads[i]);
  44384. if (this._callbackGamepadConnected) {
  44385. this._callbackGamepadConnected(newGamepad);
  44386. }
  44387. }
  44388. else {
  44389. this.babylonGamepads[i].browserGamepad = gamepads[i];
  44390. }
  44391. }
  44392. }
  44393. };
  44394. return Gamepads;
  44395. }());
  44396. BABYLON.Gamepads = Gamepads;
  44397. var StickValues = (function () {
  44398. function StickValues(x, y) {
  44399. this.x = x;
  44400. this.y = y;
  44401. }
  44402. return StickValues;
  44403. }());
  44404. BABYLON.StickValues = StickValues;
  44405. var Gamepad = (function () {
  44406. function Gamepad(id, index, browserGamepad) {
  44407. this.id = id;
  44408. this.index = index;
  44409. this.browserGamepad = browserGamepad;
  44410. if (this.browserGamepad.axes.length >= 2) {
  44411. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  44412. }
  44413. if (this.browserGamepad.axes.length >= 4) {
  44414. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  44415. }
  44416. }
  44417. Gamepad.prototype.onleftstickchanged = function (callback) {
  44418. this._onleftstickchanged = callback;
  44419. };
  44420. Gamepad.prototype.onrightstickchanged = function (callback) {
  44421. this._onrightstickchanged = callback;
  44422. };
  44423. Object.defineProperty(Gamepad.prototype, "leftStick", {
  44424. get: function () {
  44425. return this._leftStick;
  44426. },
  44427. set: function (newValues) {
  44428. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  44429. this._onleftstickchanged(newValues);
  44430. }
  44431. this._leftStick = newValues;
  44432. },
  44433. enumerable: true,
  44434. configurable: true
  44435. });
  44436. Object.defineProperty(Gamepad.prototype, "rightStick", {
  44437. get: function () {
  44438. return this._rightStick;
  44439. },
  44440. set: function (newValues) {
  44441. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  44442. this._onrightstickchanged(newValues);
  44443. }
  44444. this._rightStick = newValues;
  44445. },
  44446. enumerable: true,
  44447. configurable: true
  44448. });
  44449. Gamepad.prototype.update = function () {
  44450. if (this._leftStick) {
  44451. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  44452. }
  44453. if (this._rightStick) {
  44454. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  44455. }
  44456. };
  44457. return Gamepad;
  44458. }());
  44459. BABYLON.Gamepad = Gamepad;
  44460. var GenericPad = (function (_super) {
  44461. __extends(GenericPad, _super);
  44462. function GenericPad(id, index, gamepad) {
  44463. _super.call(this, id, index, gamepad);
  44464. this.id = id;
  44465. this.index = index;
  44466. this.gamepad = gamepad;
  44467. this._buttons = new Array(gamepad.buttons.length);
  44468. }
  44469. GenericPad.prototype.onbuttondown = function (callback) {
  44470. this._onbuttondown = callback;
  44471. };
  44472. GenericPad.prototype.onbuttonup = function (callback) {
  44473. this._onbuttonup = callback;
  44474. };
  44475. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  44476. if (newValue !== currentValue) {
  44477. if (this._onbuttondown && newValue === 1) {
  44478. this._onbuttondown(buttonIndex);
  44479. }
  44480. if (this._onbuttonup && newValue === 0) {
  44481. this._onbuttonup(buttonIndex);
  44482. }
  44483. }
  44484. return newValue;
  44485. };
  44486. GenericPad.prototype.update = function () {
  44487. _super.prototype.update.call(this);
  44488. for (var index = 0; index < this._buttons.length; index++) {
  44489. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  44490. }
  44491. };
  44492. return GenericPad;
  44493. }(Gamepad));
  44494. BABYLON.GenericPad = GenericPad;
  44495. (function (Xbox360Button) {
  44496. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  44497. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  44498. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  44499. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  44500. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  44501. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  44502. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  44503. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  44504. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  44505. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  44506. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  44507. var Xbox360Button = BABYLON.Xbox360Button;
  44508. (function (Xbox360Dpad) {
  44509. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  44510. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  44511. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  44512. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  44513. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  44514. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  44515. var Xbox360Pad = (function (_super) {
  44516. __extends(Xbox360Pad, _super);
  44517. function Xbox360Pad() {
  44518. _super.apply(this, arguments);
  44519. this._leftTrigger = 0;
  44520. this._rightTrigger = 0;
  44521. this._buttonA = 0;
  44522. this._buttonB = 0;
  44523. this._buttonX = 0;
  44524. this._buttonY = 0;
  44525. this._buttonBack = 0;
  44526. this._buttonStart = 0;
  44527. this._buttonLB = 0;
  44528. this._buttonRB = 0;
  44529. this._buttonLeftStick = 0;
  44530. this._buttonRightStick = 0;
  44531. this._dPadUp = 0;
  44532. this._dPadDown = 0;
  44533. this._dPadLeft = 0;
  44534. this._dPadRight = 0;
  44535. }
  44536. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  44537. this._onlefttriggerchanged = callback;
  44538. };
  44539. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  44540. this._onrighttriggerchanged = callback;
  44541. };
  44542. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  44543. get: function () {
  44544. return this._leftTrigger;
  44545. },
  44546. set: function (newValue) {
  44547. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  44548. this._onlefttriggerchanged(newValue);
  44549. }
  44550. this._leftTrigger = newValue;
  44551. },
  44552. enumerable: true,
  44553. configurable: true
  44554. });
  44555. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  44556. get: function () {
  44557. return this._rightTrigger;
  44558. },
  44559. set: function (newValue) {
  44560. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  44561. this._onrighttriggerchanged(newValue);
  44562. }
  44563. this._rightTrigger = newValue;
  44564. },
  44565. enumerable: true,
  44566. configurable: true
  44567. });
  44568. Xbox360Pad.prototype.onbuttondown = function (callback) {
  44569. this._onbuttondown = callback;
  44570. };
  44571. Xbox360Pad.prototype.onbuttonup = function (callback) {
  44572. this._onbuttonup = callback;
  44573. };
  44574. Xbox360Pad.prototype.ondpaddown = function (callback) {
  44575. this._ondpaddown = callback;
  44576. };
  44577. Xbox360Pad.prototype.ondpadup = function (callback) {
  44578. this._ondpadup = callback;
  44579. };
  44580. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  44581. if (newValue !== currentValue) {
  44582. if (this._onbuttondown && newValue === 1) {
  44583. this._onbuttondown(buttonType);
  44584. }
  44585. if (this._onbuttonup && newValue === 0) {
  44586. this._onbuttonup(buttonType);
  44587. }
  44588. }
  44589. return newValue;
  44590. };
  44591. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  44592. if (newValue !== currentValue) {
  44593. if (this._ondpaddown && newValue === 1) {
  44594. this._ondpaddown(buttonType);
  44595. }
  44596. if (this._ondpadup && newValue === 0) {
  44597. this._ondpadup(buttonType);
  44598. }
  44599. }
  44600. return newValue;
  44601. };
  44602. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  44603. get: function () {
  44604. return this._buttonA;
  44605. },
  44606. set: function (value) {
  44607. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  44608. },
  44609. enumerable: true,
  44610. configurable: true
  44611. });
  44612. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  44613. get: function () {
  44614. return this._buttonB;
  44615. },
  44616. set: function (value) {
  44617. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  44618. },
  44619. enumerable: true,
  44620. configurable: true
  44621. });
  44622. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  44623. get: function () {
  44624. return this._buttonX;
  44625. },
  44626. set: function (value) {
  44627. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  44628. },
  44629. enumerable: true,
  44630. configurable: true
  44631. });
  44632. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  44633. get: function () {
  44634. return this._buttonY;
  44635. },
  44636. set: function (value) {
  44637. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  44638. },
  44639. enumerable: true,
  44640. configurable: true
  44641. });
  44642. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  44643. get: function () {
  44644. return this._buttonStart;
  44645. },
  44646. set: function (value) {
  44647. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  44648. },
  44649. enumerable: true,
  44650. configurable: true
  44651. });
  44652. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  44653. get: function () {
  44654. return this._buttonBack;
  44655. },
  44656. set: function (value) {
  44657. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  44658. },
  44659. enumerable: true,
  44660. configurable: true
  44661. });
  44662. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  44663. get: function () {
  44664. return this._buttonLB;
  44665. },
  44666. set: function (value) {
  44667. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  44668. },
  44669. enumerable: true,
  44670. configurable: true
  44671. });
  44672. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  44673. get: function () {
  44674. return this._buttonRB;
  44675. },
  44676. set: function (value) {
  44677. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  44678. },
  44679. enumerable: true,
  44680. configurable: true
  44681. });
  44682. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  44683. get: function () {
  44684. return this._buttonLeftStick;
  44685. },
  44686. set: function (value) {
  44687. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  44688. },
  44689. enumerable: true,
  44690. configurable: true
  44691. });
  44692. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  44693. get: function () {
  44694. return this._buttonRightStick;
  44695. },
  44696. set: function (value) {
  44697. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  44698. },
  44699. enumerable: true,
  44700. configurable: true
  44701. });
  44702. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  44703. get: function () {
  44704. return this._dPadUp;
  44705. },
  44706. set: function (value) {
  44707. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  44708. },
  44709. enumerable: true,
  44710. configurable: true
  44711. });
  44712. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  44713. get: function () {
  44714. return this._dPadDown;
  44715. },
  44716. set: function (value) {
  44717. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  44718. },
  44719. enumerable: true,
  44720. configurable: true
  44721. });
  44722. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  44723. get: function () {
  44724. return this._dPadLeft;
  44725. },
  44726. set: function (value) {
  44727. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  44728. },
  44729. enumerable: true,
  44730. configurable: true
  44731. });
  44732. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  44733. get: function () {
  44734. return this._dPadRight;
  44735. },
  44736. set: function (value) {
  44737. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  44738. },
  44739. enumerable: true,
  44740. configurable: true
  44741. });
  44742. Xbox360Pad.prototype.update = function () {
  44743. _super.prototype.update.call(this);
  44744. this.buttonA = this.browserGamepad.buttons[0].value;
  44745. this.buttonB = this.browserGamepad.buttons[1].value;
  44746. this.buttonX = this.browserGamepad.buttons[2].value;
  44747. this.buttonY = this.browserGamepad.buttons[3].value;
  44748. this.buttonLB = this.browserGamepad.buttons[4].value;
  44749. this.buttonRB = this.browserGamepad.buttons[5].value;
  44750. this.leftTrigger = this.browserGamepad.buttons[6].value;
  44751. this.rightTrigger = this.browserGamepad.buttons[7].value;
  44752. this.buttonBack = this.browserGamepad.buttons[8].value;
  44753. this.buttonStart = this.browserGamepad.buttons[9].value;
  44754. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  44755. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  44756. this.dPadUp = this.browserGamepad.buttons[12].value;
  44757. this.dPadDown = this.browserGamepad.buttons[13].value;
  44758. this.dPadLeft = this.browserGamepad.buttons[14].value;
  44759. this.dPadRight = this.browserGamepad.buttons[15].value;
  44760. };
  44761. return Xbox360Pad;
  44762. }(Gamepad));
  44763. BABYLON.Xbox360Pad = Xbox360Pad;
  44764. })(BABYLON || (BABYLON = {}));
  44765. var BABYLON;
  44766. (function (BABYLON) {
  44767. // We're mainly based on the logic defined into the FreeCamera code
  44768. var GamepadCamera = (function (_super) {
  44769. __extends(GamepadCamera, _super);
  44770. //-- end properties for backward compatibility for inputs
  44771. function GamepadCamera(name, position, scene) {
  44772. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  44773. _super.call(this, name, position, scene);
  44774. }
  44775. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  44776. //-- Begin properties for backward compatibility for inputs
  44777. get: function () {
  44778. var gamepad = this.inputs.attached["gamepad"];
  44779. if (gamepad)
  44780. return gamepad.gamepadAngularSensibility;
  44781. },
  44782. set: function (value) {
  44783. var gamepad = this.inputs.attached["gamepad"];
  44784. if (gamepad)
  44785. gamepad.gamepadAngularSensibility = value;
  44786. },
  44787. enumerable: true,
  44788. configurable: true
  44789. });
  44790. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  44791. get: function () {
  44792. var gamepad = this.inputs.attached["gamepad"];
  44793. if (gamepad)
  44794. return gamepad.gamepadMoveSensibility;
  44795. },
  44796. set: function (value) {
  44797. var gamepad = this.inputs.attached["gamepad"];
  44798. if (gamepad)
  44799. gamepad.gamepadMoveSensibility = value;
  44800. },
  44801. enumerable: true,
  44802. configurable: true
  44803. });
  44804. GamepadCamera.prototype.getTypeName = function () {
  44805. return "GamepadCamera";
  44806. };
  44807. return GamepadCamera;
  44808. }(BABYLON.UniversalCamera));
  44809. BABYLON.GamepadCamera = GamepadCamera;
  44810. })(BABYLON || (BABYLON = {}));
  44811. var BABYLON;
  44812. (function (BABYLON) {
  44813. var Analyser = (function () {
  44814. function Analyser(scene) {
  44815. this.SMOOTHING = 0.75;
  44816. this.FFT_SIZE = 512;
  44817. this.BARGRAPHAMPLITUDE = 256;
  44818. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  44819. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  44820. this._scene = scene;
  44821. this._audioEngine = BABYLON.Engine.audioEngine;
  44822. if (this._audioEngine.canUseWebAudio) {
  44823. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  44824. this._webAudioAnalyser.minDecibels = -140;
  44825. this._webAudioAnalyser.maxDecibels = 0;
  44826. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44827. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44828. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  44829. }
  44830. }
  44831. Analyser.prototype.getFrequencyBinCount = function () {
  44832. if (this._audioEngine.canUseWebAudio) {
  44833. return this._webAudioAnalyser.frequencyBinCount;
  44834. }
  44835. else {
  44836. return 0;
  44837. }
  44838. };
  44839. Analyser.prototype.getByteFrequencyData = function () {
  44840. if (this._audioEngine.canUseWebAudio) {
  44841. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44842. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44843. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  44844. }
  44845. return this._byteFreqs;
  44846. };
  44847. Analyser.prototype.getByteTimeDomainData = function () {
  44848. if (this._audioEngine.canUseWebAudio) {
  44849. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44850. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44851. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  44852. }
  44853. return this._byteTime;
  44854. };
  44855. Analyser.prototype.getFloatFrequencyData = function () {
  44856. if (this._audioEngine.canUseWebAudio) {
  44857. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44858. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44859. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  44860. }
  44861. return this._floatFreqs;
  44862. };
  44863. Analyser.prototype.drawDebugCanvas = function () {
  44864. var _this = this;
  44865. if (this._audioEngine.canUseWebAudio) {
  44866. if (!this._debugCanvas) {
  44867. this._debugCanvas = document.createElement("canvas");
  44868. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  44869. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  44870. this._debugCanvas.style.position = "absolute";
  44871. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  44872. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  44873. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  44874. document.body.appendChild(this._debugCanvas);
  44875. this._registerFunc = function () {
  44876. _this.drawDebugCanvas();
  44877. };
  44878. this._scene.registerBeforeRender(this._registerFunc);
  44879. }
  44880. if (this._registerFunc) {
  44881. var workingArray = this.getByteFrequencyData();
  44882. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  44883. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  44884. // Draw the frequency domain chart.
  44885. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  44886. var value = workingArray[i];
  44887. var percent = value / this.BARGRAPHAMPLITUDE;
  44888. var height = this.DEBUGCANVASSIZE.height * percent;
  44889. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  44890. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  44891. var hue = i / this.getFrequencyBinCount() * 360;
  44892. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  44893. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  44894. }
  44895. }
  44896. }
  44897. };
  44898. Analyser.prototype.stopDebugCanvas = function () {
  44899. if (this._debugCanvas) {
  44900. this._scene.unregisterBeforeRender(this._registerFunc);
  44901. this._registerFunc = null;
  44902. document.body.removeChild(this._debugCanvas);
  44903. this._debugCanvas = null;
  44904. this._debugCanvasContext = null;
  44905. }
  44906. };
  44907. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  44908. if (this._audioEngine.canUseWebAudio) {
  44909. inputAudioNode.connect(this._webAudioAnalyser);
  44910. this._webAudioAnalyser.connect(outputAudioNode);
  44911. }
  44912. };
  44913. Analyser.prototype.dispose = function () {
  44914. if (this._audioEngine.canUseWebAudio) {
  44915. this._webAudioAnalyser.disconnect();
  44916. }
  44917. };
  44918. return Analyser;
  44919. }());
  44920. BABYLON.Analyser = Analyser;
  44921. })(BABYLON || (BABYLON = {}));
  44922. var BABYLON;
  44923. (function (BABYLON) {
  44924. var DepthRenderer = (function () {
  44925. function DepthRenderer(scene, type) {
  44926. var _this = this;
  44927. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  44928. this._viewMatrix = BABYLON.Matrix.Zero();
  44929. this._projectionMatrix = BABYLON.Matrix.Zero();
  44930. this._transformMatrix = BABYLON.Matrix.Zero();
  44931. this._worldViewProjection = BABYLON.Matrix.Zero();
  44932. this._scene = scene;
  44933. var engine = scene.getEngine();
  44934. // Render target
  44935. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  44936. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44937. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44938. this._depthMap.refreshRate = 1;
  44939. this._depthMap.renderParticles = false;
  44940. this._depthMap.renderList = null;
  44941. // set default depth value to 1.0 (far away)
  44942. this._depthMap.onClearObservable.add(function (engine) {
  44943. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  44944. });
  44945. // Custom render function
  44946. var renderSubMesh = function (subMesh) {
  44947. var mesh = subMesh.getRenderingMesh();
  44948. var scene = _this._scene;
  44949. var engine = scene.getEngine();
  44950. // Culling
  44951. engine.setState(subMesh.getMaterial().backFaceCulling);
  44952. // Managing instances
  44953. var batch = mesh._getInstancesRenderList(subMesh._id);
  44954. if (batch.mustReturn) {
  44955. return;
  44956. }
  44957. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  44958. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  44959. engine.enableEffect(_this._effect);
  44960. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  44961. var material = subMesh.getMaterial();
  44962. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44963. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  44964. // Alpha test
  44965. if (material && material.needAlphaTesting()) {
  44966. var alphaTexture = material.getAlphaTestTexture();
  44967. _this._effect.setTexture("diffuseSampler", alphaTexture);
  44968. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44969. }
  44970. // Bones
  44971. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44972. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44973. }
  44974. // Draw
  44975. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  44976. }
  44977. };
  44978. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  44979. var index;
  44980. for (index = 0; index < opaqueSubMeshes.length; index++) {
  44981. renderSubMesh(opaqueSubMeshes.data[index]);
  44982. }
  44983. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  44984. renderSubMesh(alphaTestSubMeshes.data[index]);
  44985. }
  44986. };
  44987. }
  44988. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  44989. var material = subMesh.getMaterial();
  44990. if (material.disableDepthWrite) {
  44991. return false;
  44992. }
  44993. var defines = [];
  44994. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44995. var mesh = subMesh.getMesh();
  44996. var scene = mesh.getScene();
  44997. // Alpha test
  44998. if (material && material.needAlphaTesting()) {
  44999. defines.push("#define ALPHATEST");
  45000. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45001. attribs.push(BABYLON.VertexBuffer.UVKind);
  45002. defines.push("#define UV1");
  45003. }
  45004. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45005. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45006. defines.push("#define UV2");
  45007. }
  45008. }
  45009. // Bones
  45010. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45011. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45012. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45013. if (mesh.numBoneInfluencers > 4) {
  45014. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45015. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45016. }
  45017. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45018. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45019. }
  45020. else {
  45021. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45022. }
  45023. // Instances
  45024. if (useInstances) {
  45025. defines.push("#define INSTANCES");
  45026. attribs.push("world0");
  45027. attribs.push("world1");
  45028. attribs.push("world2");
  45029. attribs.push("world3");
  45030. }
  45031. // Get correct effect
  45032. var join = defines.join("\n");
  45033. if (this._cachedDefines !== join) {
  45034. this._cachedDefines = join;
  45035. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  45036. }
  45037. return this._effect.isReady();
  45038. };
  45039. DepthRenderer.prototype.getDepthMap = function () {
  45040. return this._depthMap;
  45041. };
  45042. // Methods
  45043. DepthRenderer.prototype.dispose = function () {
  45044. this._depthMap.dispose();
  45045. };
  45046. return DepthRenderer;
  45047. }());
  45048. BABYLON.DepthRenderer = DepthRenderer;
  45049. })(BABYLON || (BABYLON = {}));
  45050. var BABYLON;
  45051. (function (BABYLON) {
  45052. var SSAORenderingPipeline = (function (_super) {
  45053. __extends(SSAORenderingPipeline, _super);
  45054. /**
  45055. * @constructor
  45056. * @param {string} name - The rendering pipeline name
  45057. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  45058. * @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 }
  45059. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  45060. */
  45061. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  45062. var _this = this;
  45063. _super.call(this, scene.getEngine(), name);
  45064. // Members
  45065. /**
  45066. * The PassPostProcess id in the pipeline that contains the original scene color
  45067. * @type {string}
  45068. */
  45069. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  45070. /**
  45071. * The SSAO PostProcess id in the pipeline
  45072. * @type {string}
  45073. */
  45074. this.SSAORenderEffect = "SSAORenderEffect";
  45075. /**
  45076. * The horizontal blur PostProcess id in the pipeline
  45077. * @type {string}
  45078. */
  45079. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  45080. /**
  45081. * The vertical blur PostProcess id in the pipeline
  45082. * @type {string}
  45083. */
  45084. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  45085. /**
  45086. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  45087. * @type {string}
  45088. */
  45089. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  45090. /**
  45091. * The output strength of the SSAO post-process. Default value is 1.0.
  45092. * @type {number}
  45093. */
  45094. this.totalStrength = 1.0;
  45095. /**
  45096. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  45097. * @type {number}
  45098. */
  45099. this.radius = 0.0001;
  45100. /**
  45101. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  45102. * Must not be equal to fallOff and superior to fallOff.
  45103. * Default value is 0.975
  45104. * @type {number}
  45105. */
  45106. this.area = 0.0075;
  45107. /**
  45108. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  45109. * Must not be equal to area and inferior to area.
  45110. * Default value is 0.0
  45111. * @type {number}
  45112. */
  45113. this.fallOff = 0.000001;
  45114. /**
  45115. * The base color of the SSAO post-process
  45116. * The final result is "base + ssao" between [0, 1]
  45117. * @type {number}
  45118. */
  45119. this.base = 0.5;
  45120. this._firstUpdate = true;
  45121. this._scene = scene;
  45122. // Set up assets
  45123. this._createRandomTexture();
  45124. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  45125. var ssaoRatio = ratio.ssaoRatio || ratio;
  45126. var combineRatio = ratio.combineRatio || ratio;
  45127. this._ratio = {
  45128. ssaoRatio: ssaoRatio,
  45129. combineRatio: combineRatio
  45130. };
  45131. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45132. this._createSSAOPostProcess(ssaoRatio);
  45133. this._createBlurPostProcess(ssaoRatio);
  45134. this._createSSAOCombinePostProcess(combineRatio);
  45135. // Set up pipeline
  45136. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  45137. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  45138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  45139. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  45140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  45141. // Finish
  45142. scene.postProcessRenderPipelineManager.addPipeline(this);
  45143. if (cameras)
  45144. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  45145. }
  45146. // Public Methods
  45147. /**
  45148. * Returns the horizontal blur PostProcess
  45149. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  45150. */
  45151. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  45152. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  45153. return null;
  45154. };
  45155. /**
  45156. * Returns the vertical blur PostProcess
  45157. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  45158. */
  45159. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  45160. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  45161. return null;
  45162. };
  45163. /**
  45164. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  45165. */
  45166. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  45167. if (disableDepthRender === void 0) { disableDepthRender = false; }
  45168. for (var i = 0; i < this._scene.cameras.length; i++) {
  45169. var camera = this._scene.cameras[i];
  45170. this._originalColorPostProcess.dispose(camera);
  45171. this._ssaoPostProcess.dispose(camera);
  45172. this._blurHPostProcess.dispose(camera);
  45173. this._blurVPostProcess.dispose(camera);
  45174. this._ssaoCombinePostProcess.dispose(camera);
  45175. }
  45176. this._randomTexture.dispose();
  45177. if (disableDepthRender)
  45178. this._scene.disableDepthRenderer();
  45179. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  45180. };
  45181. // Private Methods
  45182. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  45183. var _this = this;
  45184. /*
  45185. var samplerOffsets = [
  45186. -8.0, -6.0, -4.0, -2.0,
  45187. 0.0,
  45188. 2.0, 4.0, 6.0, 8.0
  45189. ];
  45190. */
  45191. var samples = 16;
  45192. var samplerOffsets = [];
  45193. for (var i = -8; i < 8; i++) {
  45194. samplerOffsets.push(i * 2);
  45195. }
  45196. 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");
  45197. this._blurHPostProcess.onApply = function (effect) {
  45198. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  45199. effect.setTexture("depthSampler", _this._depthTexture);
  45200. if (_this._firstUpdate) {
  45201. effect.setArray("samplerOffsets", samplerOffsets);
  45202. }
  45203. };
  45204. 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");
  45205. this._blurVPostProcess.onApply = function (effect) {
  45206. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  45207. effect.setTexture("depthSampler", _this._depthTexture);
  45208. if (_this._firstUpdate) {
  45209. effect.setArray("samplerOffsets", samplerOffsets);
  45210. _this._firstUpdate = false;
  45211. }
  45212. };
  45213. };
  45214. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  45215. var _this = this;
  45216. var numSamples = 16;
  45217. var sampleSphere = [
  45218. 0.5381, 0.1856, -0.4319,
  45219. 0.1379, 0.2486, 0.4430,
  45220. 0.3371, 0.5679, -0.0057,
  45221. -0.6999, -0.0451, -0.0019,
  45222. 0.0689, -0.1598, -0.8547,
  45223. 0.0560, 0.0069, -0.1843,
  45224. -0.0146, 0.1402, 0.0762,
  45225. 0.0100, -0.1924, -0.0344,
  45226. -0.3577, -0.5301, -0.4358,
  45227. -0.3169, 0.1063, 0.0158,
  45228. 0.0103, -0.5869, 0.0046,
  45229. -0.0897, -0.4940, 0.3287,
  45230. 0.7119, -0.0154, -0.0918,
  45231. -0.0533, 0.0596, -0.5411,
  45232. 0.0352, -0.0631, 0.5460,
  45233. -0.4776, 0.2847, -0.0271
  45234. ];
  45235. var samplesFactor = 1.0 / numSamples;
  45236. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  45237. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  45238. "area", "fallOff", "base", "range", "viewport"
  45239. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  45240. var viewport = new BABYLON.Vector2(0, 0);
  45241. this._ssaoPostProcess.onApply = function (effect) {
  45242. if (_this._firstUpdate) {
  45243. effect.setArray3("sampleSphere", sampleSphere);
  45244. effect.setFloat("samplesFactor", samplesFactor);
  45245. effect.setFloat("randTextureTiles", 4.0);
  45246. }
  45247. effect.setFloat("totalStrength", _this.totalStrength);
  45248. effect.setFloat("radius", _this.radius);
  45249. effect.setFloat("area", _this.area);
  45250. effect.setFloat("fallOff", _this.fallOff);
  45251. effect.setFloat("base", _this.base);
  45252. effect.setTexture("textureSampler", _this._depthTexture);
  45253. effect.setTexture("randomSampler", _this._randomTexture);
  45254. };
  45255. };
  45256. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  45257. var _this = this;
  45258. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  45259. this._ssaoCombinePostProcess.onApply = function (effect) {
  45260. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  45261. };
  45262. };
  45263. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  45264. var size = 512;
  45265. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  45266. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  45267. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  45268. var context = this._randomTexture.getContext();
  45269. var rand = function (min, max) {
  45270. return Math.random() * (max - min) + min;
  45271. };
  45272. var randVector = BABYLON.Vector3.Zero();
  45273. for (var x = 0; x < size; x++) {
  45274. for (var y = 0; y < size; y++) {
  45275. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  45276. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  45277. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  45278. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  45279. context.fillRect(x, y, 1, 1);
  45280. }
  45281. }
  45282. this._randomTexture.update(false);
  45283. };
  45284. __decorate([
  45285. BABYLON.serialize()
  45286. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  45287. __decorate([
  45288. BABYLON.serialize()
  45289. ], SSAORenderingPipeline.prototype, "radius", void 0);
  45290. __decorate([
  45291. BABYLON.serialize()
  45292. ], SSAORenderingPipeline.prototype, "area", void 0);
  45293. __decorate([
  45294. BABYLON.serialize()
  45295. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  45296. __decorate([
  45297. BABYLON.serialize()
  45298. ], SSAORenderingPipeline.prototype, "base", void 0);
  45299. __decorate([
  45300. BABYLON.serialize()
  45301. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  45302. return SSAORenderingPipeline;
  45303. }(BABYLON.PostProcessRenderPipeline));
  45304. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  45305. })(BABYLON || (BABYLON = {}));
  45306. var BABYLON;
  45307. (function (BABYLON) {
  45308. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  45309. var VolumetricLightScatteringPostProcess = (function (_super) {
  45310. __extends(VolumetricLightScatteringPostProcess, _super);
  45311. /**
  45312. * @constructor
  45313. * @param {string} name - The post-process name
  45314. * @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)
  45315. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  45316. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  45317. * @param {number} samples - The post-process quality, default 100
  45318. * @param {number} samplingMode - The post-process filtering mode
  45319. * @param {BABYLON.Engine} engine - The babylon engine
  45320. * @param {boolean} reusable - If the post-process is reusable
  45321. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  45322. */
  45323. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  45324. var _this = this;
  45325. if (samples === void 0) { samples = 100; }
  45326. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45327. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  45328. this._screenCoordinates = BABYLON.Vector2.Zero();
  45329. /**
  45330. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  45331. * @type {Vector3}
  45332. */
  45333. this.customMeshPosition = BABYLON.Vector3.Zero();
  45334. /**
  45335. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  45336. * @type {boolean}
  45337. */
  45338. this.useCustomMeshPosition = false;
  45339. /**
  45340. * If the post-process should inverse the light scattering direction
  45341. * @type {boolean}
  45342. */
  45343. this.invert = true;
  45344. /**
  45345. * Array containing the excluded meshes not rendered in the internal pass
  45346. */
  45347. this.excludedMeshes = new Array();
  45348. /**
  45349. * Controls the overall intensity of the post-process
  45350. * @type {number}
  45351. */
  45352. this.exposure = 0.3;
  45353. /**
  45354. * Dissipates each sample's contribution in range [0, 1]
  45355. * @type {number}
  45356. */
  45357. this.decay = 0.96815;
  45358. /**
  45359. * Controls the overall intensity of each sample
  45360. * @type {number}
  45361. */
  45362. this.weight = 0.58767;
  45363. /**
  45364. * Controls the density of each sample
  45365. * @type {number}
  45366. */
  45367. this.density = 0.926;
  45368. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  45369. var engine = scene.getEngine();
  45370. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  45371. // Configure mesh
  45372. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  45373. // Configure
  45374. this._createPass(scene, ratio.passRatio || ratio);
  45375. this.onActivate = function (camera) {
  45376. if (!_this.isSupported) {
  45377. _this.dispose(camera);
  45378. }
  45379. _this.onActivate = null;
  45380. };
  45381. this.onApplyObservable.add(function (effect) {
  45382. _this._updateMeshScreenCoordinates(scene);
  45383. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  45384. effect.setFloat("exposure", _this.exposure);
  45385. effect.setFloat("decay", _this.decay);
  45386. effect.setFloat("weight", _this.weight);
  45387. effect.setFloat("density", _this.density);
  45388. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  45389. });
  45390. }
  45391. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  45392. get: function () {
  45393. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  45394. return false;
  45395. },
  45396. set: function (useDiffuseColor) {
  45397. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  45398. },
  45399. enumerable: true,
  45400. configurable: true
  45401. });
  45402. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  45403. var mesh = subMesh.getMesh();
  45404. // Render this.mesh as default
  45405. if (mesh === this.mesh) {
  45406. return mesh.material.isReady(mesh);
  45407. }
  45408. var defines = [];
  45409. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45410. var material = subMesh.getMaterial();
  45411. var needUV = false;
  45412. // Alpha test
  45413. if (material) {
  45414. if (material.needAlphaTesting()) {
  45415. defines.push("#define ALPHATEST");
  45416. }
  45417. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45418. attribs.push(BABYLON.VertexBuffer.UVKind);
  45419. defines.push("#define UV1");
  45420. }
  45421. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45422. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45423. defines.push("#define UV2");
  45424. }
  45425. }
  45426. // Bones
  45427. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45428. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45429. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45430. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45431. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45432. }
  45433. else {
  45434. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45435. }
  45436. // Instances
  45437. if (useInstances) {
  45438. defines.push("#define INSTANCES");
  45439. attribs.push("world0");
  45440. attribs.push("world1");
  45441. attribs.push("world2");
  45442. attribs.push("world3");
  45443. }
  45444. // Get correct effect
  45445. var join = defines.join("\n");
  45446. if (this._cachedDefines !== join) {
  45447. this._cachedDefines = join;
  45448. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  45449. }
  45450. return this._volumetricLightScatteringPass.isReady();
  45451. };
  45452. /**
  45453. * Sets the new light position for light scattering effect
  45454. * @param {BABYLON.Vector3} The new custom light position
  45455. */
  45456. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  45457. this.customMeshPosition = position;
  45458. };
  45459. /**
  45460. * Returns the light position for light scattering effect
  45461. * @return {BABYLON.Vector3} The custom light position
  45462. */
  45463. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  45464. return this.customMeshPosition;
  45465. };
  45466. /**
  45467. * Disposes the internal assets and detaches the post-process from the camera
  45468. */
  45469. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  45470. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  45471. if (rttIndex !== -1) {
  45472. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  45473. }
  45474. this._volumetricLightScatteringRTT.dispose();
  45475. _super.prototype.dispose.call(this, camera);
  45476. };
  45477. /**
  45478. * Returns the render target texture used by the post-process
  45479. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  45480. */
  45481. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  45482. return this._volumetricLightScatteringRTT;
  45483. };
  45484. // Private methods
  45485. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  45486. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  45487. return true;
  45488. }
  45489. return false;
  45490. };
  45491. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  45492. var _this = this;
  45493. var engine = scene.getEngine();
  45494. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  45495. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45496. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45497. this._volumetricLightScatteringRTT.renderList = null;
  45498. this._volumetricLightScatteringRTT.renderParticles = false;
  45499. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  45500. // Custom render function for submeshes
  45501. var renderSubMesh = function (subMesh) {
  45502. var mesh = subMesh.getRenderingMesh();
  45503. if (_this._meshExcluded(mesh)) {
  45504. return;
  45505. }
  45506. var scene = mesh.getScene();
  45507. var engine = scene.getEngine();
  45508. // Culling
  45509. engine.setState(subMesh.getMaterial().backFaceCulling);
  45510. // Managing instances
  45511. var batch = mesh._getInstancesRenderList(subMesh._id);
  45512. if (batch.mustReturn) {
  45513. return;
  45514. }
  45515. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  45516. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  45517. var effect = _this._volumetricLightScatteringPass;
  45518. if (mesh === _this.mesh) {
  45519. effect = subMesh.getMaterial().getEffect();
  45520. }
  45521. engine.enableEffect(effect);
  45522. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  45523. if (mesh === _this.mesh) {
  45524. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  45525. }
  45526. else {
  45527. var material = subMesh.getMaterial();
  45528. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  45529. // Alpha test
  45530. if (material && material.needAlphaTesting()) {
  45531. var alphaTexture = material.getAlphaTestTexture();
  45532. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  45533. if (alphaTexture) {
  45534. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45535. }
  45536. }
  45537. // Bones
  45538. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45539. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45540. }
  45541. }
  45542. // Draw
  45543. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  45544. }
  45545. };
  45546. // Render target texture callbacks
  45547. var savedSceneClearColor;
  45548. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  45549. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  45550. savedSceneClearColor = scene.clearColor;
  45551. scene.clearColor = sceneClearColor;
  45552. });
  45553. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  45554. scene.clearColor = savedSceneClearColor;
  45555. });
  45556. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  45557. var engine = scene.getEngine();
  45558. var index;
  45559. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45560. renderSubMesh(opaqueSubMeshes.data[index]);
  45561. }
  45562. engine.setAlphaTesting(true);
  45563. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45564. renderSubMesh(alphaTestSubMeshes.data[index]);
  45565. }
  45566. engine.setAlphaTesting(false);
  45567. if (transparentSubMeshes.length) {
  45568. // Sort sub meshes
  45569. for (index = 0; index < transparentSubMeshes.length; index++) {
  45570. var submesh = transparentSubMeshes.data[index];
  45571. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  45572. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  45573. }
  45574. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  45575. sortedArray.sort(function (a, b) {
  45576. // Alpha index first
  45577. if (a._alphaIndex > b._alphaIndex) {
  45578. return 1;
  45579. }
  45580. if (a._alphaIndex < b._alphaIndex) {
  45581. return -1;
  45582. }
  45583. // Then distance to camera
  45584. if (a._distanceToCamera < b._distanceToCamera) {
  45585. return 1;
  45586. }
  45587. if (a._distanceToCamera > b._distanceToCamera) {
  45588. return -1;
  45589. }
  45590. return 0;
  45591. });
  45592. // Render sub meshes
  45593. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45594. for (index = 0; index < sortedArray.length; index++) {
  45595. renderSubMesh(sortedArray[index]);
  45596. }
  45597. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45598. }
  45599. };
  45600. };
  45601. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  45602. var transform = scene.getTransformMatrix();
  45603. var meshPosition;
  45604. if (this.useCustomMeshPosition) {
  45605. meshPosition = this.customMeshPosition;
  45606. }
  45607. else if (this.attachedNode) {
  45608. meshPosition = this.attachedNode.position;
  45609. }
  45610. else {
  45611. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  45612. }
  45613. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  45614. this._screenCoordinates.x = pos.x / this._viewPort.width;
  45615. this._screenCoordinates.y = pos.y / this._viewPort.height;
  45616. if (this.invert)
  45617. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  45618. };
  45619. // Static methods
  45620. /**
  45621. * Creates a default mesh for the Volumeric Light Scattering post-process
  45622. * @param {string} The mesh name
  45623. * @param {BABYLON.Scene} The scene where to create the mesh
  45624. * @return {BABYLON.Mesh} the default mesh
  45625. */
  45626. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  45627. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  45628. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  45629. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  45630. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  45631. mesh.material = material;
  45632. return mesh;
  45633. };
  45634. __decorate([
  45635. BABYLON.serializeAsVector3()
  45636. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  45637. __decorate([
  45638. BABYLON.serialize()
  45639. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  45640. __decorate([
  45641. BABYLON.serialize()
  45642. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  45643. __decorate([
  45644. BABYLON.serializeAsMeshReference()
  45645. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  45646. __decorate([
  45647. BABYLON.serialize()
  45648. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  45649. __decorate([
  45650. BABYLON.serialize()
  45651. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  45652. __decorate([
  45653. BABYLON.serialize()
  45654. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  45655. __decorate([
  45656. BABYLON.serialize()
  45657. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  45658. __decorate([
  45659. BABYLON.serialize()
  45660. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  45661. return VolumetricLightScatteringPostProcess;
  45662. }(BABYLON.PostProcess));
  45663. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  45664. })(BABYLON || (BABYLON = {}));
  45665. // BABYLON.JS Chromatic Aberration GLSL Shader
  45666. // Author: Olivier Guyot
  45667. // Separates very slightly R, G and B colors on the edges of the screen
  45668. // Inspired by Francois Tarlier & Martins Upitis
  45669. var BABYLON;
  45670. (function (BABYLON) {
  45671. var LensRenderingPipeline = (function (_super) {
  45672. __extends(LensRenderingPipeline, _super);
  45673. /**
  45674. * @constructor
  45675. *
  45676. * Effect parameters are as follow:
  45677. * {
  45678. * chromatic_aberration: number; // from 0 to x (1 for realism)
  45679. * edge_blur: number; // from 0 to x (1 for realism)
  45680. * distortion: number; // from 0 to x (1 for realism)
  45681. * grain_amount: number; // from 0 to 1
  45682. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  45683. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  45684. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  45685. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  45686. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  45687. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  45688. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  45689. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  45690. * }
  45691. * Note: if an effect parameter is unset, effect is disabled
  45692. *
  45693. * @param {string} name - The rendering pipeline name
  45694. * @param {object} parameters - An object containing all parameters (see above)
  45695. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  45696. * @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)
  45697. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  45698. */
  45699. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  45700. var _this = this;
  45701. if (ratio === void 0) { ratio = 1.0; }
  45702. _super.call(this, scene.getEngine(), name);
  45703. // Lens effects can be of the following:
  45704. // - chromatic aberration (slight shift of RGB colors)
  45705. // - blur on the edge of the lens
  45706. // - lens distortion
  45707. // - depth-of-field blur & highlights enhancing
  45708. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  45709. // - grain effect (noise or custom texture)
  45710. // Two additional texture samplers are needed:
  45711. // - depth map (for depth-of-field)
  45712. // - grain texture
  45713. /**
  45714. * The chromatic aberration PostProcess id in the pipeline
  45715. * @type {string}
  45716. */
  45717. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  45718. /**
  45719. * The highlights enhancing PostProcess id in the pipeline
  45720. * @type {string}
  45721. */
  45722. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  45723. /**
  45724. * The depth-of-field PostProcess id in the pipeline
  45725. * @type {string}
  45726. */
  45727. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  45728. this._scene = scene;
  45729. // Fetch texture samplers
  45730. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  45731. if (parameters.grain_texture) {
  45732. this._grainTexture = parameters.grain_texture;
  45733. }
  45734. else {
  45735. this._createGrainTexture();
  45736. }
  45737. // save parameters
  45738. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  45739. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  45740. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  45741. this._distortion = parameters.distortion ? parameters.distortion : 0;
  45742. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  45743. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  45744. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  45745. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  45746. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  45747. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  45748. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  45749. // Create effects
  45750. this._createChromaticAberrationPostProcess(ratio);
  45751. this._createHighlightsPostProcess(ratio);
  45752. this._createDepthOfFieldPostProcess(ratio / 4);
  45753. // Set up pipeline
  45754. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  45755. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  45756. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  45757. if (this._highlightsGain === -1) {
  45758. this._disableEffect(this.HighlightsEnhancingEffect, null);
  45759. }
  45760. // Finish
  45761. scene.postProcessRenderPipelineManager.addPipeline(this);
  45762. if (cameras) {
  45763. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  45764. }
  45765. }
  45766. // public methods (self explanatory)
  45767. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  45768. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  45769. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  45770. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  45771. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  45772. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  45773. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  45774. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  45775. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  45776. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  45777. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  45778. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  45779. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  45780. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  45781. };
  45782. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  45783. this._highlightsPostProcess.updateEffect();
  45784. };
  45785. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  45786. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  45787. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  45788. this._highlightsGain = amount;
  45789. };
  45790. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  45791. if (this._highlightsGain === -1) {
  45792. this._highlightsGain = 1.0;
  45793. }
  45794. this._highlightsThreshold = amount;
  45795. };
  45796. LensRenderingPipeline.prototype.disableHighlights = function () {
  45797. this._highlightsGain = -1;
  45798. };
  45799. /**
  45800. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  45801. */
  45802. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  45803. if (disableDepthRender === void 0) { disableDepthRender = false; }
  45804. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  45805. this._chromaticAberrationPostProcess = undefined;
  45806. this._highlightsPostProcess = undefined;
  45807. this._depthOfFieldPostProcess = undefined;
  45808. this._grainTexture.dispose();
  45809. if (disableDepthRender)
  45810. this._scene.disableDepthRenderer();
  45811. };
  45812. // colors shifting and distortion
  45813. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  45814. var _this = this;
  45815. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  45816. [], // samplers
  45817. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  45818. this._chromaticAberrationPostProcess.onApply = function (effect) {
  45819. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  45820. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  45821. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  45822. };
  45823. };
  45824. // highlights enhancing
  45825. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  45826. var _this = this;
  45827. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  45828. [], // samplers
  45829. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  45830. this._highlightsPostProcess.onApply = function (effect) {
  45831. effect.setFloat('gain', _this._highlightsGain);
  45832. effect.setFloat('threshold', _this._highlightsThreshold);
  45833. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  45834. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  45835. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  45836. };
  45837. };
  45838. // colors shifting and distortion
  45839. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  45840. var _this = this;
  45841. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  45842. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  45843. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  45844. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  45845. this._depthOfFieldPostProcess.onApply = function (effect) {
  45846. effect.setTexture("depthSampler", _this._depthTexture);
  45847. effect.setTexture("grainSampler", _this._grainTexture);
  45848. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  45849. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  45850. effect.setFloat('grain_amount', _this._grainAmount);
  45851. effect.setBool('blur_noise', _this._blurNoise);
  45852. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  45853. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  45854. effect.setFloat('distortion', _this._distortion);
  45855. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  45856. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  45857. effect.setFloat('aperture', _this._dofAperture);
  45858. effect.setFloat('darken', _this._dofDarken);
  45859. effect.setFloat('edge_blur', _this._edgeBlur);
  45860. effect.setBool('highlights', (_this._highlightsGain !== -1));
  45861. effect.setFloat('near', _this._scene.activeCamera.minZ);
  45862. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  45863. };
  45864. };
  45865. // creates a black and white random noise texture, 512x512
  45866. LensRenderingPipeline.prototype._createGrainTexture = function () {
  45867. var size = 512;
  45868. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45869. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  45870. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  45871. var context = this._grainTexture.getContext();
  45872. var rand = function (min, max) {
  45873. return Math.random() * (max - min) + min;
  45874. };
  45875. var value;
  45876. for (var x = 0; x < size; x++) {
  45877. for (var y = 0; y < size; y++) {
  45878. value = Math.floor(rand(0.42, 0.58) * 255);
  45879. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  45880. context.fillRect(x, y, 1, 1);
  45881. }
  45882. }
  45883. this._grainTexture.update(false);
  45884. };
  45885. return LensRenderingPipeline;
  45886. }(BABYLON.PostProcessRenderPipeline));
  45887. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  45888. })(BABYLON || (BABYLON = {}));
  45889. //
  45890. // This post-process allows the modification of rendered colors by using
  45891. // a 'look-up table' (LUT). This effect is also called Color Grading.
  45892. //
  45893. // The object needs to be provided an url to a texture containing the color
  45894. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  45895. // Use an image editing software to tweak the LUT to match your needs.
  45896. //
  45897. // For an example of a color LUT, see here:
  45898. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  45899. // For explanations on color grading, see here:
  45900. // http://udn.epicgames.com/Three/ColorGrading.html
  45901. //
  45902. var BABYLON;
  45903. (function (BABYLON) {
  45904. var ColorCorrectionPostProcess = (function (_super) {
  45905. __extends(ColorCorrectionPostProcess, _super);
  45906. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  45907. var _this = this;
  45908. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  45909. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  45910. this._colorTableTexture.anisotropicFilteringLevel = 1;
  45911. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45912. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45913. this.onApply = function (effect) {
  45914. effect.setTexture("colorTable", _this._colorTableTexture);
  45915. };
  45916. }
  45917. return ColorCorrectionPostProcess;
  45918. }(BABYLON.PostProcess));
  45919. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  45920. })(BABYLON || (BABYLON = {}));
  45921. var BABYLON;
  45922. (function (BABYLON) {
  45923. var AnaglyphFreeCamera = (function (_super) {
  45924. __extends(AnaglyphFreeCamera, _super);
  45925. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  45926. _super.call(this, name, position, scene);
  45927. this.interaxialDistance = interaxialDistance;
  45928. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  45929. }
  45930. AnaglyphFreeCamera.prototype.getTypeName = function () {
  45931. return "AnaglyphFreeCamera";
  45932. };
  45933. return AnaglyphFreeCamera;
  45934. }(BABYLON.FreeCamera));
  45935. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  45936. var AnaglyphArcRotateCamera = (function (_super) {
  45937. __extends(AnaglyphArcRotateCamera, _super);
  45938. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  45939. _super.call(this, name, alpha, beta, radius, target, scene);
  45940. this.interaxialDistance = interaxialDistance;
  45941. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  45942. }
  45943. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  45944. return "AnaglyphArcRotateCamera";
  45945. };
  45946. return AnaglyphArcRotateCamera;
  45947. }(BABYLON.ArcRotateCamera));
  45948. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  45949. var AnaglyphGamepadCamera = (function (_super) {
  45950. __extends(AnaglyphGamepadCamera, _super);
  45951. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  45952. _super.call(this, name, position, scene);
  45953. this.interaxialDistance = interaxialDistance;
  45954. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  45955. }
  45956. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  45957. return "AnaglyphGamepadCamera";
  45958. };
  45959. return AnaglyphGamepadCamera;
  45960. }(BABYLON.GamepadCamera));
  45961. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  45962. var AnaglyphUniversalCamera = (function (_super) {
  45963. __extends(AnaglyphUniversalCamera, _super);
  45964. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  45965. _super.call(this, name, position, scene);
  45966. this.interaxialDistance = interaxialDistance;
  45967. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  45968. }
  45969. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  45970. return "AnaglyphUniversalCamera";
  45971. };
  45972. return AnaglyphUniversalCamera;
  45973. }(BABYLON.UniversalCamera));
  45974. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  45975. var StereoscopicFreeCamera = (function (_super) {
  45976. __extends(StereoscopicFreeCamera, _super);
  45977. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  45978. _super.call(this, name, position, scene);
  45979. this.interaxialDistance = interaxialDistance;
  45980. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  45981. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  45982. }
  45983. StereoscopicFreeCamera.prototype.getTypeName = function () {
  45984. return "StereoscopicFreeCamera";
  45985. };
  45986. return StereoscopicFreeCamera;
  45987. }(BABYLON.FreeCamera));
  45988. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  45989. var StereoscopicArcRotateCamera = (function (_super) {
  45990. __extends(StereoscopicArcRotateCamera, _super);
  45991. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  45992. _super.call(this, name, alpha, beta, radius, target, scene);
  45993. this.interaxialDistance = interaxialDistance;
  45994. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  45995. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  45996. }
  45997. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  45998. return "StereoscopicArcRotateCamera";
  45999. };
  46000. return StereoscopicArcRotateCamera;
  46001. }(BABYLON.ArcRotateCamera));
  46002. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  46003. var StereoscopicGamepadCamera = (function (_super) {
  46004. __extends(StereoscopicGamepadCamera, _super);
  46005. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46006. _super.call(this, name, position, scene);
  46007. this.interaxialDistance = interaxialDistance;
  46008. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46009. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46010. }
  46011. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  46012. return "StereoscopicGamepadCamera";
  46013. };
  46014. return StereoscopicGamepadCamera;
  46015. }(BABYLON.GamepadCamera));
  46016. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  46017. var StereoscopicUniversalCamera = (function (_super) {
  46018. __extends(StereoscopicUniversalCamera, _super);
  46019. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46020. _super.call(this, name, position, scene);
  46021. this.interaxialDistance = interaxialDistance;
  46022. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46023. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46024. }
  46025. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  46026. return "StereoscopicUniversalCamera";
  46027. };
  46028. return StereoscopicUniversalCamera;
  46029. }(BABYLON.UniversalCamera));
  46030. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  46031. })(BABYLON || (BABYLON = {}));
  46032. var BABYLON;
  46033. (function (BABYLON) {
  46034. var HDRRenderingPipeline = (function (_super) {
  46035. __extends(HDRRenderingPipeline, _super);
  46036. /**
  46037. * @constructor
  46038. * @param {string} name - The rendering pipeline name
  46039. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46040. * @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)
  46041. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  46042. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46043. */
  46044. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  46045. var _this = this;
  46046. if (originalPostProcess === void 0) { originalPostProcess = null; }
  46047. _super.call(this, scene.getEngine(), name);
  46048. /**
  46049. * Public members
  46050. */
  46051. // Gaussian Blur
  46052. /**
  46053. * Gaussian blur coefficient
  46054. * @type {number}
  46055. */
  46056. this.gaussCoeff = 0.3;
  46057. /**
  46058. * Gaussian blur mean
  46059. * @type {number}
  46060. */
  46061. this.gaussMean = 1.0;
  46062. /**
  46063. * Gaussian blur standard deviation
  46064. * @type {number}
  46065. */
  46066. this.gaussStandDev = 0.8;
  46067. /**
  46068. * Gaussian blur multiplier. Multiplies the blur effect
  46069. * @type {number}
  46070. */
  46071. this.gaussMultiplier = 4.0;
  46072. // HDR
  46073. /**
  46074. * Exposure, controls the overall intensity of the pipeline
  46075. * @type {number}
  46076. */
  46077. this.exposure = 1.0;
  46078. /**
  46079. * Minimum luminance that the post-process can output. Luminance is >= 0
  46080. * @type {number}
  46081. */
  46082. this.minimumLuminance = 1.0;
  46083. /**
  46084. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  46085. * @type {number}
  46086. */
  46087. this.maximumLuminance = 1e20;
  46088. /**
  46089. * Increase rate for luminance: eye adaptation speed to dark
  46090. * @type {number}
  46091. */
  46092. this.luminanceIncreaserate = 0.5;
  46093. /**
  46094. * Decrease rate for luminance: eye adaptation speed to bright
  46095. * @type {number}
  46096. */
  46097. this.luminanceDecreaseRate = 0.5;
  46098. // Bright pass
  46099. /**
  46100. * Minimum luminance needed to compute HDR
  46101. * @type {number}
  46102. */
  46103. this.brightThreshold = 0.8;
  46104. this._needUpdate = true;
  46105. this._scene = scene;
  46106. // Bright pass
  46107. this._createBrightPassPostProcess(scene, ratio);
  46108. // Down sample X4
  46109. this._createDownSampleX4PostProcess(scene, ratio);
  46110. // Create gaussian blur post-processes
  46111. this._createGaussianBlurPostProcess(scene, ratio);
  46112. // Texture adder
  46113. this._createTextureAdderPostProcess(scene, ratio);
  46114. // Luminance generator
  46115. this._createLuminanceGeneratorPostProcess(scene);
  46116. // HDR
  46117. this._createHDRPostProcess(scene, ratio);
  46118. // Pass postprocess
  46119. if (originalPostProcess === null) {
  46120. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46121. }
  46122. else {
  46123. this._originalPostProcess = originalPostProcess;
  46124. }
  46125. // Configure pipeline
  46126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  46127. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  46128. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  46129. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  46130. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  46131. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  46132. var addDownSamplerPostProcess = function (id) {
  46133. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  46134. };
  46135. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46136. addDownSamplerPostProcess(i);
  46137. }
  46138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  46139. // Finish
  46140. scene.postProcessRenderPipelineManager.addPipeline(this);
  46141. if (cameras !== null) {
  46142. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46143. }
  46144. this.update();
  46145. }
  46146. /**
  46147. * Tells the pipeline to update its post-processes
  46148. */
  46149. HDRRenderingPipeline.prototype.update = function () {
  46150. this._needUpdate = true;
  46151. };
  46152. /**
  46153. * Returns the current calculated luminance
  46154. */
  46155. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  46156. return this._hdrCurrentLuminance;
  46157. };
  46158. /**
  46159. * Returns the currently drawn luminance
  46160. */
  46161. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  46162. return this._hdrOutputLuminance;
  46163. };
  46164. /**
  46165. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  46166. */
  46167. HDRRenderingPipeline.prototype.dispose = function () {
  46168. this._originalPostProcess = undefined;
  46169. this._brightPassPostProcess = undefined;
  46170. this._downSampleX4PostProcess = undefined;
  46171. this._guassianBlurHPostProcess = undefined;
  46172. this._guassianBlurVPostProcess = undefined;
  46173. this._textureAdderPostProcess = undefined;
  46174. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46175. this._downSamplePostProcesses[i] = undefined;
  46176. }
  46177. this._hdrPostProcess = undefined;
  46178. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46179. };
  46180. /**
  46181. * Creates the HDR post-process and computes the luminance adaptation
  46182. */
  46183. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  46184. var _this = this;
  46185. var hdrLastLuminance = 0.0;
  46186. this._hdrOutputLuminance = -1.0;
  46187. this._hdrCurrentLuminance = 1.0;
  46188. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  46189. this._hdrPostProcess.onApply = function (effect) {
  46190. if (_this._hdrOutputLuminance < 0.0) {
  46191. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46192. }
  46193. else {
  46194. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  46195. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  46196. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  46197. }
  46198. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  46199. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  46200. }
  46201. else {
  46202. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46203. }
  46204. }
  46205. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  46206. hdrLastLuminance += scene.getEngine().getDeltaTime();
  46207. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46208. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46209. effect.setFloat("exposure", _this.exposure);
  46210. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  46211. _this._needUpdate = false;
  46212. };
  46213. };
  46214. /**
  46215. * Texture Adder post-process
  46216. */
  46217. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  46218. var _this = this;
  46219. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  46220. this._textureAdderPostProcess.onApply = function (effect) {
  46221. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46222. };
  46223. };
  46224. /**
  46225. * Down sample X4 post-process
  46226. */
  46227. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  46228. var _this = this;
  46229. var downSampleX4Offsets = new Array(32);
  46230. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  46231. this._downSampleX4PostProcess.onApply = function (effect) {
  46232. if (_this._needUpdate) {
  46233. var id = 0;
  46234. for (var i = -2; i < 2; i++) {
  46235. for (var j = -2; j < 2; j++) {
  46236. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  46237. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  46238. id += 2;
  46239. }
  46240. }
  46241. }
  46242. effect.setArray2("dsOffsets", downSampleX4Offsets);
  46243. };
  46244. };
  46245. /**
  46246. * Bright pass post-process
  46247. */
  46248. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  46249. var _this = this;
  46250. var brightOffsets = new Array(8);
  46251. var brightPassCallback = function (effect) {
  46252. if (_this._needUpdate) {
  46253. var sU = (1.0 / _this._brightPassPostProcess.width);
  46254. var sV = (1.0 / _this._brightPassPostProcess.height);
  46255. brightOffsets[0] = -0.5 * sU;
  46256. brightOffsets[1] = 0.5 * sV;
  46257. brightOffsets[2] = 0.5 * sU;
  46258. brightOffsets[3] = 0.5 * sV;
  46259. brightOffsets[4] = -0.5 * sU;
  46260. brightOffsets[5] = -0.5 * sV;
  46261. brightOffsets[6] = 0.5 * sU;
  46262. brightOffsets[7] = -0.5 * sV;
  46263. }
  46264. effect.setArray2("dsOffsets", brightOffsets);
  46265. effect.setFloat("brightThreshold", _this.brightThreshold);
  46266. };
  46267. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  46268. this._brightPassPostProcess.onApply = brightPassCallback;
  46269. };
  46270. /**
  46271. * Luminance generator. Creates the luminance post-process and down sample post-processes
  46272. */
  46273. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  46274. var _this = this;
  46275. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  46276. var luminanceOffsets = new Array(8);
  46277. var downSampleOffsets = new Array(18);
  46278. var halfDestPixelSize;
  46279. this._downSamplePostProcesses = new Array(lumSteps);
  46280. // Utils for luminance
  46281. var luminanceUpdateSourceOffsets = function (width, height) {
  46282. var sU = (1.0 / width);
  46283. var sV = (1.0 / height);
  46284. luminanceOffsets[0] = -0.5 * sU;
  46285. luminanceOffsets[1] = 0.5 * sV;
  46286. luminanceOffsets[2] = 0.5 * sU;
  46287. luminanceOffsets[3] = 0.5 * sV;
  46288. luminanceOffsets[4] = -0.5 * sU;
  46289. luminanceOffsets[5] = -0.5 * sV;
  46290. luminanceOffsets[6] = 0.5 * sU;
  46291. luminanceOffsets[7] = -0.5 * sV;
  46292. };
  46293. var luminanceUpdateDestOffsets = function (width, height) {
  46294. var id = 0;
  46295. for (var x = -1; x < 2; x++) {
  46296. for (var y = -1; y < 2; y++) {
  46297. downSampleOffsets[id] = (x) / width;
  46298. downSampleOffsets[id + 1] = (y) / height;
  46299. id += 2;
  46300. }
  46301. }
  46302. };
  46303. // Luminance callback
  46304. var luminanceCallback = function (effect) {
  46305. if (_this._needUpdate) {
  46306. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  46307. }
  46308. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46309. effect.setArray2("lumOffsets", luminanceOffsets);
  46310. };
  46311. // Down sample callbacks
  46312. var downSampleCallback = function (indice) {
  46313. var i = indice;
  46314. return function (effect) {
  46315. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46316. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46317. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  46318. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  46319. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  46320. effect.setArray2("dsOffsets", downSampleOffsets);
  46321. };
  46322. };
  46323. var downSampleAfterRenderCallback = function (effect) {
  46324. // Unpack result
  46325. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  46326. 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);
  46327. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  46328. };
  46329. // Create luminance post-process
  46330. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  46331. 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);
  46332. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  46333. // Create down sample post-processes
  46334. for (var i = lumSteps - 2; i >= 0; i--) {
  46335. var length = Math.pow(3, i);
  46336. ratio = { width: length, height: length };
  46337. var defines = "#define DOWN_SAMPLE\n";
  46338. if (i === 0) {
  46339. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  46340. }
  46341. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  46342. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  46343. if (i === 0) {
  46344. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  46345. }
  46346. }
  46347. };
  46348. /**
  46349. * Gaussian blur post-processes. Horizontal and Vertical
  46350. */
  46351. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  46352. var _this = this;
  46353. var blurOffsetsW = new Array(9);
  46354. var blurOffsetsH = new Array(9);
  46355. var blurWeights = new Array(9);
  46356. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  46357. // Utils for gaussian blur
  46358. var calculateBlurOffsets = function (height) {
  46359. var lastOutputDimensions = {
  46360. width: scene.getEngine().getRenderWidth(),
  46361. height: scene.getEngine().getRenderHeight()
  46362. };
  46363. for (var i = 0; i < 9; i++) {
  46364. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  46365. if (height) {
  46366. blurOffsetsH[i] = value;
  46367. }
  46368. else {
  46369. blurOffsetsW[i] = value;
  46370. }
  46371. }
  46372. };
  46373. var calculateWeights = function () {
  46374. var x = 0.0;
  46375. for (var i = 0; i < 9; i++) {
  46376. x = (i - 4.0) / 4.0;
  46377. 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));
  46378. }
  46379. };
  46380. // Callback
  46381. var gaussianBlurCallback = function (height) {
  46382. return function (effect) {
  46383. if (_this._needUpdate) {
  46384. calculateWeights();
  46385. calculateBlurOffsets(height);
  46386. }
  46387. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  46388. effect.setArray("blurWeights", blurWeights);
  46389. effect.setFloat("multiplier", _this.gaussMultiplier);
  46390. };
  46391. };
  46392. // Create horizontal gaussian blur post-processes
  46393. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  46394. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  46395. // Create vertical gaussian blur post-process
  46396. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  46397. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  46398. };
  46399. // Luminance generator
  46400. HDRRenderingPipeline.LUM_STEPS = 6;
  46401. return HDRRenderingPipeline;
  46402. }(BABYLON.PostProcessRenderPipeline));
  46403. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  46404. })(BABYLON || (BABYLON = {}));
  46405. var BABYLON;
  46406. (function (BABYLON) {
  46407. var FaceAdjacencies = (function () {
  46408. function FaceAdjacencies() {
  46409. this.edges = new Array();
  46410. this.edgesConnectedCount = 0;
  46411. }
  46412. return FaceAdjacencies;
  46413. }());
  46414. var EdgesRenderer = (function () {
  46415. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  46416. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  46417. if (epsilon === void 0) { epsilon = 0.95; }
  46418. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  46419. this.edgesWidthScalerForOrthographic = 1000.0;
  46420. this.edgesWidthScalerForPerspective = 50.0;
  46421. this._linesPositions = new Array();
  46422. this._linesNormals = new Array();
  46423. this._linesIndices = new Array();
  46424. this._buffers = {};
  46425. this._checkVerticesInsteadOfIndices = false;
  46426. this._source = source;
  46427. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  46428. this._epsilon = epsilon;
  46429. this._prepareRessources();
  46430. this._generateEdgesLines();
  46431. }
  46432. EdgesRenderer.prototype._prepareRessources = function () {
  46433. if (this._lineShader) {
  46434. return;
  46435. }
  46436. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  46437. attributes: ["position", "normal"],
  46438. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  46439. });
  46440. this._lineShader.disableDepthWrite = true;
  46441. this._lineShader.backFaceCulling = false;
  46442. };
  46443. EdgesRenderer.prototype.dispose = function () {
  46444. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  46445. if (buffer) {
  46446. buffer.dispose();
  46447. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  46448. }
  46449. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  46450. if (buffer) {
  46451. buffer.dispose();
  46452. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  46453. }
  46454. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  46455. this._lineShader.dispose();
  46456. };
  46457. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  46458. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  46459. return 0;
  46460. }
  46461. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  46462. return 1;
  46463. }
  46464. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  46465. return 2;
  46466. }
  46467. return -1;
  46468. };
  46469. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  46470. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  46471. return 0;
  46472. }
  46473. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  46474. return 1;
  46475. }
  46476. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  46477. return 2;
  46478. }
  46479. return -1;
  46480. };
  46481. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  46482. var needToCreateLine;
  46483. if (edge === undefined) {
  46484. needToCreateLine = true;
  46485. }
  46486. else {
  46487. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  46488. needToCreateLine = dotProduct < this._epsilon;
  46489. }
  46490. if (needToCreateLine) {
  46491. var offset = this._linesPositions.length / 3;
  46492. var normal = p0.subtract(p1);
  46493. normal.normalize();
  46494. // Positions
  46495. this._linesPositions.push(p0.x);
  46496. this._linesPositions.push(p0.y);
  46497. this._linesPositions.push(p0.z);
  46498. this._linesPositions.push(p0.x);
  46499. this._linesPositions.push(p0.y);
  46500. this._linesPositions.push(p0.z);
  46501. this._linesPositions.push(p1.x);
  46502. this._linesPositions.push(p1.y);
  46503. this._linesPositions.push(p1.z);
  46504. this._linesPositions.push(p1.x);
  46505. this._linesPositions.push(p1.y);
  46506. this._linesPositions.push(p1.z);
  46507. // Normals
  46508. this._linesNormals.push(p1.x);
  46509. this._linesNormals.push(p1.y);
  46510. this._linesNormals.push(p1.z);
  46511. this._linesNormals.push(-1);
  46512. this._linesNormals.push(p1.x);
  46513. this._linesNormals.push(p1.y);
  46514. this._linesNormals.push(p1.z);
  46515. this._linesNormals.push(1);
  46516. this._linesNormals.push(p0.x);
  46517. this._linesNormals.push(p0.y);
  46518. this._linesNormals.push(p0.z);
  46519. this._linesNormals.push(-1);
  46520. this._linesNormals.push(p0.x);
  46521. this._linesNormals.push(p0.y);
  46522. this._linesNormals.push(p0.z);
  46523. this._linesNormals.push(1);
  46524. // Indices
  46525. this._linesIndices.push(offset);
  46526. this._linesIndices.push(offset + 1);
  46527. this._linesIndices.push(offset + 2);
  46528. this._linesIndices.push(offset);
  46529. this._linesIndices.push(offset + 2);
  46530. this._linesIndices.push(offset + 3);
  46531. }
  46532. };
  46533. EdgesRenderer.prototype._generateEdgesLines = function () {
  46534. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46535. var indices = this._source.getIndices();
  46536. // First let's find adjacencies
  46537. var adjacencies = new Array();
  46538. var faceNormals = new Array();
  46539. var index;
  46540. var faceAdjacencies;
  46541. // Prepare faces
  46542. for (index = 0; index < indices.length; index += 3) {
  46543. faceAdjacencies = new FaceAdjacencies();
  46544. var p0Index = indices[index];
  46545. var p1Index = indices[index + 1];
  46546. var p2Index = indices[index + 2];
  46547. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  46548. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  46549. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  46550. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  46551. faceNormal.normalize();
  46552. faceNormals.push(faceNormal);
  46553. adjacencies.push(faceAdjacencies);
  46554. }
  46555. // Scan
  46556. for (index = 0; index < adjacencies.length; index++) {
  46557. faceAdjacencies = adjacencies[index];
  46558. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  46559. var otherFaceAdjacencies = adjacencies[otherIndex];
  46560. if (faceAdjacencies.edgesConnectedCount === 3) {
  46561. break;
  46562. }
  46563. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  46564. continue;
  46565. }
  46566. var otherP0 = indices[otherIndex * 3];
  46567. var otherP1 = indices[otherIndex * 3 + 1];
  46568. var otherP2 = indices[otherIndex * 3 + 2];
  46569. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  46570. var otherEdgeIndex;
  46571. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  46572. continue;
  46573. }
  46574. switch (edgeIndex) {
  46575. case 0:
  46576. if (this._checkVerticesInsteadOfIndices) {
  46577. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  46578. }
  46579. else {
  46580. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  46581. }
  46582. break;
  46583. case 1:
  46584. if (this._checkVerticesInsteadOfIndices) {
  46585. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  46586. }
  46587. else {
  46588. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  46589. }
  46590. break;
  46591. case 2:
  46592. if (this._checkVerticesInsteadOfIndices) {
  46593. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  46594. }
  46595. else {
  46596. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  46597. }
  46598. break;
  46599. }
  46600. if (otherEdgeIndex === -1) {
  46601. continue;
  46602. }
  46603. faceAdjacencies.edges[edgeIndex] = otherIndex;
  46604. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  46605. faceAdjacencies.edgesConnectedCount++;
  46606. otherFaceAdjacencies.edgesConnectedCount++;
  46607. if (faceAdjacencies.edgesConnectedCount === 3) {
  46608. break;
  46609. }
  46610. }
  46611. }
  46612. }
  46613. // Create lines
  46614. for (index = 0; index < adjacencies.length; index++) {
  46615. // 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
  46616. var current = adjacencies[index];
  46617. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  46618. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  46619. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  46620. }
  46621. // Merge into a single mesh
  46622. var engine = this._source.getScene().getEngine();
  46623. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  46624. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  46625. this._ib = engine.createIndexBuffer(this._linesIndices);
  46626. this._indicesCount = this._linesIndices.length;
  46627. };
  46628. EdgesRenderer.prototype.render = function () {
  46629. if (!this._lineShader.isReady()) {
  46630. return;
  46631. }
  46632. var scene = this._source.getScene();
  46633. var engine = scene.getEngine();
  46634. this._lineShader._preBind();
  46635. // VBOs
  46636. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  46637. scene.resetCachedMaterial();
  46638. this._lineShader.setColor4("color", this._source.edgesColor);
  46639. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  46640. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  46641. }
  46642. else {
  46643. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  46644. }
  46645. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  46646. this._lineShader.bind(this._source.getWorldMatrix());
  46647. // Draw order
  46648. engine.draw(true, 0, this._indicesCount);
  46649. this._lineShader.unbind();
  46650. engine.setDepthWrite(true);
  46651. };
  46652. return EdgesRenderer;
  46653. }());
  46654. BABYLON.EdgesRenderer = EdgesRenderer;
  46655. })(BABYLON || (BABYLON = {}));
  46656. var BABYLON;
  46657. (function (BABYLON) {
  46658. (function (TonemappingOperator) {
  46659. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  46660. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  46661. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  46662. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  46663. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  46664. var TonemappingOperator = BABYLON.TonemappingOperator;
  46665. ;
  46666. var TonemapPostProcess = (function (_super) {
  46667. __extends(TonemapPostProcess, _super);
  46668. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  46669. var _this = this;
  46670. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46671. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46672. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  46673. this._operator = _operator;
  46674. this.exposureAdjustment = exposureAdjustment;
  46675. var defines = "#define ";
  46676. if (this._operator === TonemappingOperator.Hable)
  46677. defines += "HABLE_TONEMAPPING";
  46678. else if (this._operator === TonemappingOperator.Reinhard)
  46679. defines += "REINHARD_TONEMAPPING";
  46680. else if (this._operator === TonemappingOperator.HejiDawson)
  46681. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  46682. else if (this._operator === TonemappingOperator.Photographic)
  46683. defines += "PHOTOGRAPHIC_TONEMAPPING";
  46684. //sadly a second call to create the effect.
  46685. this.updateEffect(defines);
  46686. this.onApply = function (effect) {
  46687. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  46688. };
  46689. }
  46690. return TonemapPostProcess;
  46691. }(BABYLON.PostProcess));
  46692. BABYLON.TonemapPostProcess = TonemapPostProcess;
  46693. })(BABYLON || (BABYLON = {}));
  46694. var BABYLON;
  46695. (function (BABYLON) {
  46696. var ReflectionProbe = (function () {
  46697. function ReflectionProbe(name, size, scene, generateMipMaps) {
  46698. var _this = this;
  46699. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46700. this.name = name;
  46701. this._viewMatrix = BABYLON.Matrix.Identity();
  46702. this._target = BABYLON.Vector3.Zero();
  46703. this._add = BABYLON.Vector3.Zero();
  46704. this.invertYAxis = false;
  46705. this.position = BABYLON.Vector3.Zero();
  46706. this._scene = scene;
  46707. this._scene.reflectionProbes.push(this);
  46708. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  46709. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  46710. switch (faceIndex) {
  46711. case 0:
  46712. _this._add.copyFromFloats(1, 0, 0);
  46713. break;
  46714. case 1:
  46715. _this._add.copyFromFloats(-1, 0, 0);
  46716. break;
  46717. case 2:
  46718. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  46719. break;
  46720. case 3:
  46721. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  46722. break;
  46723. case 4:
  46724. _this._add.copyFromFloats(0, 0, 1);
  46725. break;
  46726. case 5:
  46727. _this._add.copyFromFloats(0, 0, -1);
  46728. break;
  46729. }
  46730. if (_this._attachedMesh) {
  46731. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  46732. }
  46733. _this.position.addToRef(_this._add, _this._target);
  46734. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  46735. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  46736. });
  46737. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  46738. scene.updateTransformMatrix(true);
  46739. });
  46740. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  46741. }
  46742. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  46743. get: function () {
  46744. return this._renderTargetTexture.refreshRate;
  46745. },
  46746. set: function (value) {
  46747. this._renderTargetTexture.refreshRate = value;
  46748. },
  46749. enumerable: true,
  46750. configurable: true
  46751. });
  46752. ReflectionProbe.prototype.getScene = function () {
  46753. return this._scene;
  46754. };
  46755. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  46756. get: function () {
  46757. return this._renderTargetTexture;
  46758. },
  46759. enumerable: true,
  46760. configurable: true
  46761. });
  46762. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  46763. get: function () {
  46764. return this._renderTargetTexture.renderList;
  46765. },
  46766. enumerable: true,
  46767. configurable: true
  46768. });
  46769. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  46770. this._attachedMesh = mesh;
  46771. };
  46772. ReflectionProbe.prototype.dispose = function () {
  46773. var index = this._scene.reflectionProbes.indexOf(this);
  46774. if (index !== -1) {
  46775. // Remove from the scene if found
  46776. this._scene.reflectionProbes.splice(index, 1);
  46777. }
  46778. if (this._renderTargetTexture) {
  46779. this._renderTargetTexture.dispose();
  46780. this._renderTargetTexture = null;
  46781. }
  46782. };
  46783. return ReflectionProbe;
  46784. }());
  46785. BABYLON.ReflectionProbe = ReflectionProbe;
  46786. })(BABYLON || (BABYLON = {}));
  46787. var BABYLON;
  46788. (function (BABYLON) {
  46789. var SolidParticle = (function () {
  46790. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, modelBoundingInfo) {
  46791. this.idx = 0; // particle global index
  46792. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  46793. this.position = BABYLON.Vector3.Zero(); // position
  46794. this.rotation = BABYLON.Vector3.Zero(); // rotation
  46795. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  46796. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  46797. this.velocity = BABYLON.Vector3.Zero(); // velocity
  46798. this.alive = true; // alive
  46799. this.isVisible = true; // visibility
  46800. this._pos = 0; // index of this particle in the global "positions" array
  46801. this.shapeId = 0; // model shape id
  46802. this.idxInShape = 0; // index of the particle in its shape id
  46803. this.idx = particleIndex;
  46804. this._pos = positionIndex;
  46805. this._model = model;
  46806. this.shapeId = shapeId;
  46807. this.idxInShape = idxInShape;
  46808. if (modelBoundingInfo) {
  46809. this._modelBoundingInfo = modelBoundingInfo;
  46810. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  46811. }
  46812. }
  46813. Object.defineProperty(SolidParticle.prototype, "scale", {
  46814. //legacy support, changed scale to scaling
  46815. get: function () {
  46816. return this.scaling;
  46817. },
  46818. set: function (scale) {
  46819. this.scaling = scale;
  46820. },
  46821. enumerable: true,
  46822. configurable: true
  46823. });
  46824. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  46825. //legacy support, changed quaternion to rotationQuaternion
  46826. get: function () {
  46827. return this.rotationQuaternion;
  46828. },
  46829. set: function (q) {
  46830. this.rotationQuaternion = q;
  46831. },
  46832. enumerable: true,
  46833. configurable: true
  46834. });
  46835. SolidParticle.prototype.intersectsMesh = function (target) {
  46836. if (!(this.isVisible && target.isVisible)) {
  46837. return false; // only visible particle and target can intersect
  46838. }
  46839. if (!this._boundingInfo || !target._boundingInfo) {
  46840. return false;
  46841. }
  46842. return this._boundingInfo.intersects(target._boundingInfo, false);
  46843. };
  46844. return SolidParticle;
  46845. }());
  46846. BABYLON.SolidParticle = SolidParticle;
  46847. var ModelShape = (function () {
  46848. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  46849. this.shapeID = id;
  46850. this._shape = shape;
  46851. this._shapeUV = shapeUV;
  46852. this._positionFunction = posFunction;
  46853. this._vertexFunction = vtxFunction;
  46854. }
  46855. return ModelShape;
  46856. }());
  46857. BABYLON.ModelShape = ModelShape;
  46858. })(BABYLON || (BABYLON = {}));
  46859. var BABYLON;
  46860. (function (BABYLON) {
  46861. /**
  46862. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  46863. */
  46864. var SolidParticleSystem = (function () {
  46865. /**
  46866. * Creates a SPS (Solid Particle System) object.
  46867. * `name` (String) is the SPS name, this will be the underlying mesh name.
  46868. * `scene` (Scene) is the scene in which the SPS is added.
  46869. * `updatable` (default true) : if the SPS must be updatable or immutable.
  46870. * `isPickable` (default false) : if the solid particles must be pickable.
  46871. * `particleIntersection` (default false) : if the solid particle intersections must be computed
  46872. */
  46873. function SolidParticleSystem(name, scene, options) {
  46874. // public members
  46875. /**
  46876. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  46877. * Example : var p = SPS.particles[i];
  46878. */
  46879. this.particles = new Array();
  46880. /**
  46881. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  46882. */
  46883. this.nbParticles = 0;
  46884. /**
  46885. * If the particles must ever face the camera (default false). Useful for planar particles.
  46886. */
  46887. this.billboard = false;
  46888. /**
  46889. * Recompute normals when adding a shape
  46890. */
  46891. this.recomputeNormals = true;
  46892. /**
  46893. * This a counter ofr your own usage. It's not set by any SPS functions.
  46894. */
  46895. this.counter = 0;
  46896. /**
  46897. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  46898. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  46899. */
  46900. this.vars = {};
  46901. this._positions = new Array();
  46902. this._indices = new Array();
  46903. this._normals = new Array();
  46904. this._colors = new Array();
  46905. this._uvs = new Array();
  46906. this._index = 0; // indices index
  46907. this._updatable = true;
  46908. this._pickable = false;
  46909. this._isVisibilityBoxLocked = false;
  46910. this._alwaysVisible = false;
  46911. this._shapeCounter = 0;
  46912. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  46913. this._color = new BABYLON.Color4(0, 0, 0, 0);
  46914. this._computeParticleColor = true;
  46915. this._computeParticleTexture = true;
  46916. this._computeParticleRotation = true;
  46917. this._computeParticleVertex = false;
  46918. this._computeBoundingBox = false;
  46919. this._cam_axisZ = BABYLON.Vector3.Zero();
  46920. this._cam_axisY = BABYLON.Vector3.Zero();
  46921. this._cam_axisX = BABYLON.Vector3.Zero();
  46922. this._axisX = BABYLON.Axis.X;
  46923. this._axisY = BABYLON.Axis.Y;
  46924. this._axisZ = BABYLON.Axis.Z;
  46925. this._camDir = BABYLON.Vector3.Zero();
  46926. this._rotMatrix = new BABYLON.Matrix();
  46927. this._invertMatrix = new BABYLON.Matrix();
  46928. this._rotated = BABYLON.Vector3.Zero();
  46929. this._quaternion = new BABYLON.Quaternion();
  46930. this._vertex = BABYLON.Vector3.Zero();
  46931. this._normal = BABYLON.Vector3.Zero();
  46932. this._yaw = 0.0;
  46933. this._pitch = 0.0;
  46934. this._roll = 0.0;
  46935. this._halfroll = 0.0;
  46936. this._halfpitch = 0.0;
  46937. this._halfyaw = 0.0;
  46938. this._sinRoll = 0.0;
  46939. this._cosRoll = 0.0;
  46940. this._sinPitch = 0.0;
  46941. this._cosPitch = 0.0;
  46942. this._sinYaw = 0.0;
  46943. this._cosYaw = 0.0;
  46944. this._w = 0.0;
  46945. this._minimum = BABYLON.Tmp.Vector3[0];
  46946. this._maximum = BABYLON.Tmp.Vector3[1];
  46947. this._scale = BABYLON.Tmp.Vector3[2];
  46948. this._translation = BABYLON.Tmp.Vector3[3];
  46949. this._particlesIntersect = false;
  46950. this.name = name;
  46951. this._scene = scene;
  46952. this._camera = scene.activeCamera;
  46953. this._pickable = options ? options.isPickable : false;
  46954. this._particlesIntersect = options ? options.particleIntersection : false;
  46955. if (options && options.updatable) {
  46956. this._updatable = options.updatable;
  46957. }
  46958. else {
  46959. this._updatable = true;
  46960. }
  46961. if (this._pickable) {
  46962. this.pickedParticles = [];
  46963. }
  46964. }
  46965. /**
  46966. * Builds the SPS underlying mesh. Returns a standard Mesh.
  46967. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  46968. */
  46969. SolidParticleSystem.prototype.buildMesh = function () {
  46970. if (this.nbParticles === 0) {
  46971. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  46972. this.addShape(triangle, 1);
  46973. triangle.dispose();
  46974. }
  46975. this._positions32 = new Float32Array(this._positions);
  46976. this._uvs32 = new Float32Array(this._uvs);
  46977. this._colors32 = new Float32Array(this._colors);
  46978. if (this.recomputeNormals) {
  46979. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  46980. }
  46981. this._normals32 = new Float32Array(this._normals);
  46982. this._fixedNormal32 = new Float32Array(this._normals);
  46983. var vertexData = new BABYLON.VertexData();
  46984. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  46985. vertexData.indices = this._indices;
  46986. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  46987. if (this._uvs32) {
  46988. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  46989. ;
  46990. }
  46991. if (this._colors32) {
  46992. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  46993. }
  46994. var mesh = new BABYLON.Mesh(this.name, this._scene);
  46995. vertexData.applyToMesh(mesh, this._updatable);
  46996. this.mesh = mesh;
  46997. this.mesh.isPickable = this._pickable;
  46998. this._wm = this.mesh.getWorldMatrix();
  46999. // free memory
  47000. this._positions = null;
  47001. this._normals = null;
  47002. this._uvs = null;
  47003. this._colors = null;
  47004. if (!this._updatable) {
  47005. this.particles.length = 0;
  47006. }
  47007. return mesh;
  47008. };
  47009. /**
  47010. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47011. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47012. * Thus the particles generated from `digest()` have their property `position` set yet.
  47013. * `mesh` ( Mesh ) is the mesh to be digested
  47014. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47015. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47016. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47017. */
  47018. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47019. var size = (options && options.facetNb) || 1;
  47020. var number = (options && options.number);
  47021. var delta = (options && options.delta) || 0;
  47022. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47023. var meshInd = mesh.getIndices();
  47024. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47025. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47026. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47027. var f = 0; // facet counter
  47028. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47029. // compute size from number
  47030. if (number) {
  47031. number = (number > totalFacets) ? totalFacets : number;
  47032. size = Math.round(totalFacets / number);
  47033. delta = 0;
  47034. }
  47035. else {
  47036. size = (size > totalFacets) ? totalFacets : size;
  47037. }
  47038. var facetPos = []; // submesh positions
  47039. var facetInd = []; // submesh indices
  47040. var facetUV = []; // submesh UV
  47041. var facetCol = []; // submesh colors
  47042. var barycenter = BABYLON.Tmp.Vector3[0];
  47043. var rand;
  47044. var sizeO = size;
  47045. while (f < totalFacets) {
  47046. size = sizeO + Math.floor((1 + delta) * Math.random());
  47047. if (f > totalFacets - size) {
  47048. size = totalFacets - f;
  47049. }
  47050. // reset temp arrays
  47051. facetPos.length = 0;
  47052. facetInd.length = 0;
  47053. facetUV.length = 0;
  47054. facetCol.length = 0;
  47055. // iterate over "size" facets
  47056. var fi = 0;
  47057. for (var j = f * 3; j < (f + size) * 3; j++) {
  47058. facetInd.push(fi);
  47059. var i = meshInd[j];
  47060. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47061. if (meshUV) {
  47062. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47063. }
  47064. if (meshCol) {
  47065. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47066. }
  47067. fi++;
  47068. }
  47069. // create a model shape for each single particle
  47070. var idx = this.nbParticles;
  47071. var shape = this._posToShape(facetPos);
  47072. var shapeUV = this._uvsToShapeUV(facetUV);
  47073. // compute the barycenter of the shape
  47074. var v;
  47075. for (v = 0; v < shape.length; v++) {
  47076. barycenter.addInPlace(shape[v]);
  47077. }
  47078. barycenter.scaleInPlace(1 / shape.length);
  47079. // shift the shape from its barycenter to the origin
  47080. for (v = 0; v < shape.length; v++) {
  47081. shape[v].subtractInPlace(barycenter);
  47082. }
  47083. var bInfo;
  47084. if (this._particlesIntersect) {
  47085. bInfo = new BABYLON.BoundingInfo(barycenter, 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, bInfo);
  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, bInfo) {
  47210. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, bInfo));
  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._wm.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._wm);
  47517. bSphere._update(this._wm);
  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=this.x,n=this.y,o=this.z,e=this.w,s=r*r,h=-2*(s+n*n)+1,a=2*(o*r+e*n),u=-2*(o*n-e*r),m=2*(r*n+e*o),y=-2*(o*o+s)+1;return u=u>1?1:u,u=u<-1?-1:u,t.x=Math.asin(u),t.z=Math.atan2(m,y),t.y=Math.atan2(a,h),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,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){return 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];\nreturn 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. };